1use std::collections::HashMap;
15use std::sync::Arc;
16
17use memstead_schema::{Schema, TypeDefinition, type_by_name};
18
19use super::{
20 DanglingLink, FoldedTag, HealthIssue, HealthReport, HealthSummary, StaleEntity,
21 TagDistribution, TagVariant, UntaggedStats,
22};
23use crate::entity::MetadataValue;
24use crate::graph::query;
25use crate::store::Store;
26
27pub const HEALTH_INCLUDE_KEYS: &[&str] = &[
33 "orphans",
34 "stubs",
35 "most_connected",
36 "missing_fields",
37 "stale",
38 "dangling_links",
39 "tags",
40 "missing_required_outgoing",
41 "constraints",
42 "signals",
43 "labelling",
44 "conformance",
45 "integrity",
46 "config",
47 "anchors",
48 "friction",
49 "open_questions",
50 "stale_derivations",
51 "checks",
52 "ledger",
53 "vital_signs",
54 "due",
55];
56
57pub const VITAL_SIGNS_ITEM_CAP: usize = 20;
59
60pub fn health_vital_signs_axis(
85 engine: &crate::engine::Engine,
86 mem_filter: Option<&str>,
87) -> serde_json::Value {
88 let cap = VITAL_SIGNS_ITEM_CAP;
89 let capped = |mut items: Vec<serde_json::Value>| -> serde_json::Value {
90 let count = items.len();
91 let more = count.saturating_sub(cap);
92 items.truncate(cap);
93 let mut o = serde_json::Map::new();
94 o.insert("count".into(), serde_json::json!(count));
95 o.insert("items".into(), serde_json::Value::Array(items));
96 if more > 0 {
97 o.insert("more".into(), serde_json::json!(more));
98 }
99 serde_json::Value::Object(o)
100 };
101
102 let mut mems: Vec<String> = engine.mem_names().iter().map(|s| s.to_string()).collect();
103 mems.sort();
104 let communities = engine.communities();
105 let mut out = serde_json::Map::new();
106 for mem in &mems {
107 if let Some(f) = mem_filter
108 && f != mem
109 {
110 continue;
111 }
112 let entities: Vec<&crate::entity::Entity> = engine
113 .store()
114 .all_entities()
115 .filter(|e| !e.stub && e.id.mem() == mem)
116 .collect();
117 let schema = engine.schema_for(mem);
118
119 let last_resort: Option<String> = schema.as_ref().and_then(|s| {
121 s.types
122 .values()
123 .find(|t| t.last_resort)
124 .map(|t| t.name.clone())
125 });
126 let type_share = match &last_resort {
127 None => serde_json::json!({ "status": "not_declared" }),
128 Some(lr) => {
129 let mut per: std::collections::BTreeMap<String, (usize, usize)> =
130 std::collections::BTreeMap::new();
131 for e in &entities {
132 let cluster = communities
133 .entity_cluster_map
134 .get(&e.id.0)
135 .cloned()
136 .unwrap_or_else(|| "unplaced".to_string());
137 let slot = per.entry(cluster).or_insert((0, 0));
138 slot.0 += 1;
139 if e.entity_type == *lr {
140 slot.1 += 1;
141 }
142 }
143 let mut rows: Vec<serde_json::Value> = per
144 .into_iter()
145 .map(|(community, (total, on_last_resort))| {
146 serde_json::json!({
147 "community": community,
148 "entities": total,
149 "on_last_resort_type": on_last_resort,
150 })
151 })
152 .collect();
153 rows.sort_by(|a, b| {
156 let share = |v: &serde_json::Value| {
157 let t = v["entities"].as_u64().unwrap_or(1).max(1) as f64;
158 v["on_last_resort_type"].as_u64().unwrap_or(0) as f64 / t
159 };
160 share(b)
161 .partial_cmp(&share(a))
162 .unwrap_or(std::cmp::Ordering::Equal)
163 .then_with(|| a["community"].as_str().cmp(&b["community"].as_str()))
164 });
165 let mut v = capped(rows);
166 v["status"] = serde_json::json!("declared");
167 v["last_resort_type"] = serde_json::json!(lr);
168 v
169 }
170 };
171
172 let mut claims: std::collections::BTreeMap<
175 String,
176 (std::collections::BTreeSet<String>, bool),
177 > = std::collections::BTreeMap::new();
178 for e in &entities {
179 for a in engine.entity_anchors(&e.id) {
180 let slot = claims.entry(a.artifact.clone()).or_default();
181 slot.0.insert(e.id.0.clone());
182 if a.class == crate::anchor::AnchorProvenanceClass::Anchored {
183 slot.1 = true;
184 }
185 }
186 }
187 let roots = engine.anchor_source_roots(mem);
188 let mut unclaimed: Vec<serde_json::Value> = Vec::new();
189 let mut sources_enumerated = 0usize;
190 if let Some(ws) = engine.workspace_root() {
191 let mut seen: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
192 for join in roots.values() {
193 sources_enumerated += 1;
194 for file in crate::source_scope::enumerate_source_artifacts(
195 engine,
196 &join.source,
197 &join.deny_paths,
198 ws,
199 ) {
200 if !seen.insert(file.clone()) || claims.contains_key(&file) {
201 continue;
202 }
203 let size = std::fs::metadata(ws.join(&file))
204 .map(|m| m.len())
205 .unwrap_or(0);
206 unclaimed.push(serde_json::json!({ "artifact": file, "bytes": size }));
207 }
208 }
209 }
210 unclaimed.sort_by(|a, b| {
211 b["bytes"]
212 .as_u64()
213 .cmp(&a["bytes"].as_u64())
214 .then_with(|| a["artifact"].as_str().cmp(&b["artifact"].as_str()))
215 });
216 let unclaimed_v = if sources_enumerated == 0 {
217 serde_json::json!({ "status": "no_bound_source" })
218 } else {
219 let mut v = capped(unclaimed);
220 v["status"] = serde_json::json!("enumerated");
221 v
222 };
223 let contested: Vec<serde_json::Value> = claims
224 .iter()
225 .filter(|(_, (who, owned))| who.len() >= 2 && !owned)
226 .map(|(artifact, (who, _))| {
227 serde_json::json!({
228 "artifact": artifact,
229 "claimed_by": who.iter().cloned().collect::<Vec<_>>(),
230 })
231 })
232 .collect();
233
234 let cluster_size = |c: &str| -> usize {
236 communities
237 .clusters
238 .get(c)
239 .map(|ci| ci.entities.len())
240 .unwrap_or(0)
241 };
242 let mut by_community: std::collections::BTreeMap<String, Vec<String>> =
243 std::collections::BTreeMap::new();
244 for e in &entities {
245 if !engine.store().outgoing(&e.id).is_empty() {
246 continue;
247 }
248 let own = communities.entity_cluster_map.get(&e.id.0).cloned();
249 let community = match own {
250 Some(c) if cluster_size(&c) > 1 => c,
251 _ => engine
252 .store()
253 .incoming(&e.id)
254 .iter()
255 .find_map(|edge| communities.entity_cluster_map.get(&edge.from.0).cloned())
256 .unwrap_or_else(|| "unplaced".to_string()),
257 };
258 by_community
259 .entry(community)
260 .or_default()
261 .push(e.id.0.clone());
262 }
263 let zero_total: usize = by_community.values().map(Vec::len).sum();
264 let zero_rows: Vec<serde_json::Value> = by_community
265 .into_iter()
266 .map(|(community, mut ids)| {
267 ids.sort();
268 let count = ids.len();
269 let more = count.saturating_sub(cap);
270 ids.truncate(cap);
271 let mut o = serde_json::json!({
272 "community": community,
273 "count": count,
274 "items": ids,
275 });
276 if more > 0 {
277 o["more"] = serde_json::json!(more);
278 }
279 o
280 })
281 .collect();
282 let mut zero_v = capped(zero_rows);
283 zero_v["entities"] = serde_json::json!(zero_total);
284
285 let mut empty_sections: Vec<serde_json::Value> = Vec::new();
287 if let Some(s) = &schema {
288 for e in &entities {
289 let Some(td) = s.types.get(&e.entity_type) else {
290 continue;
291 };
292 for sec in &td.sections {
293 if e.sections
294 .get(&sec.key)
295 .is_some_and(|body| body.trim().is_empty())
296 {
297 empty_sections.push(serde_json::json!({
298 "id": e.id.0,
299 "section": sec.key,
300 }));
301 }
302 }
303 }
304 }
305
306 out.insert(
307 mem.clone(),
308 serde_json::json!({
309 "type_share_by_community": type_share,
310 "unclaimed_source_files": unclaimed_v,
311 "contested_unowned_files": capped(contested),
312 "zero_outgoing_entities": zero_v,
313 "empty_declared_sections": capped(empty_sections),
314 }),
315 );
316 }
317 let mut top = serde_json::Map::new();
318 top.insert("_item_cap".into(), serde_json::json!(cap));
319 for (k, v) in out {
320 top.insert(k, v);
321 }
322 serde_json::Value::Object(top)
323}
324
325#[derive(Default)]
333struct CheckMaps {
334 latest: std::collections::BTreeMap<String, crate::check::CheckRecord>,
336 latest_conformance: std::collections::BTreeMap<String, crate::check::CheckRecord>,
338 foreign_by_entity: std::collections::BTreeMap<String, Vec<String>>,
341 newest_any: std::collections::BTreeMap<String, crate::check::CheckRecord>,
343 all_verification: std::collections::BTreeMap<String, Vec<crate::check::CheckRecord>>,
346}
347
348impl CheckMaps {
349 fn from_records<'a>(records: impl Iterator<Item = &'a crate::check::CheckRecord>) -> Self {
350 let mut maps = Self::default();
351 for rec in records {
352 maps.newest_any.insert(rec.entity.clone(), rec.clone());
353 match rec.resolved_kind() {
354 Some(crate::check::CheckKind::Verification) => {
355 maps.all_verification
356 .entry(rec.entity.clone())
357 .or_default()
358 .push(rec.clone());
359 maps.latest.insert(rec.entity.clone(), rec.clone());
360 }
361 Some(crate::check::CheckKind::Conformance) => {
362 maps.latest_conformance
363 .insert(rec.entity.clone(), rec.clone());
364 }
365 None => {
366 if let Some(k) = rec.foreign_kind() {
367 maps.foreign_by_entity
368 .entry(rec.entity.clone())
369 .or_default()
370 .push(k.to_string());
371 }
372 }
373 }
374 }
375 maps
376 }
377}
378
379pub fn health_checks_axis(
400 engine: &crate::engine::Engine,
401 mem_filter: Option<&str>,
402) -> serde_json::Value {
403 let cap = OPEN_QUESTIONS_ITEM_CAP;
404 let capped = |mut items: Vec<String>| -> serde_json::Value {
405 items.sort();
406 let count = items.len();
407 let more = count.saturating_sub(cap);
408 items.truncate(cap);
409 let mut o = serde_json::Map::new();
410 o.insert("count".into(), serde_json::json!(count));
411 o.insert("items".into(), serde_json::json!(items));
412 if more > 0 {
413 o.insert("more".into(), serde_json::json!(more));
414 }
415 serde_json::Value::Object(o)
416 };
417
418 let ledger_records: Vec<crate::check::CheckRecord> = engine
424 .workspace_root()
425 .map(|root| crate::check::CheckLedger::for_workspace(root).all())
426 .unwrap_or_default();
427 let from_ledger = CheckMaps::from_records(ledger_records.iter());
428
429 let mut mems: Vec<String> = engine.mem_names().iter().map(|s| s.to_string()).collect();
430 mems.sort();
431 let mut out = serde_json::Map::new();
432 for mem in mems {
433 if let Some(f) = mem_filter
434 && f != mem
435 {
436 continue;
437 }
438 let sealed_maps;
442 let (maps, sealed_note) = if engine.is_archive_mount(&mem) {
443 match engine.archive_checks_for(&mem) {
444 Some(sealed) => {
445 let records: Vec<crate::check::CheckRecord> = sealed
446 .entities
447 .iter()
448 .flat_map(|(path, kinds)| {
449 let id = crate::EntityId::new(&mem, path).0;
450 kinds.iter().map(move |(kind, sc)| sc.to_record(&id, kind))
451 })
452 .collect();
453 sealed_maps = CheckMaps::from_records(records.iter());
454 (
455 &sealed_maps,
456 Some(serde_json::json!({
457 "carried": true,
458 "records": records.len(),
459 })),
460 )
461 }
462 None => {
463 sealed_maps = CheckMaps::default();
464 (
465 &sealed_maps,
466 Some(serde_json::json!({
467 "carried": false,
468 "reason": "the archive carries no check records; every state reads never_checked",
469 })),
470 )
471 }
472 }
473 } else {
474 (&from_ledger, None)
475 };
476 let CheckMaps {
477 latest,
478 latest_conformance,
479 foreign_by_entity,
480 newest_any,
481 all_verification,
482 } = maps;
483 let mut counts = std::collections::BTreeMap::from([
484 ("never_checked", 0usize),
485 ("checked_ok", 0usize),
486 ("check_failed", 0usize),
487 ("check_stale", 0usize),
488 ]);
489 let current_pin = engine
495 .mount(&mem)
496 .and_then(|m| m.schema.as_ref())
497 .map(|s| s.as_display());
498 let mut conformance_counts = std::collections::BTreeMap::from([
499 ("never_checked", 0usize),
500 ("checked_ok", 0usize),
501 ("check_failed", 0usize),
502 ("check_stale", 0usize),
503 ]);
504 let mut self_checked: Vec<String> = Vec::new();
505 let mut confirmed_independent: Vec<String> = Vec::new();
506 let mut unconfirmable: Vec<String> = Vec::new();
507 let mut executors = serde_json::Map::new();
511 let mut readings = serde_json::Map::new();
512 let touches = engine.mem_touches(&mem);
513 let mut foreign_kinds: std::collections::BTreeMap<String, usize> =
514 std::collections::BTreeMap::new();
515 let mut findings = serde_json::Map::new();
516 for e in engine.store().all_entities().filter(|e| e.mem == mem) {
517 let id = e.id.0.clone();
518 if let Some(kinds) = foreign_by_entity.get(&id) {
519 for k in kinds {
520 *foreign_kinds.entry(k.clone()).or_insert(0) += 1;
521 }
522 }
523 if let Some(rec) = newest_any.get(&id)
524 && let Some(f) = &rec.finding
525 {
526 findings.insert(
527 id.clone(),
528 serde_json::json!({
529 "verdict": rec.verdict,
530 "kind": rec.kind.as_deref().unwrap_or("verification"),
531 "ts": rec.ts,
532 "observed_at": rec.observed_at,
533 "identity": rec.identity,
534 "origin": engine.check_row_prose_origin(&mem, &id, rec).as_wire(),
540 "finding": f,
541 }),
542 );
543 }
544 let state = crate::check::derive_state(latest.get(&id), &e.content_hash);
545 *counts.entry(state.as_str()).or_insert(0) += 1;
546 if let Some(records) = all_verification.get(&id) {
547 let rows: Vec<serde_json::Value> = records
548 .iter()
549 .map(|rec| {
550 let reading = if rec.verdict == "ok" {
551 engine.independence_of(e, rec, &touches).0.as_str()
552 } else {
553 "failed"
554 };
555 let role_confirms = matches!(
560 crate::vcs::Role::from_wire(&rec.role).unwrap_or_default(),
561 crate::vcs::Role::Checker | crate::vcs::Role::Verifier
562 );
563 serde_json::json!({
564 "ts": rec.ts,
565 "observed_at": rec.observed_at,
566 "identity": rec.identity,
567 "verdict": rec.verdict,
568 "reading": reading,
569 "role": rec.role,
570 "role_confirms": role_confirms,
571 })
572 })
573 .collect();
574 readings.insert(id.clone(), serde_json::Value::Array(rows));
575 }
576 let cstate = crate::check::derive_state_pinned(
577 latest_conformance.get(&id),
578 &e.content_hash,
579 current_pin.as_deref(),
580 );
581 *conformance_counts.entry(cstate.as_str()).or_insert(0) += 1;
582 if state != crate::check::CheckState::CheckedOk {
583 continue;
584 }
585 let check = latest.get(&id).expect("checked_ok implies a record");
595 let (reading, execs) = engine.independence_of(e, check, &touches);
596 if let Some(execs) = execs {
597 executors.insert(id.clone(), serde_json::json!(execs.identities));
598 }
599 match reading {
600 crate::engine::independence::Independence::SelfChecked => self_checked.push(id),
601 crate::engine::independence::Independence::ConfirmedIndependent => {
602 confirmed_independent.push(id)
603 }
604 crate::engine::independence::Independence::Unconfirmable => unconfirmable.push(id),
605 }
606 }
607 let mut m = serde_json::Map::new();
608 for (k, v) in counts {
609 m.insert(k.to_string(), serde_json::json!(v));
610 }
611 let mut c = serde_json::Map::new();
612 for (k, v) in conformance_counts {
613 c.insert(k.to_string(), serde_json::json!(v));
614 }
615 m.insert("conformance".into(), serde_json::Value::Object(c));
616 m.insert(
620 "foreign_kinds".into(),
621 serde_json::to_value(&foreign_kinds).unwrap_or(serde_json::json!({})),
622 );
623 m.insert("findings".into(), serde_json::Value::Object(findings));
624 if let Some(note) = sealed_note {
627 m.insert("sealed".into(), note);
628 }
629 m.insert(
630 "independence".into(),
631 serde_json::json!({
632 "self_checked": capped(self_checked),
633 "confirmed_independent": capped(confirmed_independent),
634 "unconfirmable": capped(unconfirmable),
635 "comparator": "every identity that mutated the verified plan, its criteria or its session-log notes since the criterion was written; a non-criterion compares against its own author",
636 "executors": serde_json::Value::Object(executors),
637 "readings": serde_json::Value::Object(readings),
638 }),
639 );
640 out.insert(mem, serde_json::Value::Object(m));
641 }
642 serde_json::Value::Object(out)
643}
644
645#[derive(Debug, Clone, serde::Serialize)]
651pub struct DerivationFinding {
652 pub source: crate::entity::EntityId,
653 pub rel_type: String,
654 pub target: crate::entity::EntityId,
655 pub state: String,
657 #[serde(skip_serializing_if = "Option::is_none")]
659 pub baseline: Option<String>,
660 pub current: String,
662}
663
664pub fn health_stale_derivations_axis(
669 engine: &crate::engine::Engine,
670 mem_filter: Option<&str>,
671) -> serde_json::Value {
672 let mut mems: Vec<String> = engine.mem_names().iter().map(|s| s.to_string()).collect();
673 mems.sort();
674 let mut out = serde_json::Map::new();
675 for mem in mems {
676 if let Some(f) = mem_filter
677 && f != mem
678 {
679 continue;
680 }
681 let findings = engine.derivation_report(&mem).unwrap_or_default();
682 out.insert(
683 mem,
684 serde_json::to_value(&findings).unwrap_or(serde_json::Value::Array(Vec::new())),
685 );
686 }
687 serde_json::Value::Object(out)
688}
689
690pub const OPEN_QUESTIONS_ITEM_CAP: usize = 20;
694
695pub fn health_open_questions_axis(
711 engine: &crate::engine::Engine,
712 mem_filter: Option<&str>,
713) -> serde_json::Value {
714 let cap = OPEN_QUESTIONS_ITEM_CAP;
715 let capped = |mut items: Vec<serde_json::Value>| -> serde_json::Value {
716 let count = items.len();
717 let more = count.saturating_sub(cap);
718 items.truncate(cap);
719 let mut o = serde_json::Map::new();
720 o.insert("count".into(), serde_json::json!(count));
721 o.insert("items".into(), serde_json::Value::Array(items));
722 if more > 0 {
723 o.insert("more".into(), serde_json::json!(more));
724 }
725 serde_json::Value::Object(o)
726 };
727
728 let bindings: Vec<(String, String)> = engine
732 .workspace_root()
733 .and_then(|root| crate::pipeline_store::load_pipeline_configs(root).ok())
734 .map(|c| {
735 c.bindings
736 .iter()
737 .map(|r| (r.config.destination_mem.clone(), r.name.clone()))
738 .collect()
739 })
740 .unwrap_or_default();
741 let mounted: Vec<String> = engine.mem_names().iter().map(|s| s.to_string()).collect();
742
743 let mut mems: Vec<String> = mounted.clone();
744 mems.sort();
745 let mut out = serde_json::Map::new();
746 for mem in &mems {
747 if let Some(f) = mem_filter
748 && f != mem
749 {
750 continue;
751 }
752
753 let stubs = capped(
755 engine
756 .store()
757 .all_entities()
758 .filter(|e| e.stub && e.id.mem() == mem)
759 .map(|e| serde_json::json!({ "kind": "stub", "id": e.id.to_string() }))
760 .collect(),
761 );
762
763 let (mut recheck, mut unresolvable, mut unobserved, mut dangling_rows) =
776 (Vec::new(), Vec::new(), Vec::new(), Vec::new());
777 let mut span_absent = Vec::new();
781 let mut aging = Vec::new();
784 let mut entity_end_unreconciled: Option<String> = None;
785 if let Ok(report) = engine.verify_mem_anchors(mem) {
786 entity_end_unreconciled = report.unreconciled.clone();
787 for a in &report.anchors {
788 if let Some(days) = a.unobserved_for_days
789 && days > 0
790 {
791 aging.push(serde_json::json!({
792 "kind": "anchor_aging",
793 "id": a.entity_id,
794 "artifact": a.artifact,
795 "state": a.state,
796 "observed_at": a.observed_at,
797 "unobserved_for_days": days,
798 "note": format!("unobserved for {days} days"),
799 }));
800 }
801 let item = serde_json::json!({
802 "kind": format!("anchor_{}", a.state),
803 "id": a.entity_id,
804 "artifact": a.artifact,
805 });
806 match a.state.as_str() {
807 "recheck" => recheck.push(item),
808 "orphaned" => unresolvable.push(item),
811 "span_absent" => span_absent.push(item),
812 "unobserved" => unobserved.push(item),
813 "dangling" => dangling_rows.push(item),
814 _ => {}
815 }
816 }
817 }
818
819 let constraints = capped(
822 engine
823 .constraint_findings(Some(mem))
824 .iter()
825 .map(|r| {
826 serde_json::json!({
827 "kind": "unsatisfied_constraint",
828 "id": r.id.to_string(),
829 "violations": r.violations.len(),
830 })
831 })
832 .collect(),
833 );
834
835 let dangling = capped(
841 collect_dangling_links(engine.store(), Some(mem))
842 .iter()
843 .map(|d| {
844 serde_json::json!({
845 "kind": d.kind.code(),
846 "id": d.from.to_string(),
847 "target": d.target_id.to_string(),
848 "repair": d.kind.repair(),
849 })
850 })
851 .collect(),
852 );
853
854 let mut process = Vec::new();
864 let mem_bindings: Vec<&String> = bindings
865 .iter()
866 .filter(|(d, _)| d == mem)
867 .map(|(_, b)| b)
868 .collect();
869 let mut resolutions: Vec<(Option<String>, crate::binding_run::ProcessMemResolution)> =
870 Vec::new();
871 if mem_bindings.is_empty() {
872 let r = crate::binding_run::resolve_process_mem(engine, mem, "");
873 if r.declared {
874 resolutions.push((None, r));
875 }
876 } else {
877 for binding in &mem_bindings {
878 let derived =
882 crate::binding_run::derived_process_mem_name(&format!("{mem}/{binding}"));
883 resolutions.push((
884 Some((*binding).clone()),
885 crate::binding_run::resolve_process_mem(engine, mem, &derived),
886 ));
887 }
888 }
889 for (binding, r) in resolutions {
890 if r.mounted {
891 let mut open = Vec::new();
892 let mut searched = Vec::new();
893 for e in engine
894 .store()
895 .all_entities()
896 .filter(|e| !e.stub && e.id.mem() == r.mem.as_str())
897 {
898 let item = serde_json::json!({
899 "kind": e.entity_type,
900 "id": e.id.to_string(),
901 "title": e.title,
902 });
903 if e.entity_type == "negative_finding" {
904 searched.push(item);
905 } else {
906 open.push(item);
907 }
908 }
909 let by_id = |a: &serde_json::Value, b: &serde_json::Value| {
914 a["id"].as_str().cmp(&b["id"].as_str())
915 };
916 open.sort_by(by_id);
917 searched.sort_by(by_id);
918 process.push(serde_json::json!({
919 "binding": binding,
920 "process_mem": r.mem,
921 "declared": r.declared,
922 "resolvable": true,
923 "open_entries": capped(open),
924 "already_searched": capped(searched),
925 }));
926 } else if r.declared {
927 process.push(serde_json::json!({
928 "binding": binding,
929 "process_mem": r.mem,
930 "declared": true,
931 "resolvable": false,
932 "finding": "DECLARED_PROCESS_MEM_MISSING",
933 }));
934 } else {
935 process.push(serde_json::json!({
936 "binding": binding,
937 "resolvable": false,
938 }));
939 }
940 }
941
942 let (mut missing, mut unchecked) = (Vec::new(), Vec::new());
948 if let Some(schema) = engine.schema_for(mem) {
949 for entity in engine
950 .store()
951 .all_entities()
952 .filter(|e| !e.stub && e.id.mem() == mem)
953 {
954 let Some(td) = schema.types.get(&entity.entity_type) else {
955 continue;
956 };
957 let Some(res) = &td.resolution else { continue };
958 if let Some(field) = &res.status_field {
959 let open = match entity.metadata.get(field) {
960 Some(crate::entity::MetadataValue::String(s)) => {
961 res.open_values.contains(s)
962 }
963 _ => false,
964 };
965 if !open {
966 continue;
967 }
968 }
969 let has_condition = entity
970 .sections
971 .get(&res.condition_section)
972 .is_some_and(|body| !body.trim().is_empty());
973 if !has_condition {
974 missing.push(serde_json::json!({
975 "kind": "resolution_missing",
976 "id": entity.id.to_string(),
977 "section": res.condition_section,
978 }));
979 continue;
980 }
981 let kind = res.check_kind.as_deref().unwrap_or("verification");
982 let checked = crate::check::RecordKind::from_wire(kind).is_some()
986 && engine
987 .latest_check_record(mem, &entity.id.0, kind)
988 .is_some_and(|r| r.verdict == "ok" && r.entity_hash == entity.content_hash);
989 if !checked {
990 unchecked.push(serde_json::json!({
991 "kind": "resolution_unchecked",
992 "id": entity.id.to_string(),
993 "section": res.condition_section,
994 "check_kind": kind,
995 }));
996 }
997 }
998 }
999 let resolution_missing = capped(missing);
1000 let resolution_unchecked = capped(unchecked);
1001
1002 let total_open = stubs["count"].as_u64().unwrap_or(0)
1003 + resolution_missing["count"].as_u64().unwrap_or(0)
1004 + resolution_unchecked["count"].as_u64().unwrap_or(0)
1005 + recheck.len() as u64
1006 + unresolvable.len() as u64
1007 + span_absent.len() as u64
1008 + unobserved.len() as u64
1009 + dangling_rows.len() as u64
1010 + aging.len() as u64
1011 + constraints["count"].as_u64().unwrap_or(0)
1012 + dangling["count"].as_u64().unwrap_or(0)
1013 + process
1014 .iter()
1015 .filter_map(|p| p["open_entries"]["count"].as_u64())
1016 .sum::<u64>();
1017
1018 let mut entry = serde_json::Map::new();
1019 entry.insert("stubs".into(), stubs);
1020 entry.insert("anchors_recheck".into(), capped(recheck));
1021 entry.insert("anchors_unresolvable".into(), capped(unresolvable));
1022 entry.insert("anchors_span_absent".into(), capped(span_absent));
1023 entry.insert("anchors_unobserved".into(), capped(unobserved));
1027 entry.insert("anchors_dangling".into(), capped(dangling_rows));
1028 entry.insert("anchors_aging".into(), capped(aging));
1029 if let Some(why) = entity_end_unreconciled {
1030 entry.insert("entity_end_unreconciled".into(), serde_json::json!(why));
1031 }
1032 entry.insert("unsatisfied_constraints".into(), constraints);
1033 entry.insert("dangling_links".into(), dangling);
1034 entry.insert("resolution_missing".into(), resolution_missing);
1035 entry.insert("resolution_unchecked".into(), resolution_unchecked);
1036 if !process.is_empty() {
1037 entry.insert("process".into(), serde_json::Value::Array(process));
1038 } else {
1039 entry.insert("process_mem_resolvable".into(), serde_json::json!(false));
1042 }
1043 entry.insert("total_open".into(), serde_json::json!(total_open));
1044 out.insert(mem.clone(), serde_json::Value::Object(entry));
1045 }
1046 let mut top = serde_json::Map::new();
1047 top.insert("_item_cap".into(), serde_json::json!(cap));
1048 for (k, v) in out {
1049 top.insert(k, v);
1050 }
1051 serde_json::Value::Object(top)
1052}
1053
1054pub fn health_anchors_axis(
1055 engine: &crate::engine::Engine,
1056 mem_filter: Option<&str>,
1057) -> serde_json::Value {
1058 let mut mems: Vec<String> = engine.mem_names().iter().map(|s| s.to_string()).collect();
1059 mems.retain(|m| mem_filter.is_none_or(|v| m == v));
1060 mems.sort();
1061 let mut out = serde_json::Map::new();
1062 for mem in mems {
1063 let Ok(report) = engine.verify_mem_anchors(&mem) else {
1064 continue;
1065 };
1066 let condition = report.sidecar_error.as_ref().map(|why| {
1067 serde_json::json!({
1068 "code": "ANCHORS_SIDECAR_UNREADABLE",
1069 "mem": mem,
1070 "reason": why,
1071 })
1072 });
1073 let mut row = serde_json::json!({
1076 "condition": condition,
1079 "drifted": report.drifted,
1080 "recheck": report.recheck,
1081 "unresolvable": report.unresolvable,
1086 "span_absent": report.span_absent,
1089 "unobserved": report.unobserved,
1090 "dangling": report.dangling,
1095 "entity_end_unreconciled": report.unreconciled,
1096 "aging": report
1101 .anchors
1102 .iter()
1103 .filter(|a| a.observed_at.is_some())
1104 .map(|a| {
1105 let days = a.unobserved_for_days.unwrap_or(0);
1106 serde_json::json!({
1107 "id": a.entity_id,
1108 "artifact": a.artifact,
1109 "state": a.state,
1110 "observed_at": a.observed_at,
1111 "unobserved_for_days": days,
1112 "note": format!("unobserved for {days} days"),
1113 })
1114 })
1115 .collect::<Vec<_>>(),
1116 });
1117 if let (Some(o), Ok(serde_json::Value::Object(f))) =
1118 (row.as_object_mut(), serde_json::to_value(&report.figure))
1119 {
1120 o.extend(f);
1121 }
1122 out.insert(mem, row);
1123 }
1124 serde_json::Value::Object(out)
1125}
1126
1127pub fn compute_health(
1140 store: &Store,
1141 default_schema: &TypeDefinition,
1142 mem_schemas: &HashMap<String, Arc<Schema>>,
1143 mem_filter: Option<&str>,
1144) -> HealthSummary {
1145 let mut missing_fields = Vec::new();
1146 let mut stale_entities = Vec::new();
1147
1148 let today_days = days_since_epoch();
1149
1150 let in_scope = |mem: &str| mem_filter.is_none_or(|v| mem == v);
1151
1152 for entity in store.all_entities() {
1153 if entity.stub || !in_scope(&entity.mem) {
1154 continue;
1155 }
1156
1157 let resolved = mem_schemas
1166 .get(entity.mem.as_str())
1167 .and_then(|s| s.types.get(entity.entity_type.as_str()).cloned())
1168 .or_else(|| type_by_name(&entity.entity_type));
1169 let schema: &TypeDefinition = resolved.as_deref().unwrap_or(default_schema);
1170 let mut issues = Vec::new();
1171
1172 for field in &schema.health_required_fields {
1174 if schema.section(field).is_some() {
1176 let content = entity.sections.get(field.as_str());
1181 if content.is_none_or(|c| c.trim().is_empty()) {
1182 if let Some(issue) = section_heading_mismatch_issue(entity, schema, field) {
1183 issues.push(issue);
1184 } else {
1185 issues.push(HealthIssue {
1186 field: field.clone(),
1187 code: super::HealthIssueCode::Missing,
1188 message: format!("required section '{field}' is empty"),
1189 });
1190 }
1191 }
1192 } else {
1193 let value = entity.metadata.get(field.as_str());
1199 let is_empty = match value {
1200 None => true,
1201 Some(v) => v.to_frontmatter_string().trim().is_empty(),
1202 };
1203 if is_empty {
1204 issues.push(HealthIssue {
1205 field: field.clone(),
1206 code: super::HealthIssueCode::Missing,
1207 message: format!("required field '{field}' is missing"),
1208 });
1209 }
1210 }
1211 }
1212
1213 for s in schema.sections.iter().filter(|s| !s.catch_all) {
1216 if schema.health_required_fields.contains(&s.key) {
1217 continue; }
1219 let content = entity.sections.get(s.key.as_str());
1220 if content.is_none_or(|c| c.trim().is_empty())
1221 && let Some(issue) = section_heading_mismatch_issue(entity, schema, &s.key)
1222 {
1223 issues.push(issue);
1224 }
1225 }
1226
1227 if let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) {
1243 let mut seen_unknown = std::collections::HashSet::new();
1244 for rel in &entity.relationships {
1245 if !mem_schema.relationship_known(&rel.rel_type) {
1246 if seen_unknown.insert(rel.rel_type.clone()) {
1247 let suggestion = mem_schema
1248 .suggest_relationship(&rel.rel_type)
1249 .map(|s| format!(" Did you mean '{s}'?"))
1250 .unwrap_or_default();
1251 let (schema_name, schema_version) = mem_schema.id();
1252 issues.push(HealthIssue {
1253 field: "relationships".to_string(),
1254 code: super::HealthIssueCode::UndeclaredRelationship,
1255 message: format!(
1256 "relationship '{}' is not declared in schema \
1257 '{schema_name}@{schema_version}'.{suggestion}",
1258 rel.rel_type
1259 ),
1260 });
1261 }
1262 continue;
1263 }
1264
1265 let target_type = store
1266 .get(&rel.target)
1267 .map(|t| t.entity_type.clone())
1268 .filter(|t| !t.is_empty());
1269 if let Err(crate::runtime_validator::ValidationError::InvalidRelationshipShape {
1270 rel_type,
1271 from_type,
1272 to_type,
1273 allowed_source_types,
1274 allowed_target_types,
1275 ..
1276 }) = crate::runtime_validator::validate_rel_shape(
1277 &rel.rel_type,
1278 entity.entity_type.as_str(),
1279 target_type.as_deref(),
1280 mem_schema.as_ref(),
1281 ) {
1282 let allowed_src = if allowed_source_types.is_empty() {
1283 "<any>".to_string()
1284 } else {
1285 allowed_source_types.join(", ")
1286 };
1287 let allowed_tgt = if allowed_target_types.is_empty() {
1288 "<any>".to_string()
1289 } else {
1290 allowed_target_types.join(", ")
1291 };
1292 issues.push(HealthIssue {
1293 field: "relationships".to_string(),
1294 code: super::HealthIssueCode::InvalidRelShape,
1295 message: format!(
1296 "INVALID_REL_SHAPE: edge '{rel_type}' from \
1297 '{from_type}' to '{to_type}' (target {target}) \
1298 violates declared shape — allowed_source_types: \
1299 [{allowed_src}], allowed_target_types: \
1300 [{allowed_tgt}]. Remove via \
1301 `memstead_relate from={from_id} to={target} \
1302 type={rel_type} remove=true`.",
1303 target = rel.target,
1304 from_id = entity.id,
1305 ),
1306 });
1307 }
1308 }
1309 }
1310
1311 let auto_ts_field = schema.metadata_fields.iter().find(|f| f.auto_timestamp);
1313
1314 if let Some(ts_field) = auto_ts_field
1315 && let Some(val) = entity.metadata.get(ts_field.key.as_str())
1316 {
1317 let date_str = val.to_frontmatter_string();
1318 if let Some(modified_days) = parse_iso_to_days(&date_str) {
1319 let days_since = today_days.saturating_sub(modified_days);
1320 if days_since > schema.staleness_threshold_days as u64 {
1321 stale_entities.push(StaleEntity {
1322 id: entity.id.clone(),
1323 title: entity.title.clone(),
1324 days_since_modified: days_since,
1325 anchor_state: None,
1326 });
1327 }
1328 }
1329 }
1330
1331 if !issues.is_empty() {
1332 let total = schema.health_required_fields.len();
1338 let score = if total > 0 {
1339 (total.saturating_sub(issues.len()) as f32) / (total as f32)
1340 } else {
1341 1.0
1342 };
1343
1344 missing_fields.push(HealthReport {
1345 id: entity.id.clone(),
1346 title: entity.title.clone(),
1347 score,
1348 issues,
1349 });
1350 }
1351 }
1352
1353 stale_entities.sort_by_key(|e| std::cmp::Reverse(e.days_since_modified));
1355
1356 let orphan_count = query::find_orphans_with_schemas(store, mem_schemas)
1359 .into_iter()
1360 .filter(|id| store.get(id).is_some_and(|e| in_scope(&e.mem)))
1361 .count();
1362 let leaf_entities_by_type = match mem_filter {
1363 None => query::leaf_population(store, mem_schemas),
1364 Some(v) => {
1365 let scoped: HashMap<String, Arc<Schema>> = mem_schemas
1366 .iter()
1367 .filter(|(mem, _)| mem.as_str() == v)
1368 .map(|(mem, s)| (mem.clone(), s.clone()))
1369 .collect();
1370 query::leaf_population(store, &scoped)
1371 }
1372 };
1373 let stub_count = query::find_stubs(store)
1374 .iter()
1375 .filter(|(id, _)| store.get(id).is_some_and(|e| in_scope(&e.mem)))
1376 .count();
1377
1378 stale_entities.sort_by(|a, b| a.id.0.cmp(&b.id.0));
1381 missing_fields.sort_by(|a, b| a.id.0.cmp(&b.id.0));
1382
1383 HealthSummary {
1384 stale_entities,
1385 anchor_fresh: Vec::new(),
1386 missing_fields,
1387 orphan_count,
1388 stub_count,
1389 warnings: Vec::new(),
1390 quarantined: Vec::new(),
1391 load_errors: Vec::new(),
1392 boot_diagnosis: None,
1393 leaf_entities_by_type,
1394 dangling_links: None,
1395 findings: None,
1396 tag_distribution: None,
1397 tag_distribution_folded: None,
1398 untagged_entities: None,
1399 }
1400}
1401
1402pub fn collect_tag_distribution(
1416 store: &Store,
1417 mem_filter: Option<&str>,
1418 limit: usize,
1419) -> (Vec<TagDistribution>, Vec<FoldedTag>, UntaggedStats) {
1420 let mut counts: HashMap<String, (usize, HashMap<String, usize>)> = HashMap::new();
1422 let mut untagged = UntaggedStats {
1423 total: 0,
1424 by_entity_type: HashMap::new(),
1425 };
1426
1427 for entity in store.all_entities() {
1428 if entity.stub {
1429 continue;
1430 }
1431 if let Some(v) = mem_filter
1432 && entity.mem != v
1433 {
1434 continue;
1435 }
1436
1437 let tags_raw = entity
1438 .metadata
1439 .get("tags")
1440 .and_then(|v| match v {
1441 MetadataValue::String(s) => Some(s.as_str()),
1442 _ => None,
1443 })
1444 .unwrap_or("");
1445
1446 let mut any_tag = false;
1447 for tag in tags_raw.split(',').map(str::trim).filter(|s| !s.is_empty()) {
1448 any_tag = true;
1449 let entry = counts
1450 .entry(tag.to_string())
1451 .or_insert_with(|| (0, HashMap::new()));
1452 entry.0 += 1;
1453 *entry.1.entry(entity.entity_type.clone()).or_insert(0) += 1;
1454 }
1455 if !any_tag {
1456 untagged.total += 1;
1457 *untagged
1458 .by_entity_type
1459 .entry(entity.entity_type.clone())
1460 .or_insert(0) += 1;
1461 }
1462 }
1463
1464 let mut entries: Vec<TagDistribution> = counts
1466 .iter()
1467 .map(|(tag, (count, by_type))| TagDistribution {
1468 tag: tag.clone(),
1469 count: *count,
1470 by_entity_type: by_type.clone(),
1471 })
1472 .collect();
1473 entries.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.tag.cmp(&b.tag)));
1474 entries.truncate(limit);
1475
1476 let mut by_canonical: HashMap<String, Vec<(String, usize)>> = HashMap::new();
1481 for (tag, (count, _)) in counts.iter() {
1482 by_canonical
1483 .entry(tag.to_lowercase())
1484 .or_default()
1485 .push((tag.clone(), *count));
1486 }
1487 let mut folded: Vec<FoldedTag> = by_canonical
1488 .into_iter()
1489 .filter(|(_, v)| v.len() > 1)
1490 .map(|(canonical, mut variants)| {
1491 variants.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
1492 let total = variants.iter().map(|(_, c)| *c).sum();
1493 FoldedTag {
1494 canonical,
1495 total,
1496 variants: variants
1497 .into_iter()
1498 .map(|(tag, count)| TagVariant { tag, count })
1499 .collect(),
1500 }
1501 })
1502 .collect();
1503 folded.sort_by(|a, b| {
1504 b.total
1505 .cmp(&a.total)
1506 .then_with(|| a.canonical.cmp(&b.canonical))
1507 });
1508
1509 (entries, folded, untagged)
1510}
1511
1512pub fn collect_dangling_links(store: &Store, mem_filter: Option<&str>) -> Vec<DanglingLink> {
1538 use crate::entity::parser::extract_inline_links_lenient;
1539 use std::collections::HashSet;
1540
1541 let mut out = Vec::new();
1542 for entity in store.all_entities() {
1543 if entity.stub {
1544 continue;
1545 }
1546 if let Some(v) = mem_filter
1547 && entity.mem != v
1548 {
1549 continue;
1550 }
1551 let explicit_targets: HashSet<_> = entity
1552 .relationships
1553 .iter()
1554 .map(|r| r.target.clone())
1555 .collect();
1556 for (section_key, section_body) in &entity.sections {
1557 for target_id in extract_inline_links_lenient(section_body, &entity.mem) {
1558 let target_missing = store.get(&target_id).map(|e| e.stub).unwrap_or(true);
1559 let alias_orphan = !target_missing && !explicit_targets.contains(&target_id);
1560 let kind = if target_missing {
1564 crate::ops::DanglingLinkKind::LinkTargetMissing
1565 } else {
1566 crate::ops::DanglingLinkKind::LinkNotRelated
1567 };
1568 if target_missing || alias_orphan {
1569 out.push(DanglingLink {
1570 kind,
1571 from: entity.id.clone(),
1572 target_id: target_id.clone(),
1573 target_path: target_id.path().to_string(),
1574 section: Some(section_key.clone()),
1575 });
1576 }
1577 }
1578 }
1579 for rel in &entity.relationships {
1596 if store.get(&rel.target).is_some() {
1597 continue;
1598 }
1599 let already_reported = out
1600 .iter()
1601 .any(|d| d.from == entity.id && d.target_id == rel.target);
1602 if already_reported {
1603 continue;
1604 }
1605 out.push(DanglingLink {
1606 kind: crate::ops::DanglingLinkKind::RelationTargetMissing,
1607 from: entity.id.clone(),
1608 target_id: rel.target.clone(),
1609 target_path: rel.target.path().to_string(),
1610 section: None,
1611 });
1612 }
1613 }
1614 out.sort_by(|a, b| {
1619 (&a.from.0, &a.target_id.0, &a.section).cmp(&(&b.from.0, &b.target_id.0, &b.section))
1620 });
1621 out
1622}
1623
1624pub fn collect_missing_required_outgoing(
1635 store: &Store,
1636 mem_filter: Option<&str>,
1637 mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
1638) -> Vec<MissingRequiredOutgoingReport> {
1639 let mut out = Vec::new();
1640 for entity in store.all_entities() {
1641 if entity.stub {
1642 continue;
1643 }
1644 if let Some(v) = mem_filter
1645 && entity.mem != v
1646 {
1647 continue;
1648 }
1649 let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
1650 continue;
1651 };
1652 let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
1653 continue;
1654 };
1655 if td.required_outgoing.is_empty() {
1656 continue;
1657 }
1658 let unsatisfied = unsatisfied_required_outgoing(entity, td);
1659 if unsatisfied.is_empty() {
1660 continue;
1661 }
1662 out.push(MissingRequiredOutgoingReport {
1663 id: entity.id.clone(),
1664 title: entity.title.clone(),
1665 entity_type: entity.entity_type.clone(),
1666 mem: entity.mem.clone(),
1667 missing: unsatisfied,
1668 });
1669 }
1670 out.sort_by(|a, b| a.mem.cmp(&b.mem).then_with(|| a.id.0.cmp(&b.id.0)));
1671 out
1672}
1673
1674pub fn unsatisfied_required_outgoing(
1682 entity: &crate::entity::Entity,
1683 td: &TypeDefinition,
1684) -> Vec<super::MissingRequiredOutgoingBlock> {
1685 td.required_outgoing
1686 .iter()
1687 .filter(|block| {
1688 if let (Some(when_field), Some(when_value)) = (&block.when_field, &block.when_value) {
1693 let armed = entity
1694 .metadata
1695 .get(when_field.as_str())
1696 .is_some_and(|v| v.to_frontmatter_string() == *when_value);
1697 if !armed {
1698 return false;
1699 }
1700 }
1701 let count = entity
1702 .relationships
1703 .iter()
1704 .filter(|rel| block.relationships.iter().any(|name| name == &rel.rel_type))
1705 .count();
1706 !block.admits(count)
1707 })
1708 .map(|block| super::MissingRequiredOutgoingBlock {
1709 relationships: block.relationships.clone(),
1710 cardinality: block.cardinality.to_string(),
1711 severity: block.severity,
1712 when_field: block.when_field.clone(),
1713 when_value: block.when_value.clone(),
1714 })
1715 .collect()
1716}
1717
1718#[derive(Debug, Clone, serde::Serialize)]
1726#[serde(tag = "kind", rename_all = "snake_case")]
1727pub enum UnsatisfiedConstraint {
1728 RequiresWhen {
1729 field: String,
1730 when_field: String,
1731 when_value: String,
1732 severity: memstead_schema::ConstraintSeverity,
1733 },
1734 Unique {
1735 fields: Vec<String>,
1736 values: Vec<String>,
1738 colliding: String,
1741 severity: memstead_schema::ConstraintSeverity,
1742 },
1743 EnumFromNeighbour {
1744 field: String,
1745 value: String,
1747 rel_type: String,
1748 section: String,
1749 severity: memstead_schema::ConstraintSeverity,
1750 },
1751 StatusPropagation {
1752 field: String,
1753 value: String,
1755 #[serde(skip_serializing_if = "Option::is_none")]
1759 rel_type: Option<String>,
1760 #[serde(skip_serializing_if = "Option::is_none")]
1762 rel_types: Option<Vec<String>>,
1763 tainted_by: String,
1766 severity: memstead_schema::ConstraintSeverity,
1767 },
1768 TransitionRequiresChecks {
1771 field: String,
1772 to_value: String,
1773 relationships: Vec<String>,
1774 direction: memstead_schema::PropagationDirection,
1775 unchecked: Vec<UncheckedRelated>,
1778 related: usize,
1780 min_related: usize,
1783 severity: memstead_schema::ConstraintSeverity,
1784 },
1785 TransitionRequiresSelfCheck {
1788 field: String,
1789 to_value: String,
1790 check_kind: String,
1791 state: String,
1795 severity: memstead_schema::ConstraintSeverity,
1796 },
1797 MustReach {
1802 relationships: Vec<String>,
1803 direction: memstead_schema::ReachDirection,
1804 terminal_types: Vec<String>,
1805 #[serde(skip_serializing_if = "Option::is_none")]
1806 max_depth: Option<u32>,
1807 severity: memstead_schema::ConstraintSeverity,
1808 },
1809}
1810
1811impl UnsatisfiedConstraint {
1812 pub fn severity(&self) -> memstead_schema::ConstraintSeverity {
1813 match self {
1814 Self::RequiresWhen { severity, .. }
1815 | Self::Unique { severity, .. }
1816 | Self::EnumFromNeighbour { severity, .. }
1817 | Self::StatusPropagation { severity, .. }
1818 | Self::MustReach { severity, .. }
1819 | Self::TransitionRequiresChecks { severity, .. }
1820 | Self::TransitionRequiresSelfCheck { severity, .. } => *severity,
1821 }
1822 }
1823
1824 pub fn describe(&self) -> String {
1826 match self {
1827 Self::RequiresWhen {
1828 field,
1829 when_field,
1830 when_value,
1831 ..
1832 } => format!(
1833 "requires_when: '{field}' is required when {when_field}={when_value} and is unset"
1834 ),
1835 Self::Unique {
1836 fields, colliding, ..
1837 } => format!(
1838 "unique: tuple ({}) collides with '{colliding}'",
1839 fields.join(", ")
1840 ),
1841 Self::EnumFromNeighbour {
1842 field,
1843 value,
1844 rel_type,
1845 section,
1846 ..
1847 } => format!(
1848 "enum_from_neighbour: '{field}' value '{value}' has no backing entry in any \
1849 `{section}` section reached via {rel_type}"
1850 ),
1851 Self::StatusPropagation {
1852 field,
1853 value,
1854 tainted_by,
1855 ..
1856 } => {
1857 format!("status_propagation: tainted by '{tainted_by}' ({field}={value})")
1858 }
1859 Self::MustReach {
1860 relationships,
1861 direction,
1862 terminal_types,
1863 max_depth,
1864 ..
1865 } => {
1866 let depth = match max_depth {
1867 Some(d) => format!(" within {d} hop(s)"),
1868 None => String::new(),
1869 };
1870 format!(
1871 "must_reach: no path via [{}] ({direction}) reaches a [{}] entity{depth}",
1872 relationships.join(", "),
1873 terminal_types.join(", ")
1874 )
1875 }
1876 Self::TransitionRequiresChecks {
1877 field,
1878 to_value,
1879 relationships,
1880 unchecked,
1881 related,
1882 min_related,
1883 ..
1884 } => {
1885 if related < min_related {
1886 return format!(
1887 "transition_requires_checks: {field}={to_value} requires at least \
1888 {min_related} related entit{} via [{}] — found {related}",
1889 if *min_related == 1 { "y" } else { "ies" },
1890 relationships.join(", ")
1891 );
1892 }
1893 let listed: Vec<String> = unchecked
1894 .iter()
1895 .map(|u| format!("'{}' ({})", u.id, u.state))
1896 .collect();
1897 format!(
1898 "transition_requires_checks: {field}={to_value} requires a fresh confirming \
1899 check record on every entity related via [{}] — unconfirmed: {}",
1900 relationships.join(", "),
1901 listed.join(", ")
1902 )
1903 }
1904 Self::TransitionRequiresSelfCheck {
1905 field,
1906 to_value,
1907 check_kind,
1908 state,
1909 ..
1910 } => format!(
1911 "transition_requires_self_check: {field}={to_value} requires a fresh confirming \
1912 `{check_kind}` check record on this entity under an identity other than its \
1913 author — derived: {state}"
1914 ),
1915 }
1916 }
1917}
1918
1919#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
1923pub struct UncheckedRelated {
1924 pub id: String,
1925 pub state: String,
1926}
1927
1928pub type CheckStateProvider<'a> =
1936 &'a dyn Fn(&crate::entity::Entity, &str) -> crate::engine::independence::CheckStanding;
1937
1938pub fn unsatisfied_constraints(
1962 store: &Store,
1963 entity: &crate::entity::Entity,
1964 td: &TypeDefinition,
1965 exclude: Option<&crate::entity::EntityId>,
1966 checks: Option<CheckStateProvider<'_>>,
1967) -> Vec<UnsatisfiedConstraint> {
1968 use memstead_schema::ConstraintDef;
1969 td.constraints
1970 .iter()
1971 .filter_map(|c| match c {
1972 ConstraintDef::RequiresWhen {
1973 field,
1974 when_field,
1975 when_value,
1976 severity,
1977 } => {
1978 let triggered = entity
1979 .metadata
1980 .get(when_field.as_str())
1981 .is_some_and(|v| v.to_frontmatter_string() == *when_value);
1982 if !triggered {
1983 return None;
1984 }
1985 let satisfied = entity
1986 .metadata
1987 .get(field.as_str())
1988 .is_some_and(|v| !v.to_frontmatter_string().trim().is_empty())
1989 || entity
1990 .sections
1991 .get(field.as_str())
1992 .is_some_and(|body| !body.trim().is_empty());
1993 if satisfied {
1994 return None;
1995 }
1996 Some(UnsatisfiedConstraint::RequiresWhen {
1997 field: field.clone(),
1998 when_field: when_field.clone(),
1999 when_value: when_value.clone(),
2000 severity: *severity,
2001 })
2002 }
2003 ConstraintDef::Unique { fields, severity } => {
2004 let tuple = tuple_of(entity, fields)?;
2005 let mut colliding: Vec<&str> = store
2006 .all_entities()
2007 .filter(|other| {
2008 !other.stub
2009 && other.mem == entity.mem
2010 && other.entity_type == entity.entity_type
2011 && Some(&other.id) != exclude
2012 && other.id != entity.id
2013 && tuple_of(other, fields).as_ref() == Some(&tuple)
2014 })
2015 .map(|other| other.id.0.as_str())
2016 .collect();
2017 colliding.sort_unstable();
2018 let first = colliding.first()?;
2019 Some(UnsatisfiedConstraint::Unique {
2020 fields: fields.clone(),
2021 values: tuple,
2022 colliding: first.to_string(),
2023 severity: *severity,
2024 })
2025 }
2026 ConstraintDef::EnumFromNeighbour {
2027 field,
2028 rel_type,
2029 section,
2030 severity,
2031 } => {
2032 let value = entity
2033 .metadata
2034 .get(field.as_str())
2035 .map(|v| v.to_frontmatter_string())
2036 .filter(|v| !v.trim().is_empty())?;
2037 let backed = entity
2038 .relationships
2039 .iter()
2040 .filter(|rel| rel.rel_type == *rel_type)
2041 .filter_map(|rel| store.get(&rel.target))
2042 .filter_map(|neighbour| neighbour.sections.get(section.as_str()))
2043 .any(|body| bullet_entries(body).contains(&value));
2044 if backed {
2045 return None;
2046 }
2047 Some(UnsatisfiedConstraint::EnumFromNeighbour {
2048 field: field.clone(),
2049 value,
2050 rel_type: rel_type.clone(),
2051 section: section.clone(),
2052 severity: *severity,
2053 })
2054 }
2055 ConstraintDef::StatusPropagation { .. } => None,
2056 ConstraintDef::TransitionRequiresChecks {
2057 field,
2058 to_value,
2059 relationships,
2060 direction,
2061 min_related,
2062 severity,
2063 } => {
2064 let triggered = entity
2065 .metadata
2066 .get(field.as_str())
2067 .is_some_and(|v| v.to_frontmatter_string() == *to_value);
2068 if !triggered {
2069 return None;
2070 }
2071 let (related, unchecked) = transition_gate_standing(
2072 store,
2073 entity,
2074 relationships,
2075 *direction,
2076 exclude,
2077 checks,
2078 );
2079 if unchecked.is_empty() && related >= *min_related {
2080 return None;
2081 }
2082 Some(UnsatisfiedConstraint::TransitionRequiresChecks {
2083 field: field.clone(),
2084 to_value: to_value.clone(),
2085 relationships: relationships.clone(),
2086 direction: *direction,
2087 unchecked,
2088 related,
2089 min_related: *min_related,
2090 severity: *severity,
2091 })
2092 }
2093 ConstraintDef::TransitionRequiresSelfCheck {
2094 field,
2095 to_value,
2096 check_kind,
2097 severity,
2098 } => {
2099 let triggered = entity
2100 .metadata
2101 .get(field.as_str())
2102 .is_some_and(|v| v.to_frontmatter_string() == *to_value);
2103 if !triggered {
2104 return None;
2105 }
2106 let standing = match checks {
2111 Some(provider) => provider(entity, check_kind),
2112 None => crate::engine::independence::CheckStanding {
2113 state: crate::check::CheckState::NeverChecked,
2114 independence: None,
2115 role: crate::vcs::Role::Unspecified,
2116 },
2117 };
2118 if standing.confirms() {
2119 return None;
2120 }
2121 Some(UnsatisfiedConstraint::TransitionRequiresSelfCheck {
2122 field: field.clone(),
2123 to_value: to_value.clone(),
2124 check_kind: check_kind.clone(),
2125 state: standing.label().to_string(),
2126 severity: *severity,
2127 })
2128 }
2129 })
2130 .collect()
2131}
2132
2133pub fn transition_gate_standing(
2144 store: &Store,
2145 entity: &crate::entity::Entity,
2146 relationships: &[String],
2147 direction: memstead_schema::PropagationDirection,
2148 exclude: Option<&crate::entity::EntityId>,
2149 checks: Option<CheckStateProvider<'_>>,
2150) -> (usize, Vec<UncheckedRelated>) {
2151 let related: Vec<&crate::entity::Entity> = match direction {
2152 memstead_schema::PropagationDirection::Outgoing => entity
2153 .relationships
2154 .iter()
2155 .filter(|rel| relationships.contains(&rel.rel_type))
2156 .filter_map(|rel| store.get(&rel.target))
2157 .collect(),
2158 memstead_schema::PropagationDirection::Incoming => store
2159 .all_entities()
2160 .filter(|other| {
2161 other.id != entity.id
2162 && Some(&other.id) != exclude
2163 && other
2164 .relationships
2165 .iter()
2166 .any(|rel| rel.target == entity.id && relationships.contains(&rel.rel_type))
2167 })
2168 .collect(),
2169 };
2170 let total = related.len();
2171 let mut unchecked: Vec<UncheckedRelated> = related
2172 .into_iter()
2173 .filter_map(|rel_entity| {
2174 let standing = match checks {
2178 Some(provider) => {
2179 provider(rel_entity, crate::check::CheckKind::Verification.as_str())
2180 }
2181 None => crate::engine::independence::CheckStanding {
2182 state: crate::check::CheckState::NeverChecked,
2183 independence: None,
2184 role: crate::vcs::Role::Unspecified,
2185 },
2186 };
2187 if standing.confirms() {
2188 None
2189 } else {
2190 Some(UncheckedRelated {
2191 id: rel_entity.id.0.clone(),
2192 state: standing.label().to_string(),
2193 })
2194 }
2195 })
2196 .collect();
2197 unchecked.sort_by(|a, b| a.id.cmp(&b.id));
2198 (total, unchecked)
2199}
2200
2201fn tuple_of(entity: &crate::entity::Entity, fields: &[String]) -> Option<Vec<String>> {
2205 fields
2206 .iter()
2207 .map(|f| {
2208 entity
2209 .metadata
2210 .get(f.as_str())
2211 .map(|v| v.to_frontmatter_string())
2212 .filter(|v| !v.trim().is_empty())
2213 })
2214 .collect()
2215}
2216
2217fn bullet_entries(body: &str) -> Vec<String> {
2220 let masked = crate::markdown::mask_code_blocks_and_spans(body);
2225 body.lines()
2226 .zip(masked.lines())
2227 .filter_map(|(line, masked_line)| {
2228 let m = masked_line.trim_start();
2229 if m.starts_with("- ") || m.starts_with("* ") {
2230 let t = line.trim_start();
2231 t.strip_prefix("- ")
2232 .or_else(|| t.strip_prefix("* "))
2233 .map(|e| e.trim().to_string())
2234 } else {
2235 None
2236 }
2237 })
2238 .collect()
2239}
2240
2241#[derive(Debug, Clone, serde::Serialize)]
2246pub struct ConstraintFindingReport {
2247 pub id: crate::entity::EntityId,
2248 pub title: String,
2249 pub entity_type: String,
2250 pub mem: String,
2251 pub violations: Vec<UnsatisfiedConstraint>,
2252 #[serde(skip_serializing_if = "Vec::is_empty")]
2256 pub format_violations: Vec<crate::section_format::SectionFormatViolation>,
2257}
2258
2259pub fn collect_constraint_findings(
2269 store: &Store,
2270 mem_filter: Option<&str>,
2271 mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
2272 checks: Option<CheckStateProvider<'_>>,
2273) -> Vec<ConstraintFindingReport> {
2274 use memstead_schema::ConstraintDef;
2275 type Bucket = (
2276 Vec<UnsatisfiedConstraint>,
2277 Vec<crate::section_format::SectionFormatViolation>,
2278 );
2279 let mut by_entity: std::collections::BTreeMap<String, Bucket> = Default::default();
2280
2281 let needs_reverse = mem_schemas.values().any(|s| {
2285 s.types.values().any(|t| {
2286 t.must_reach
2287 .iter()
2288 .any(|ob| ob.direction == memstead_schema::ReachDirection::In)
2289 })
2290 });
2291 let reverse: ReverseIndex = if needs_reverse {
2292 build_reverse_index(store)
2293 } else {
2294 ReverseIndex::default()
2295 };
2296
2297 for entity in store.all_entities() {
2298 if entity.stub {
2299 continue;
2300 }
2301 if let Some(v) = mem_filter
2302 && entity.mem != v
2303 {
2304 continue;
2305 }
2306 let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
2307 continue;
2308 };
2309 let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
2310 continue;
2311 };
2312
2313 for def in &td.sections {
2318 if def.compiled_content.is_none() {
2319 continue;
2320 }
2321 let Some(body) = entity.sections.get(def.key.as_str()) else {
2322 continue;
2323 };
2324 let violations = crate::section_format::check_section_format(def, body);
2325 if !violations.is_empty() {
2326 by_entity
2327 .entry(entity.id.0.clone())
2328 .or_default()
2329 .1
2330 .extend(violations);
2331 }
2332 }
2333
2334 for ob in &td.must_reach {
2339 if !reaches_terminal(store, &reverse, &entity.id, ob) {
2340 by_entity.entry(entity.id.0.clone()).or_default().0.push(
2341 UnsatisfiedConstraint::MustReach {
2342 relationships: ob.relationships.clone(),
2343 direction: ob.direction,
2344 terminal_types: ob.terminal_types.clone(),
2345 max_depth: ob.max_depth,
2346 severity: ob.severity,
2347 },
2348 );
2349 }
2350 }
2351
2352 if td.constraints.is_empty() {
2353 continue;
2354 }
2355
2356 let violations = unsatisfied_constraints(store, entity, td, None, checks);
2358 if !violations.is_empty() {
2359 by_entity
2360 .entry(entity.id.0.clone())
2361 .or_default()
2362 .0
2363 .extend(violations);
2364 }
2365 }
2366
2367 for entity in store.all_entities() {
2378 if entity.stub {
2379 continue;
2380 }
2381 let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
2382 continue;
2383 };
2384 let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
2385 continue;
2386 };
2387 for c in &td.constraints {
2388 let ConstraintDef::StatusPropagation {
2389 field,
2390 value,
2391 rel_type,
2392 rel_types,
2393 direction,
2394 severity,
2395 } = c
2396 else {
2397 continue;
2398 };
2399 let terminal = entity
2400 .metadata
2401 .get(field.as_str())
2402 .is_some_and(|v| v.to_frontmatter_string() == *value);
2403 if !terminal {
2404 continue;
2405 }
2406 let set = c
2407 .propagation_rel_types()
2408 .expect("StatusPropagation always yields a set");
2409 for tainted in reach_transitively(store, &entity.id, &set, *direction) {
2410 if let Some(v) = mem_filter
2411 && tainted.mem() != v
2412 {
2413 continue;
2414 }
2415 by_entity.entry(tainted.0.clone()).or_default().0.push(
2416 UnsatisfiedConstraint::StatusPropagation {
2417 field: field.clone(),
2418 value: value.clone(),
2419 rel_type: rel_type.clone(),
2420 rel_types: rel_types.clone(),
2421 tainted_by: entity.id.to_string(),
2422 severity: *severity,
2423 },
2424 );
2425 }
2426 }
2427 }
2428
2429 let mut out: Vec<ConstraintFindingReport> = by_entity
2430 .into_iter()
2431 .filter_map(|(id, (violations, format_violations))| {
2432 let id = crate::entity::EntityId(id);
2433 let entity = store.get(&id)?;
2434 Some(ConstraintFindingReport {
2435 id,
2436 title: entity.title.clone(),
2437 entity_type: entity.entity_type.clone(),
2438 mem: entity.mem.clone(),
2439 violations,
2440 format_violations,
2441 })
2442 })
2443 .collect();
2444 out.sort_by(|a, b| a.mem.cmp(&b.mem).then_with(|| a.id.0.cmp(&b.id.0)));
2445 out
2446}
2447
2448fn reach_transitively(
2455 store: &Store,
2456 start: &crate::entity::EntityId,
2457 rel_types: &[String],
2458 direction: memstead_schema::PropagationDirection,
2459) -> Vec<crate::entity::EntityId> {
2460 use memstead_schema::PropagationDirection;
2461 let mut seen: std::collections::HashSet<crate::entity::EntityId> =
2462 std::iter::once(start.clone()).collect();
2463 let mut frontier = vec![start.clone()];
2464 let mut reached = Vec::new();
2465 while let Some(current) = frontier.pop() {
2466 let next: Vec<crate::entity::EntityId> = match direction {
2467 PropagationDirection::Incoming => store
2468 .all_entities()
2469 .filter(|e| {
2470 e.relationships
2471 .iter()
2472 .any(|r| rel_types.iter().any(|n| n == &r.rel_type) && r.target == current)
2473 })
2474 .map(|e| e.id.clone())
2475 .collect(),
2476 PropagationDirection::Outgoing => store
2477 .get(¤t)
2478 .map(|e| {
2479 e.relationships
2480 .iter()
2481 .filter(|r| rel_types.iter().any(|n| n == &r.rel_type))
2482 .map(|r| r.target.clone())
2483 .collect()
2484 })
2485 .unwrap_or_default(),
2486 };
2487 for id in next {
2488 if seen.insert(id.clone()) {
2489 if store.get(&id).is_some_and(|e| !e.stub) {
2490 reached.push(id.clone());
2491 }
2492 frontier.push(id);
2493 }
2494 }
2495 }
2496 reached
2497}
2498
2499type ReverseIndex =
2504 std::collections::HashMap<crate::entity::EntityId, Vec<(String, crate::entity::EntityId)>>;
2505
2506fn build_reverse_index(store: &Store) -> ReverseIndex {
2507 let mut idx = ReverseIndex::default();
2508 for entity in store.all_entities() {
2509 for rel in &entity.relationships {
2510 idx.entry(rel.target.clone())
2511 .or_default()
2512 .push((rel.rel_type.clone(), entity.id.clone()));
2513 }
2514 }
2515 idx
2516}
2517
2518fn reaches_terminal(
2527 store: &Store,
2528 reverse: &ReverseIndex,
2529 start: &crate::entity::EntityId,
2530 ob: &memstead_schema::MustReach,
2531) -> bool {
2532 use memstead_schema::ReachDirection;
2533 let mut seen: std::collections::HashSet<crate::entity::EntityId> =
2534 std::iter::once(start.clone()).collect();
2535 let mut frontier = vec![start.clone()];
2536 let mut depth: u32 = 0;
2537 while !frontier.is_empty() {
2538 if let Some(max) = ob.max_depth
2539 && depth >= max
2540 {
2541 return false;
2542 }
2543 depth += 1;
2544 let mut next_frontier = Vec::new();
2545 for current in frontier {
2546 let next: Vec<crate::entity::EntityId> = match ob.direction {
2547 ReachDirection::Out => store
2548 .get(¤t)
2549 .map(|e| {
2550 e.relationships
2551 .iter()
2552 .filter(|r| ob.relationships.iter().any(|n| n == &r.rel_type))
2553 .map(|r| r.target.clone())
2554 .collect()
2555 })
2556 .unwrap_or_default(),
2557 ReachDirection::In => reverse
2558 .get(¤t)
2559 .map(|sources| {
2560 sources
2561 .iter()
2562 .filter(|(rel, _)| ob.relationships.iter().any(|n| n == rel))
2563 .map(|(_, src)| src.clone())
2564 .collect()
2565 })
2566 .unwrap_or_default(),
2567 };
2568 for id in next {
2569 if seen.insert(id.clone()) {
2570 if store.get(&id).is_some_and(|e| {
2571 !e.stub && ob.terminal_types.iter().any(|t| t == &e.entity_type)
2572 }) {
2573 return true;
2574 }
2575 next_frontier.push(id);
2576 }
2577 }
2578 }
2579 frontier = next_frontier;
2580 }
2581 false
2582}
2583
2584#[derive(Debug, Clone, serde::Serialize)]
2589pub struct SignalReport {
2590 pub id: crate::entity::EntityId,
2591 pub title: String,
2592 pub entity_type: String,
2593 pub mem: String,
2594 pub signals: Vec<super::signals::ComputedSignal>,
2596}
2597
2598impl SignalReport {
2599 pub fn has_warn(&self) -> bool {
2603 self.signals
2604 .iter()
2605 .any(|s| s.level == Some(memstead_schema::SignalLevel::Warn))
2606 }
2607}
2608
2609pub fn collect_signal_reports(
2613 store: &Store,
2614 mem_filter: Option<&str>,
2615 mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
2616) -> Vec<SignalReport> {
2617 let mut out = Vec::new();
2618 for entity in store.all_entities() {
2619 if entity.stub {
2620 continue;
2621 }
2622 if let Some(v) = mem_filter
2623 && entity.mem != v
2624 {
2625 continue;
2626 }
2627 let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
2628 continue;
2629 };
2630 let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
2631 continue;
2632 };
2633 if td.signals.is_empty() {
2634 continue;
2635 }
2636 let above: Vec<super::signals::ComputedSignal> =
2637 super::signals::compute_signals(store, td, &entity.id)
2638 .into_iter()
2639 .filter(|s| s.level.is_some())
2640 .collect();
2641 if above.is_empty() {
2642 continue;
2643 }
2644 out.push(SignalReport {
2645 id: entity.id.clone(),
2646 title: entity.title.clone(),
2647 entity_type: entity.entity_type.clone(),
2648 mem: entity.mem.clone(),
2649 signals: above,
2650 });
2651 }
2652 out.sort_by(|a, b| a.mem.cmp(&b.mem).then_with(|| a.id.0.cmp(&b.id.0)));
2653 out
2654}
2655
2656#[derive(Debug, Clone, serde::Serialize)]
2661pub struct SchemaFormatDefect {
2662 pub schema: String,
2663 pub type_name: String,
2664 pub section: String,
2665 pub problems: Vec<String>,
2666}
2667
2668pub fn collect_schema_format_defects(
2672 mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
2673) -> Vec<SchemaFormatDefect> {
2674 let mut seen: std::collections::BTreeSet<String> = Default::default();
2675 let mut out = Vec::new();
2676 let mut schemas: Vec<&Arc<memstead_schema::Schema>> = mem_schemas.values().collect();
2677 schemas.sort_by_key(|s| (s.manifest.name.clone(), s.version.clone()));
2678 for schema in schemas {
2679 let schema_ref = format!("{}@{}", schema.manifest.name, schema.version);
2680 if !seen.insert(schema_ref.clone()) {
2681 continue;
2682 }
2683 for td in schema.types.values() {
2684 for section in &td.sections {
2685 if !section.format_problems.is_empty() {
2686 out.push(SchemaFormatDefect {
2687 schema: schema_ref.clone(),
2688 type_name: td.name.clone(),
2689 section: section.key.clone(),
2690 problems: section.format_problems.clone(),
2691 });
2692 }
2693 }
2694 }
2695 }
2696 out.sort_by(|a, b| {
2697 (&a.schema, &a.type_name, &a.section).cmp(&(&b.schema, &b.type_name, &b.section))
2698 });
2699 out
2700}
2701
2702#[derive(Debug, Clone, serde::Serialize)]
2710pub struct MissingRequiredOutgoingReport {
2711 pub id: crate::entity::EntityId,
2712 pub title: String,
2713 pub entity_type: String,
2714 pub mem: String,
2715 pub missing: Vec<super::MissingRequiredOutgoingBlock>,
2716}
2717
2718pub fn config_projection(
2731 engine: &crate::Engine,
2732 writable_mems: &[String],
2733 mutations: serde_json::Value,
2734 plugin: serde_json::Value,
2735) -> serde_json::Map<String, serde_json::Value> {
2736 let backend_by_mem: std::collections::HashMap<&str, (&'static str, bool)> = engine
2741 .mounts()
2742 .iter()
2743 .map(|m| {
2744 (
2745 m.mem.as_str(),
2746 (m.storage.backend_id(), m.storage.is_durable()),
2747 )
2748 })
2749 .collect();
2750 let mems_detail: Vec<serde_json::Value> = writable_mems
2751 .iter()
2752 .map(|name| {
2753 let origin = engine
2754 .mem_router()
2755 .origin_for_mem(name)
2756 .map(|o| o.kind())
2757 .unwrap_or("explicit");
2758 let mut entry = serde_json::Map::new();
2759 entry.insert("name".into(), serde_json::json!(name));
2760 entry.insert("origin".into(), serde_json::json!(origin));
2761 if let Some((storage, durable)) = backend_by_mem.get(name.as_str()).copied() {
2762 entry.insert("storage".into(), serde_json::json!(storage));
2763 entry.insert("durable".into(), serde_json::json!(durable));
2764 }
2765 let mut vcs_obj = serde_json::Map::new();
2766 if let Ok(gitdir) = engine.gitdir_for(name) {
2767 vcs_obj.insert("gitdir".into(), serde_json::json!(gitdir));
2768 }
2769 if let Ok(worktree) = engine.worktree_for(name) {
2770 vcs_obj.insert("worktree".into(), serde_json::json!(worktree));
2771 }
2772 if let Some(sha) = engine.mem_head_sha(name).ok().flatten() {
2773 vcs_obj.insert("head".into(), serde_json::json!(sha));
2774 }
2775 if !vcs_obj.is_empty() {
2776 entry.insert("vcs".into(), serde_json::Value::Object(vcs_obj));
2777 }
2778 if let Some(cfg) = engine.mem_config_for(name) {
2779 if let Some(title) = &cfg.title {
2783 entry.insert("title".into(), serde_json::json!(title));
2784 }
2785 if let Some(subject) = &cfg.subject {
2786 entry.insert("subject".into(), serde_json::json!(subject));
2787 }
2788 let guidance = serde_json::Map::from_iter(
2789 cfg.write_guidance
2790 .iter()
2791 .map(|(k, v)| (k.clone(), v.clone())),
2792 );
2793 entry.insert("write_guidance".into(), serde_json::Value::Object(guidance));
2794 let extra = serde_json::Map::from_iter(
2795 cfg.extra.iter().map(|(k, v)| (k.clone(), v.clone())),
2796 );
2797 entry.insert("extra".into(), serde_json::Value::Object(extra));
2798 }
2799 serde_json::Value::Object(entry)
2800 })
2801 .collect();
2802
2803 let mut out = serde_json::Map::new();
2804 out.insert("mems".into(), serde_json::json!(mems_detail));
2805 out.insert("mutations".into(), mutations);
2806 out.insert("plugin".into(), plugin);
2807 out
2808}
2809
2810pub fn config_projection_from_settings(
2816 settings: &crate::workspace::WorkspaceSettings,
2817) -> (serde_json::Value, serde_json::Value) {
2818 let mutations = serde_json::json!({ "require_notes": settings.mutations.require_notes });
2819 let plugin_map: serde_json::Map<String, serde_json::Value> = settings
2820 .plugin
2821 .iter()
2822 .map(|(k, v)| {
2823 (
2824 k.clone(),
2825 serde_json::to_value(v).unwrap_or(serde_json::Value::Null),
2826 )
2827 })
2828 .collect();
2829 (mutations, serde_json::Value::Object(plugin_map))
2830}
2831
2832pub(crate) fn section_heading_mismatch_issue(
2847 entity: &crate::entity::Entity,
2848 schema: &TypeDefinition,
2849 key: &str,
2850) -> Option<HealthIssue> {
2851 let def = schema.section(key)?;
2852 let derived = memstead_schema::derive_section_key(&def.heading);
2853 if derived == key {
2854 return None;
2855 }
2856 if !entity
2857 .raw_section_headings
2858 .iter()
2859 .any(|h| h == &def.heading)
2860 {
2861 return None;
2862 }
2863 let landing = match schema.catch_all_section() {
2864 Some(c) => format!(
2865 "the content was absorbed into catch-all section '{}'",
2866 c.key
2867 ),
2868 None => "the content is unreachable under any declared key".to_string(),
2869 };
2870 Some(HealthIssue {
2871 field: key.to_string(),
2872 code: super::HealthIssueCode::SectionHeadingMismatch,
2873 message: format!(
2874 "SECTION_HEADING_MISMATCH: section '{key}' is not missing — its content sits \
2875 under heading '{found}', which derives to '{derived}', not '{key}'; {landing}. \
2876 The schema's declared heading cannot round-trip to its key (expected a heading \
2877 that derives to '{key}'); fix the schema's heading/key pair — new installs of \
2878 such a schema are refused",
2879 found = def.heading,
2880 ),
2881 })
2882}
2883
2884pub fn entity_health(entity: &crate::entity::Entity, schema: &TypeDefinition) -> HealthReport {
2886 let mut issues = Vec::new();
2887
2888 for field in &schema.health_required_fields {
2889 if schema.section(field).is_some() {
2890 let content = entity.sections.get(field.as_str());
2891 if content.is_none_or(|c| c.trim().is_empty()) {
2892 if let Some(issue) = section_heading_mismatch_issue(entity, schema, field) {
2893 issues.push(issue);
2894 } else {
2895 issues.push(HealthIssue {
2896 field: field.clone(),
2897 code: super::HealthIssueCode::Missing,
2898 message: format!("required section '{field}' is empty"),
2899 });
2900 }
2901 }
2902 } else {
2903 let value = entity.metadata.get(field.as_str());
2904 if value.is_none() {
2905 issues.push(HealthIssue {
2906 field: field.clone(),
2907 code: super::HealthIssueCode::Missing,
2908 message: format!("required field '{field}' is missing"),
2909 });
2910 }
2911 }
2912 }
2913
2914 for s in schema.sections.iter().filter(|s| !s.catch_all) {
2918 if schema.health_required_fields.contains(&s.key) {
2919 continue; }
2921 let content = entity.sections.get(s.key.as_str());
2922 if content.is_none_or(|c| c.trim().is_empty())
2923 && let Some(issue) = section_heading_mismatch_issue(entity, schema, &s.key)
2924 {
2925 issues.push(issue);
2926 }
2927 }
2928
2929 let total = schema.health_required_fields.len();
2930 let score = if total > 0 {
2931 (total.saturating_sub(issues.len()) as f32) / (total as f32)
2932 } else {
2933 1.0
2934 };
2935
2936 HealthReport {
2937 id: entity.id.clone(),
2938 title: entity.title.clone(),
2939 score,
2940 issues,
2941 }
2942}
2943
2944pub fn days_since_epoch() -> u64 {
2959 if let Some(pinned) = std::env::var("MEMSTEAD_TODAY")
2960 .ok()
2961 .and_then(|s| crate::engine::due::pinned_days_since_epoch(&s))
2962 {
2963 return pinned;
2964 }
2965 #[cfg(target_arch = "wasm32")]
2966 {
2967 (js_sys::Date::now() / 1000.0) as u64 / 86400
2968 }
2969 #[cfg(not(target_arch = "wasm32"))]
2970 {
2971 std::time::SystemTime::now()
2972 .duration_since(std::time::UNIX_EPOCH)
2973 .unwrap_or_default()
2974 .as_secs()
2975 / 86400
2976 }
2977}
2978
2979pub fn parse_iso_to_days(date: &str) -> Option<u64> {
2982 let date_part = date.split('T').next()?;
2983 let parts: Vec<&str> = date_part.split('-').collect();
2984 if parts.len() != 3 {
2985 return None;
2986 }
2987 let year: u64 = parts[0].parse().ok()?;
2988 let month: u64 = parts[1].parse().ok()?;
2989 let day: u64 = parts[2].parse().ok()?;
2990 Some(ymd_to_days(year, month, day))
2991}
2992
2993fn ymd_to_days(year: u64, month: u64, day: u64) -> u64 {
2996 let y = if month <= 2 { year - 1 } else { year };
2998 let m = if month <= 2 { month + 9 } else { month - 3 };
2999 let era = y / 400;
3000 let yoe = y - era * 400;
3001 let doy = (153 * m + 2) / 5 + day - 1;
3002 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
3003 let days = era * 146097 + doe;
3004 days - 719468
3005}
3006
3007#[cfg(test)]
3008mod tests;