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 "identity": rec.identity,
533 "origin": engine.check_row_prose_origin(&mem, &id, rec).as_wire(),
539 "finding": f,
540 }),
541 );
542 }
543 let state = crate::check::derive_state(latest.get(&id), &e.content_hash);
544 *counts.entry(state.as_str()).or_insert(0) += 1;
545 if let Some(records) = all_verification.get(&id) {
546 let rows: Vec<serde_json::Value> = records
547 .iter()
548 .map(|rec| {
549 let reading = if rec.verdict == "ok" {
550 engine.independence_of(e, rec, &touches).0.as_str()
551 } else {
552 "failed"
553 };
554 let role_confirms = matches!(
559 crate::vcs::Role::from_wire(&rec.role).unwrap_or_default(),
560 crate::vcs::Role::Checker | crate::vcs::Role::Verifier
561 );
562 serde_json::json!({
563 "ts": rec.ts,
564 "identity": rec.identity,
565 "verdict": rec.verdict,
566 "reading": reading,
567 "role": rec.role,
568 "role_confirms": role_confirms,
569 })
570 })
571 .collect();
572 readings.insert(id.clone(), serde_json::Value::Array(rows));
573 }
574 let cstate = crate::check::derive_state_pinned(
575 latest_conformance.get(&id),
576 &e.content_hash,
577 current_pin.as_deref(),
578 );
579 *conformance_counts.entry(cstate.as_str()).or_insert(0) += 1;
580 if state != crate::check::CheckState::CheckedOk {
581 continue;
582 }
583 let check = latest.get(&id).expect("checked_ok implies a record");
593 let (reading, execs) = engine.independence_of(e, check, &touches);
594 if let Some(execs) = execs {
595 executors.insert(id.clone(), serde_json::json!(execs.identities));
596 }
597 match reading {
598 crate::engine::independence::Independence::SelfChecked => self_checked.push(id),
599 crate::engine::independence::Independence::ConfirmedIndependent => {
600 confirmed_independent.push(id)
601 }
602 crate::engine::independence::Independence::Unconfirmable => unconfirmable.push(id),
603 }
604 }
605 let mut m = serde_json::Map::new();
606 for (k, v) in counts {
607 m.insert(k.to_string(), serde_json::json!(v));
608 }
609 let mut c = serde_json::Map::new();
610 for (k, v) in conformance_counts {
611 c.insert(k.to_string(), serde_json::json!(v));
612 }
613 m.insert("conformance".into(), serde_json::Value::Object(c));
614 m.insert(
618 "foreign_kinds".into(),
619 serde_json::to_value(&foreign_kinds).unwrap_or(serde_json::json!({})),
620 );
621 m.insert("findings".into(), serde_json::Value::Object(findings));
622 if let Some(note) = sealed_note {
625 m.insert("sealed".into(), note);
626 }
627 m.insert(
628 "independence".into(),
629 serde_json::json!({
630 "self_checked": capped(self_checked),
631 "confirmed_independent": capped(confirmed_independent),
632 "unconfirmable": capped(unconfirmable),
633 "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",
634 "executors": serde_json::Value::Object(executors),
635 "readings": serde_json::Value::Object(readings),
636 }),
637 );
638 out.insert(mem, serde_json::Value::Object(m));
639 }
640 serde_json::Value::Object(out)
641}
642
643#[derive(Debug, Clone, serde::Serialize)]
649pub struct DerivationFinding {
650 pub source: crate::entity::EntityId,
651 pub rel_type: String,
652 pub target: crate::entity::EntityId,
653 pub state: String,
655 #[serde(skip_serializing_if = "Option::is_none")]
657 pub baseline: Option<String>,
658 pub current: String,
660}
661
662pub fn health_stale_derivations_axis(
667 engine: &crate::engine::Engine,
668 mem_filter: Option<&str>,
669) -> serde_json::Value {
670 let mut mems: Vec<String> = engine.mem_names().iter().map(|s| s.to_string()).collect();
671 mems.sort();
672 let mut out = serde_json::Map::new();
673 for mem in mems {
674 if let Some(f) = mem_filter
675 && f != mem
676 {
677 continue;
678 }
679 let findings = engine.derivation_report(&mem).unwrap_or_default();
680 out.insert(
681 mem,
682 serde_json::to_value(&findings).unwrap_or(serde_json::Value::Array(Vec::new())),
683 );
684 }
685 serde_json::Value::Object(out)
686}
687
688pub const OPEN_QUESTIONS_ITEM_CAP: usize = 20;
692
693pub fn health_open_questions_axis(
709 engine: &crate::engine::Engine,
710 mem_filter: Option<&str>,
711) -> serde_json::Value {
712 let cap = OPEN_QUESTIONS_ITEM_CAP;
713 let capped = |mut items: Vec<serde_json::Value>| -> serde_json::Value {
714 let count = items.len();
715 let more = count.saturating_sub(cap);
716 items.truncate(cap);
717 let mut o = serde_json::Map::new();
718 o.insert("count".into(), serde_json::json!(count));
719 o.insert("items".into(), serde_json::Value::Array(items));
720 if more > 0 {
721 o.insert("more".into(), serde_json::json!(more));
722 }
723 serde_json::Value::Object(o)
724 };
725
726 let bindings: Vec<(String, String)> = engine
730 .workspace_root()
731 .and_then(|root| crate::pipeline_store::load_pipeline_configs(root).ok())
732 .map(|c| {
733 c.bindings
734 .iter()
735 .map(|r| (r.config.destination_mem.clone(), r.name.clone()))
736 .collect()
737 })
738 .unwrap_or_default();
739 let mounted: Vec<String> = engine.mem_names().iter().map(|s| s.to_string()).collect();
740
741 let mut mems: Vec<String> = mounted.clone();
742 mems.sort();
743 let mut out = serde_json::Map::new();
744 for mem in &mems {
745 if let Some(f) = mem_filter
746 && f != mem
747 {
748 continue;
749 }
750
751 let stubs = capped(
753 engine
754 .store()
755 .all_entities()
756 .filter(|e| e.stub && e.id.mem() == mem)
757 .map(|e| serde_json::json!({ "kind": "stub", "id": e.id.to_string() }))
758 .collect(),
759 );
760
761 let (mut recheck, mut unresolvable, mut unobserved, mut dangling_rows) =
774 (Vec::new(), Vec::new(), Vec::new(), Vec::new());
775 let mut span_absent = Vec::new();
779 let mut aging = Vec::new();
782 let mut entity_end_unreconciled: Option<String> = None;
783 if let Ok(report) = engine.verify_mem_anchors(mem) {
784 entity_end_unreconciled = report.unreconciled.clone();
785 for a in &report.anchors {
786 if let Some(days) = a.unobserved_for_days
787 && days > 0
788 {
789 aging.push(serde_json::json!({
790 "kind": "anchor_aging",
791 "id": a.entity_id,
792 "artifact": a.artifact,
793 "state": a.state,
794 "observed_at": a.observed_at,
795 "unobserved_for_days": days,
796 "note": format!("unobserved for {days} days"),
797 }));
798 }
799 let item = serde_json::json!({
800 "kind": format!("anchor_{}", a.state),
801 "id": a.entity_id,
802 "artifact": a.artifact,
803 });
804 match a.state.as_str() {
805 "recheck" => recheck.push(item),
806 "orphaned" => unresolvable.push(item),
809 "span_absent" => span_absent.push(item),
810 "unobserved" => unobserved.push(item),
811 "dangling" => dangling_rows.push(item),
812 _ => {}
813 }
814 }
815 }
816
817 let constraints = capped(
820 engine
821 .constraint_findings(Some(mem))
822 .iter()
823 .map(|r| {
824 serde_json::json!({
825 "kind": "unsatisfied_constraint",
826 "id": r.id.to_string(),
827 "violations": r.violations.len(),
828 })
829 })
830 .collect(),
831 );
832
833 let dangling = capped(
839 collect_dangling_links(engine.store(), Some(mem))
840 .iter()
841 .map(|d| {
842 serde_json::json!({
843 "kind": d.kind.code(),
844 "id": d.from.to_string(),
845 "target": d.target_id.to_string(),
846 "repair": d.kind.repair(),
847 })
848 })
849 .collect(),
850 );
851
852 let mut process = Vec::new();
862 let mem_bindings: Vec<&String> = bindings
863 .iter()
864 .filter(|(d, _)| d == mem)
865 .map(|(_, b)| b)
866 .collect();
867 let mut resolutions: Vec<(Option<String>, crate::binding_run::ProcessMemResolution)> =
868 Vec::new();
869 if mem_bindings.is_empty() {
870 let r = crate::binding_run::resolve_process_mem(engine, mem, "");
871 if r.declared {
872 resolutions.push((None, r));
873 }
874 } else {
875 for binding in &mem_bindings {
876 let derived =
880 crate::binding_run::derived_process_mem_name(&format!("{mem}/{binding}"));
881 resolutions.push((
882 Some((*binding).clone()),
883 crate::binding_run::resolve_process_mem(engine, mem, &derived),
884 ));
885 }
886 }
887 for (binding, r) in resolutions {
888 if r.mounted {
889 let mut open = Vec::new();
890 let mut searched = Vec::new();
891 for e in engine
892 .store()
893 .all_entities()
894 .filter(|e| !e.stub && e.id.mem() == r.mem.as_str())
895 {
896 let item = serde_json::json!({
897 "kind": e.entity_type,
898 "id": e.id.to_string(),
899 "title": e.title,
900 });
901 if e.entity_type == "negative_finding" {
902 searched.push(item);
903 } else {
904 open.push(item);
905 }
906 }
907 let by_id = |a: &serde_json::Value, b: &serde_json::Value| {
912 a["id"].as_str().cmp(&b["id"].as_str())
913 };
914 open.sort_by(by_id);
915 searched.sort_by(by_id);
916 process.push(serde_json::json!({
917 "binding": binding,
918 "process_mem": r.mem,
919 "declared": r.declared,
920 "resolvable": true,
921 "open_entries": capped(open),
922 "already_searched": capped(searched),
923 }));
924 } else if r.declared {
925 process.push(serde_json::json!({
926 "binding": binding,
927 "process_mem": r.mem,
928 "declared": true,
929 "resolvable": false,
930 "finding": "DECLARED_PROCESS_MEM_MISSING",
931 }));
932 } else {
933 process.push(serde_json::json!({
934 "binding": binding,
935 "resolvable": false,
936 }));
937 }
938 }
939
940 let (mut missing, mut unchecked) = (Vec::new(), Vec::new());
946 if let Some(schema) = engine.schema_for(mem) {
947 for entity in engine
948 .store()
949 .all_entities()
950 .filter(|e| !e.stub && e.id.mem() == mem)
951 {
952 let Some(td) = schema.types.get(&entity.entity_type) else {
953 continue;
954 };
955 let Some(res) = &td.resolution else { continue };
956 if let Some(field) = &res.status_field {
957 let open = match entity.metadata.get(field) {
958 Some(crate::entity::MetadataValue::String(s)) => {
959 res.open_values.contains(s)
960 }
961 _ => false,
962 };
963 if !open {
964 continue;
965 }
966 }
967 let has_condition = entity
968 .sections
969 .get(&res.condition_section)
970 .is_some_and(|body| !body.trim().is_empty());
971 if !has_condition {
972 missing.push(serde_json::json!({
973 "kind": "resolution_missing",
974 "id": entity.id.to_string(),
975 "section": res.condition_section,
976 }));
977 continue;
978 }
979 let kind = res.check_kind.as_deref().unwrap_or("verification");
980 let checked = crate::check::RecordKind::from_wire(kind).is_some()
984 && engine
985 .latest_check_record(mem, &entity.id.0, kind)
986 .is_some_and(|r| r.verdict == "ok" && r.entity_hash == entity.content_hash);
987 if !checked {
988 unchecked.push(serde_json::json!({
989 "kind": "resolution_unchecked",
990 "id": entity.id.to_string(),
991 "section": res.condition_section,
992 "check_kind": kind,
993 }));
994 }
995 }
996 }
997 let resolution_missing = capped(missing);
998 let resolution_unchecked = capped(unchecked);
999
1000 let total_open = stubs["count"].as_u64().unwrap_or(0)
1001 + resolution_missing["count"].as_u64().unwrap_or(0)
1002 + resolution_unchecked["count"].as_u64().unwrap_or(0)
1003 + recheck.len() as u64
1004 + unresolvable.len() as u64
1005 + span_absent.len() as u64
1006 + unobserved.len() as u64
1007 + dangling_rows.len() as u64
1008 + aging.len() as u64
1009 + constraints["count"].as_u64().unwrap_or(0)
1010 + dangling["count"].as_u64().unwrap_or(0)
1011 + process
1012 .iter()
1013 .filter_map(|p| p["open_entries"]["count"].as_u64())
1014 .sum::<u64>();
1015
1016 let mut entry = serde_json::Map::new();
1017 entry.insert("stubs".into(), stubs);
1018 entry.insert("anchors_recheck".into(), capped(recheck));
1019 entry.insert("anchors_unresolvable".into(), capped(unresolvable));
1020 entry.insert("anchors_span_absent".into(), capped(span_absent));
1021 entry.insert("anchors_unobserved".into(), capped(unobserved));
1025 entry.insert("anchors_dangling".into(), capped(dangling_rows));
1026 entry.insert("anchors_aging".into(), capped(aging));
1027 if let Some(why) = entity_end_unreconciled {
1028 entry.insert("entity_end_unreconciled".into(), serde_json::json!(why));
1029 }
1030 entry.insert("unsatisfied_constraints".into(), constraints);
1031 entry.insert("dangling_links".into(), dangling);
1032 entry.insert("resolution_missing".into(), resolution_missing);
1033 entry.insert("resolution_unchecked".into(), resolution_unchecked);
1034 if !process.is_empty() {
1035 entry.insert("process".into(), serde_json::Value::Array(process));
1036 } else {
1037 entry.insert("process_mem_resolvable".into(), serde_json::json!(false));
1040 }
1041 entry.insert("total_open".into(), serde_json::json!(total_open));
1042 out.insert(mem.clone(), serde_json::Value::Object(entry));
1043 }
1044 let mut top = serde_json::Map::new();
1045 top.insert("_item_cap".into(), serde_json::json!(cap));
1046 for (k, v) in out {
1047 top.insert(k, v);
1048 }
1049 serde_json::Value::Object(top)
1050}
1051
1052pub fn health_anchors_axis(
1053 engine: &crate::engine::Engine,
1054 mem_filter: Option<&str>,
1055) -> serde_json::Value {
1056 let mut mems: Vec<String> = engine.mem_names().iter().map(|s| s.to_string()).collect();
1057 mems.retain(|m| mem_filter.is_none_or(|v| m == v));
1058 mems.sort();
1059 let mut out = serde_json::Map::new();
1060 for mem in mems {
1061 let Ok(report) = engine.verify_mem_anchors(&mem) else {
1062 continue;
1063 };
1064 let condition = report.sidecar_error.as_ref().map(|why| {
1065 serde_json::json!({
1066 "code": "ANCHORS_SIDECAR_UNREADABLE",
1067 "mem": mem,
1068 "reason": why,
1069 })
1070 });
1071 let mut row = serde_json::json!({
1074 "condition": condition,
1077 "drifted": report.drifted,
1078 "recheck": report.recheck,
1079 "unresolvable": report.unresolvable,
1084 "span_absent": report.span_absent,
1087 "unobserved": report.unobserved,
1088 "dangling": report.dangling,
1093 "entity_end_unreconciled": report.unreconciled,
1094 "aging": report
1099 .anchors
1100 .iter()
1101 .filter(|a| a.observed_at.is_some())
1102 .map(|a| {
1103 let days = a.unobserved_for_days.unwrap_or(0);
1104 serde_json::json!({
1105 "id": a.entity_id,
1106 "artifact": a.artifact,
1107 "state": a.state,
1108 "observed_at": a.observed_at,
1109 "unobserved_for_days": days,
1110 "note": format!("unobserved for {days} days"),
1111 })
1112 })
1113 .collect::<Vec<_>>(),
1114 });
1115 if let (Some(o), Ok(serde_json::Value::Object(f))) =
1116 (row.as_object_mut(), serde_json::to_value(&report.figure))
1117 {
1118 o.extend(f);
1119 }
1120 out.insert(mem, row);
1121 }
1122 serde_json::Value::Object(out)
1123}
1124
1125pub fn compute_health(
1138 store: &Store,
1139 default_schema: &TypeDefinition,
1140 mem_schemas: &HashMap<String, Arc<Schema>>,
1141 mem_filter: Option<&str>,
1142) -> HealthSummary {
1143 let mut missing_fields = Vec::new();
1144 let mut stale_entities = Vec::new();
1145
1146 let today_days = days_since_epoch();
1147
1148 let in_scope = |mem: &str| mem_filter.is_none_or(|v| mem == v);
1149
1150 for entity in store.all_entities() {
1151 if entity.stub || !in_scope(&entity.mem) {
1152 continue;
1153 }
1154
1155 let resolved = mem_schemas
1164 .get(entity.mem.as_str())
1165 .and_then(|s| s.types.get(entity.entity_type.as_str()).cloned())
1166 .or_else(|| type_by_name(&entity.entity_type));
1167 let schema: &TypeDefinition = resolved.as_deref().unwrap_or(default_schema);
1168 let mut issues = Vec::new();
1169
1170 for field in &schema.health_required_fields {
1172 if schema.section(field).is_some() {
1174 let content = entity.sections.get(field.as_str());
1179 if content.is_none_or(|c| c.trim().is_empty()) {
1180 if let Some(issue) = section_heading_mismatch_issue(entity, schema, field) {
1181 issues.push(issue);
1182 } else {
1183 issues.push(HealthIssue {
1184 field: field.clone(),
1185 code: super::HealthIssueCode::Missing,
1186 message: format!("required section '{field}' is empty"),
1187 });
1188 }
1189 }
1190 } else {
1191 let value = entity.metadata.get(field.as_str());
1197 let is_empty = match value {
1198 None => true,
1199 Some(v) => v.to_frontmatter_string().trim().is_empty(),
1200 };
1201 if is_empty {
1202 issues.push(HealthIssue {
1203 field: field.clone(),
1204 code: super::HealthIssueCode::Missing,
1205 message: format!("required field '{field}' is missing"),
1206 });
1207 }
1208 }
1209 }
1210
1211 for s in schema.sections.iter().filter(|s| !s.catch_all) {
1214 if schema.health_required_fields.contains(&s.key) {
1215 continue; }
1217 let content = entity.sections.get(s.key.as_str());
1218 if content.is_none_or(|c| c.trim().is_empty())
1219 && let Some(issue) = section_heading_mismatch_issue(entity, schema, &s.key)
1220 {
1221 issues.push(issue);
1222 }
1223 }
1224
1225 if let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) {
1241 let mut seen_unknown = std::collections::HashSet::new();
1242 for rel in &entity.relationships {
1243 if !mem_schema.relationship_known(&rel.rel_type) {
1244 if seen_unknown.insert(rel.rel_type.clone()) {
1245 let suggestion = mem_schema
1246 .suggest_relationship(&rel.rel_type)
1247 .map(|s| format!(" Did you mean '{s}'?"))
1248 .unwrap_or_default();
1249 let (schema_name, schema_version) = mem_schema.id();
1250 issues.push(HealthIssue {
1251 field: "relationships".to_string(),
1252 code: super::HealthIssueCode::UndeclaredRelationship,
1253 message: format!(
1254 "relationship '{}' is not declared in schema \
1255 '{schema_name}@{schema_version}'.{suggestion}",
1256 rel.rel_type
1257 ),
1258 });
1259 }
1260 continue;
1261 }
1262
1263 let target_type = store
1264 .get(&rel.target)
1265 .map(|t| t.entity_type.clone())
1266 .filter(|t| !t.is_empty());
1267 if let Err(crate::runtime_validator::ValidationError::InvalidRelationshipShape {
1268 rel_type,
1269 from_type,
1270 to_type,
1271 allowed_source_types,
1272 allowed_target_types,
1273 ..
1274 }) = crate::runtime_validator::validate_rel_shape(
1275 &rel.rel_type,
1276 entity.entity_type.as_str(),
1277 target_type.as_deref(),
1278 mem_schema.as_ref(),
1279 ) {
1280 let allowed_src = if allowed_source_types.is_empty() {
1281 "<any>".to_string()
1282 } else {
1283 allowed_source_types.join(", ")
1284 };
1285 let allowed_tgt = if allowed_target_types.is_empty() {
1286 "<any>".to_string()
1287 } else {
1288 allowed_target_types.join(", ")
1289 };
1290 issues.push(HealthIssue {
1291 field: "relationships".to_string(),
1292 code: super::HealthIssueCode::InvalidRelShape,
1293 message: format!(
1294 "INVALID_REL_SHAPE: edge '{rel_type}' from \
1295 '{from_type}' to '{to_type}' (target {target}) \
1296 violates declared shape — allowed_source_types: \
1297 [{allowed_src}], allowed_target_types: \
1298 [{allowed_tgt}]. Remove via \
1299 `memstead_relate from={from_id} to={target} \
1300 type={rel_type} remove=true`.",
1301 target = rel.target,
1302 from_id = entity.id,
1303 ),
1304 });
1305 }
1306 }
1307 }
1308
1309 let auto_ts_field = schema.metadata_fields.iter().find(|f| f.auto_timestamp);
1311
1312 if let Some(ts_field) = auto_ts_field
1313 && let Some(val) = entity.metadata.get(ts_field.key.as_str())
1314 {
1315 let date_str = val.to_frontmatter_string();
1316 if let Some(modified_days) = parse_iso_to_days(&date_str) {
1317 let days_since = today_days.saturating_sub(modified_days);
1318 if days_since > schema.staleness_threshold_days as u64 {
1319 stale_entities.push(StaleEntity {
1320 id: entity.id.clone(),
1321 title: entity.title.clone(),
1322 days_since_modified: days_since,
1323 anchor_state: None,
1324 });
1325 }
1326 }
1327 }
1328
1329 if !issues.is_empty() {
1330 let total = schema.health_required_fields.len();
1336 let score = if total > 0 {
1337 (total.saturating_sub(issues.len()) as f32) / (total as f32)
1338 } else {
1339 1.0
1340 };
1341
1342 missing_fields.push(HealthReport {
1343 id: entity.id.clone(),
1344 title: entity.title.clone(),
1345 score,
1346 issues,
1347 });
1348 }
1349 }
1350
1351 stale_entities.sort_by_key(|e| std::cmp::Reverse(e.days_since_modified));
1353
1354 let orphan_count = query::find_orphans_with_schemas(store, mem_schemas)
1357 .into_iter()
1358 .filter(|id| store.get(id).is_some_and(|e| in_scope(&e.mem)))
1359 .count();
1360 let leaf_entities_by_type = match mem_filter {
1361 None => query::leaf_population(store, mem_schemas),
1362 Some(v) => {
1363 let scoped: HashMap<String, Arc<Schema>> = mem_schemas
1364 .iter()
1365 .filter(|(mem, _)| mem.as_str() == v)
1366 .map(|(mem, s)| (mem.clone(), s.clone()))
1367 .collect();
1368 query::leaf_population(store, &scoped)
1369 }
1370 };
1371 let stub_count = query::find_stubs(store)
1372 .iter()
1373 .filter(|(id, _)| store.get(id).is_some_and(|e| in_scope(&e.mem)))
1374 .count();
1375
1376 stale_entities.sort_by(|a, b| a.id.0.cmp(&b.id.0));
1379 missing_fields.sort_by(|a, b| a.id.0.cmp(&b.id.0));
1380
1381 HealthSummary {
1382 stale_entities,
1383 anchor_fresh: Vec::new(),
1384 missing_fields,
1385 orphan_count,
1386 stub_count,
1387 warnings: Vec::new(),
1388 quarantined: Vec::new(),
1389 load_errors: Vec::new(),
1390 boot_diagnosis: None,
1391 leaf_entities_by_type,
1392 dangling_links: None,
1393 findings: None,
1394 tag_distribution: None,
1395 tag_distribution_folded: None,
1396 untagged_entities: None,
1397 }
1398}
1399
1400pub fn collect_tag_distribution(
1414 store: &Store,
1415 mem_filter: Option<&str>,
1416 limit: usize,
1417) -> (Vec<TagDistribution>, Vec<FoldedTag>, UntaggedStats) {
1418 let mut counts: HashMap<String, (usize, HashMap<String, usize>)> = HashMap::new();
1420 let mut untagged = UntaggedStats {
1421 total: 0,
1422 by_entity_type: HashMap::new(),
1423 };
1424
1425 for entity in store.all_entities() {
1426 if entity.stub {
1427 continue;
1428 }
1429 if let Some(v) = mem_filter
1430 && entity.mem != v
1431 {
1432 continue;
1433 }
1434
1435 let tags_raw = entity
1436 .metadata
1437 .get("tags")
1438 .and_then(|v| match v {
1439 MetadataValue::String(s) => Some(s.as_str()),
1440 _ => None,
1441 })
1442 .unwrap_or("");
1443
1444 let mut any_tag = false;
1445 for tag in tags_raw.split(',').map(str::trim).filter(|s| !s.is_empty()) {
1446 any_tag = true;
1447 let entry = counts
1448 .entry(tag.to_string())
1449 .or_insert_with(|| (0, HashMap::new()));
1450 entry.0 += 1;
1451 *entry.1.entry(entity.entity_type.clone()).or_insert(0) += 1;
1452 }
1453 if !any_tag {
1454 untagged.total += 1;
1455 *untagged
1456 .by_entity_type
1457 .entry(entity.entity_type.clone())
1458 .or_insert(0) += 1;
1459 }
1460 }
1461
1462 let mut entries: Vec<TagDistribution> = counts
1464 .iter()
1465 .map(|(tag, (count, by_type))| TagDistribution {
1466 tag: tag.clone(),
1467 count: *count,
1468 by_entity_type: by_type.clone(),
1469 })
1470 .collect();
1471 entries.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.tag.cmp(&b.tag)));
1472 entries.truncate(limit);
1473
1474 let mut by_canonical: HashMap<String, Vec<(String, usize)>> = HashMap::new();
1479 for (tag, (count, _)) in counts.iter() {
1480 by_canonical
1481 .entry(tag.to_lowercase())
1482 .or_default()
1483 .push((tag.clone(), *count));
1484 }
1485 let mut folded: Vec<FoldedTag> = by_canonical
1486 .into_iter()
1487 .filter(|(_, v)| v.len() > 1)
1488 .map(|(canonical, mut variants)| {
1489 variants.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
1490 let total = variants.iter().map(|(_, c)| *c).sum();
1491 FoldedTag {
1492 canonical,
1493 total,
1494 variants: variants
1495 .into_iter()
1496 .map(|(tag, count)| TagVariant { tag, count })
1497 .collect(),
1498 }
1499 })
1500 .collect();
1501 folded.sort_by(|a, b| {
1502 b.total
1503 .cmp(&a.total)
1504 .then_with(|| a.canonical.cmp(&b.canonical))
1505 });
1506
1507 (entries, folded, untagged)
1508}
1509
1510pub fn collect_dangling_links(store: &Store, mem_filter: Option<&str>) -> Vec<DanglingLink> {
1536 use crate::entity::parser::extract_inline_links_lenient;
1537 use std::collections::HashSet;
1538
1539 let mut out = Vec::new();
1540 for entity in store.all_entities() {
1541 if entity.stub {
1542 continue;
1543 }
1544 if let Some(v) = mem_filter
1545 && entity.mem != v
1546 {
1547 continue;
1548 }
1549 let explicit_targets: HashSet<_> = entity
1550 .relationships
1551 .iter()
1552 .map(|r| r.target.clone())
1553 .collect();
1554 for (section_key, section_body) in &entity.sections {
1555 for target_id in extract_inline_links_lenient(section_body, &entity.mem) {
1556 let target_missing = store.get(&target_id).map(|e| e.stub).unwrap_or(true);
1557 let alias_orphan = !target_missing && !explicit_targets.contains(&target_id);
1558 let kind = if target_missing {
1562 crate::ops::DanglingLinkKind::LinkTargetMissing
1563 } else {
1564 crate::ops::DanglingLinkKind::LinkNotRelated
1565 };
1566 if target_missing || alias_orphan {
1567 out.push(DanglingLink {
1568 kind,
1569 from: entity.id.clone(),
1570 target_id: target_id.clone(),
1571 target_path: target_id.path().to_string(),
1572 section: Some(section_key.clone()),
1573 });
1574 }
1575 }
1576 }
1577 for rel in &entity.relationships {
1594 if store.get(&rel.target).is_some() {
1595 continue;
1596 }
1597 let already_reported = out
1598 .iter()
1599 .any(|d| d.from == entity.id && d.target_id == rel.target);
1600 if already_reported {
1601 continue;
1602 }
1603 out.push(DanglingLink {
1604 kind: crate::ops::DanglingLinkKind::RelationTargetMissing,
1605 from: entity.id.clone(),
1606 target_id: rel.target.clone(),
1607 target_path: rel.target.path().to_string(),
1608 section: None,
1609 });
1610 }
1611 }
1612 out.sort_by(|a, b| {
1617 (&a.from.0, &a.target_id.0, &a.section).cmp(&(&b.from.0, &b.target_id.0, &b.section))
1618 });
1619 out
1620}
1621
1622pub fn collect_missing_required_outgoing(
1633 store: &Store,
1634 mem_filter: Option<&str>,
1635 mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
1636) -> Vec<MissingRequiredOutgoingReport> {
1637 let mut out = Vec::new();
1638 for entity in store.all_entities() {
1639 if entity.stub {
1640 continue;
1641 }
1642 if let Some(v) = mem_filter
1643 && entity.mem != v
1644 {
1645 continue;
1646 }
1647 let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
1648 continue;
1649 };
1650 let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
1651 continue;
1652 };
1653 if td.required_outgoing.is_empty() {
1654 continue;
1655 }
1656 let unsatisfied = unsatisfied_required_outgoing(entity, td);
1657 if unsatisfied.is_empty() {
1658 continue;
1659 }
1660 out.push(MissingRequiredOutgoingReport {
1661 id: entity.id.clone(),
1662 title: entity.title.clone(),
1663 entity_type: entity.entity_type.clone(),
1664 mem: entity.mem.clone(),
1665 missing: unsatisfied,
1666 });
1667 }
1668 out.sort_by(|a, b| a.mem.cmp(&b.mem).then_with(|| a.id.0.cmp(&b.id.0)));
1669 out
1670}
1671
1672pub fn unsatisfied_required_outgoing(
1680 entity: &crate::entity::Entity,
1681 td: &TypeDefinition,
1682) -> Vec<super::MissingRequiredOutgoingBlock> {
1683 td.required_outgoing
1684 .iter()
1685 .filter(|block| {
1686 if let (Some(when_field), Some(when_value)) = (&block.when_field, &block.when_value) {
1691 let armed = entity
1692 .metadata
1693 .get(when_field.as_str())
1694 .is_some_and(|v| v.to_frontmatter_string() == *when_value);
1695 if !armed {
1696 return false;
1697 }
1698 }
1699 let count = entity
1700 .relationships
1701 .iter()
1702 .filter(|rel| block.relationships.iter().any(|name| name == &rel.rel_type))
1703 .count();
1704 !block.admits(count)
1705 })
1706 .map(|block| super::MissingRequiredOutgoingBlock {
1707 relationships: block.relationships.clone(),
1708 cardinality: block.cardinality.to_string(),
1709 severity: block.severity,
1710 when_field: block.when_field.clone(),
1711 when_value: block.when_value.clone(),
1712 })
1713 .collect()
1714}
1715
1716#[derive(Debug, Clone, serde::Serialize)]
1724#[serde(tag = "kind", rename_all = "snake_case")]
1725pub enum UnsatisfiedConstraint {
1726 RequiresWhen {
1727 field: String,
1728 when_field: String,
1729 when_value: String,
1730 severity: memstead_schema::ConstraintSeverity,
1731 },
1732 Unique {
1733 fields: Vec<String>,
1734 values: Vec<String>,
1736 colliding: String,
1739 severity: memstead_schema::ConstraintSeverity,
1740 },
1741 EnumFromNeighbour {
1742 field: String,
1743 value: String,
1745 rel_type: String,
1746 section: String,
1747 severity: memstead_schema::ConstraintSeverity,
1748 },
1749 StatusPropagation {
1750 field: String,
1751 value: String,
1753 #[serde(skip_serializing_if = "Option::is_none")]
1757 rel_type: Option<String>,
1758 #[serde(skip_serializing_if = "Option::is_none")]
1760 rel_types: Option<Vec<String>>,
1761 tainted_by: String,
1764 severity: memstead_schema::ConstraintSeverity,
1765 },
1766 TransitionRequiresChecks {
1769 field: String,
1770 to_value: String,
1771 relationships: Vec<String>,
1772 direction: memstead_schema::PropagationDirection,
1773 unchecked: Vec<UncheckedRelated>,
1776 related: usize,
1778 min_related: usize,
1781 severity: memstead_schema::ConstraintSeverity,
1782 },
1783 TransitionRequiresSelfCheck {
1786 field: String,
1787 to_value: String,
1788 check_kind: String,
1789 state: String,
1793 severity: memstead_schema::ConstraintSeverity,
1794 },
1795 MustReach {
1800 relationships: Vec<String>,
1801 direction: memstead_schema::ReachDirection,
1802 terminal_types: Vec<String>,
1803 #[serde(skip_serializing_if = "Option::is_none")]
1804 max_depth: Option<u32>,
1805 severity: memstead_schema::ConstraintSeverity,
1806 },
1807}
1808
1809impl UnsatisfiedConstraint {
1810 pub fn severity(&self) -> memstead_schema::ConstraintSeverity {
1811 match self {
1812 Self::RequiresWhen { severity, .. }
1813 | Self::Unique { severity, .. }
1814 | Self::EnumFromNeighbour { severity, .. }
1815 | Self::StatusPropagation { severity, .. }
1816 | Self::MustReach { severity, .. }
1817 | Self::TransitionRequiresChecks { severity, .. }
1818 | Self::TransitionRequiresSelfCheck { severity, .. } => *severity,
1819 }
1820 }
1821
1822 pub fn describe(&self) -> String {
1824 match self {
1825 Self::RequiresWhen {
1826 field,
1827 when_field,
1828 when_value,
1829 ..
1830 } => format!(
1831 "requires_when: '{field}' is required when {when_field}={when_value} and is unset"
1832 ),
1833 Self::Unique {
1834 fields, colliding, ..
1835 } => format!(
1836 "unique: tuple ({}) collides with '{colliding}'",
1837 fields.join(", ")
1838 ),
1839 Self::EnumFromNeighbour {
1840 field,
1841 value,
1842 rel_type,
1843 section,
1844 ..
1845 } => format!(
1846 "enum_from_neighbour: '{field}' value '{value}' has no backing entry in any \
1847 `{section}` section reached via {rel_type}"
1848 ),
1849 Self::StatusPropagation {
1850 field,
1851 value,
1852 tainted_by,
1853 ..
1854 } => {
1855 format!("status_propagation: tainted by '{tainted_by}' ({field}={value})")
1856 }
1857 Self::MustReach {
1858 relationships,
1859 direction,
1860 terminal_types,
1861 max_depth,
1862 ..
1863 } => {
1864 let depth = match max_depth {
1865 Some(d) => format!(" within {d} hop(s)"),
1866 None => String::new(),
1867 };
1868 format!(
1869 "must_reach: no path via [{}] ({direction}) reaches a [{}] entity{depth}",
1870 relationships.join(", "),
1871 terminal_types.join(", ")
1872 )
1873 }
1874 Self::TransitionRequiresChecks {
1875 field,
1876 to_value,
1877 relationships,
1878 unchecked,
1879 related,
1880 min_related,
1881 ..
1882 } => {
1883 if related < min_related {
1884 return format!(
1885 "transition_requires_checks: {field}={to_value} requires at least \
1886 {min_related} related entit{} via [{}] — found {related}",
1887 if *min_related == 1 { "y" } else { "ies" },
1888 relationships.join(", ")
1889 );
1890 }
1891 let listed: Vec<String> = unchecked
1892 .iter()
1893 .map(|u| format!("'{}' ({})", u.id, u.state))
1894 .collect();
1895 format!(
1896 "transition_requires_checks: {field}={to_value} requires a fresh confirming \
1897 check record on every entity related via [{}] — unconfirmed: {}",
1898 relationships.join(", "),
1899 listed.join(", ")
1900 )
1901 }
1902 Self::TransitionRequiresSelfCheck {
1903 field,
1904 to_value,
1905 check_kind,
1906 state,
1907 ..
1908 } => format!(
1909 "transition_requires_self_check: {field}={to_value} requires a fresh confirming \
1910 `{check_kind}` check record on this entity under an identity other than its \
1911 author — derived: {state}"
1912 ),
1913 }
1914 }
1915}
1916
1917#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
1921pub struct UncheckedRelated {
1922 pub id: String,
1923 pub state: String,
1924}
1925
1926pub type CheckStateProvider<'a> =
1934 &'a dyn Fn(&crate::entity::Entity, &str) -> crate::engine::independence::CheckStanding;
1935
1936pub fn unsatisfied_constraints(
1960 store: &Store,
1961 entity: &crate::entity::Entity,
1962 td: &TypeDefinition,
1963 exclude: Option<&crate::entity::EntityId>,
1964 checks: Option<CheckStateProvider<'_>>,
1965) -> Vec<UnsatisfiedConstraint> {
1966 use memstead_schema::ConstraintDef;
1967 td.constraints
1968 .iter()
1969 .filter_map(|c| match c {
1970 ConstraintDef::RequiresWhen {
1971 field,
1972 when_field,
1973 when_value,
1974 severity,
1975 } => {
1976 let triggered = entity
1977 .metadata
1978 .get(when_field.as_str())
1979 .is_some_and(|v| v.to_frontmatter_string() == *when_value);
1980 if !triggered {
1981 return None;
1982 }
1983 let satisfied = entity
1984 .metadata
1985 .get(field.as_str())
1986 .is_some_and(|v| !v.to_frontmatter_string().trim().is_empty())
1987 || entity
1988 .sections
1989 .get(field.as_str())
1990 .is_some_and(|body| !body.trim().is_empty());
1991 if satisfied {
1992 return None;
1993 }
1994 Some(UnsatisfiedConstraint::RequiresWhen {
1995 field: field.clone(),
1996 when_field: when_field.clone(),
1997 when_value: when_value.clone(),
1998 severity: *severity,
1999 })
2000 }
2001 ConstraintDef::Unique { fields, severity } => {
2002 let tuple = tuple_of(entity, fields)?;
2003 let mut colliding: Vec<&str> = store
2004 .all_entities()
2005 .filter(|other| {
2006 !other.stub
2007 && other.mem == entity.mem
2008 && other.entity_type == entity.entity_type
2009 && Some(&other.id) != exclude
2010 && other.id != entity.id
2011 && tuple_of(other, fields).as_ref() == Some(&tuple)
2012 })
2013 .map(|other| other.id.0.as_str())
2014 .collect();
2015 colliding.sort_unstable();
2016 let first = colliding.first()?;
2017 Some(UnsatisfiedConstraint::Unique {
2018 fields: fields.clone(),
2019 values: tuple,
2020 colliding: first.to_string(),
2021 severity: *severity,
2022 })
2023 }
2024 ConstraintDef::EnumFromNeighbour {
2025 field,
2026 rel_type,
2027 section,
2028 severity,
2029 } => {
2030 let value = entity
2031 .metadata
2032 .get(field.as_str())
2033 .map(|v| v.to_frontmatter_string())
2034 .filter(|v| !v.trim().is_empty())?;
2035 let backed = entity
2036 .relationships
2037 .iter()
2038 .filter(|rel| rel.rel_type == *rel_type)
2039 .filter_map(|rel| store.get(&rel.target))
2040 .filter_map(|neighbour| neighbour.sections.get(section.as_str()))
2041 .any(|body| bullet_entries(body).contains(&value));
2042 if backed {
2043 return None;
2044 }
2045 Some(UnsatisfiedConstraint::EnumFromNeighbour {
2046 field: field.clone(),
2047 value,
2048 rel_type: rel_type.clone(),
2049 section: section.clone(),
2050 severity: *severity,
2051 })
2052 }
2053 ConstraintDef::StatusPropagation { .. } => None,
2054 ConstraintDef::TransitionRequiresChecks {
2055 field,
2056 to_value,
2057 relationships,
2058 direction,
2059 min_related,
2060 severity,
2061 } => {
2062 let triggered = entity
2063 .metadata
2064 .get(field.as_str())
2065 .is_some_and(|v| v.to_frontmatter_string() == *to_value);
2066 if !triggered {
2067 return None;
2068 }
2069 let (related, unchecked) = transition_gate_standing(
2070 store,
2071 entity,
2072 relationships,
2073 *direction,
2074 exclude,
2075 checks,
2076 );
2077 if unchecked.is_empty() && related >= *min_related {
2078 return None;
2079 }
2080 Some(UnsatisfiedConstraint::TransitionRequiresChecks {
2081 field: field.clone(),
2082 to_value: to_value.clone(),
2083 relationships: relationships.clone(),
2084 direction: *direction,
2085 unchecked,
2086 related,
2087 min_related: *min_related,
2088 severity: *severity,
2089 })
2090 }
2091 ConstraintDef::TransitionRequiresSelfCheck {
2092 field,
2093 to_value,
2094 check_kind,
2095 severity,
2096 } => {
2097 let triggered = entity
2098 .metadata
2099 .get(field.as_str())
2100 .is_some_and(|v| v.to_frontmatter_string() == *to_value);
2101 if !triggered {
2102 return None;
2103 }
2104 let standing = match checks {
2109 Some(provider) => provider(entity, check_kind),
2110 None => crate::engine::independence::CheckStanding {
2111 state: crate::check::CheckState::NeverChecked,
2112 independence: None,
2113 role: crate::vcs::Role::Unspecified,
2114 },
2115 };
2116 if standing.confirms() {
2117 return None;
2118 }
2119 Some(UnsatisfiedConstraint::TransitionRequiresSelfCheck {
2120 field: field.clone(),
2121 to_value: to_value.clone(),
2122 check_kind: check_kind.clone(),
2123 state: standing.label().to_string(),
2124 severity: *severity,
2125 })
2126 }
2127 })
2128 .collect()
2129}
2130
2131pub fn transition_gate_standing(
2142 store: &Store,
2143 entity: &crate::entity::Entity,
2144 relationships: &[String],
2145 direction: memstead_schema::PropagationDirection,
2146 exclude: Option<&crate::entity::EntityId>,
2147 checks: Option<CheckStateProvider<'_>>,
2148) -> (usize, Vec<UncheckedRelated>) {
2149 let related: Vec<&crate::entity::Entity> = match direction {
2150 memstead_schema::PropagationDirection::Outgoing => entity
2151 .relationships
2152 .iter()
2153 .filter(|rel| relationships.contains(&rel.rel_type))
2154 .filter_map(|rel| store.get(&rel.target))
2155 .collect(),
2156 memstead_schema::PropagationDirection::Incoming => store
2157 .all_entities()
2158 .filter(|other| {
2159 other.id != entity.id
2160 && Some(&other.id) != exclude
2161 && other
2162 .relationships
2163 .iter()
2164 .any(|rel| rel.target == entity.id && relationships.contains(&rel.rel_type))
2165 })
2166 .collect(),
2167 };
2168 let total = related.len();
2169 let mut unchecked: Vec<UncheckedRelated> = related
2170 .into_iter()
2171 .filter_map(|rel_entity| {
2172 let standing = match checks {
2176 Some(provider) => {
2177 provider(rel_entity, crate::check::CheckKind::Verification.as_str())
2178 }
2179 None => crate::engine::independence::CheckStanding {
2180 state: crate::check::CheckState::NeverChecked,
2181 independence: None,
2182 role: crate::vcs::Role::Unspecified,
2183 },
2184 };
2185 if standing.confirms() {
2186 None
2187 } else {
2188 Some(UncheckedRelated {
2189 id: rel_entity.id.0.clone(),
2190 state: standing.label().to_string(),
2191 })
2192 }
2193 })
2194 .collect();
2195 unchecked.sort_by(|a, b| a.id.cmp(&b.id));
2196 (total, unchecked)
2197}
2198
2199fn tuple_of(entity: &crate::entity::Entity, fields: &[String]) -> Option<Vec<String>> {
2203 fields
2204 .iter()
2205 .map(|f| {
2206 entity
2207 .metadata
2208 .get(f.as_str())
2209 .map(|v| v.to_frontmatter_string())
2210 .filter(|v| !v.trim().is_empty())
2211 })
2212 .collect()
2213}
2214
2215fn bullet_entries(body: &str) -> Vec<String> {
2218 let masked = crate::markdown::mask_code_blocks_and_spans(body);
2223 body.lines()
2224 .zip(masked.lines())
2225 .filter_map(|(line, masked_line)| {
2226 let m = masked_line.trim_start();
2227 if m.starts_with("- ") || m.starts_with("* ") {
2228 let t = line.trim_start();
2229 t.strip_prefix("- ")
2230 .or_else(|| t.strip_prefix("* "))
2231 .map(|e| e.trim().to_string())
2232 } else {
2233 None
2234 }
2235 })
2236 .collect()
2237}
2238
2239#[derive(Debug, Clone, serde::Serialize)]
2244pub struct ConstraintFindingReport {
2245 pub id: crate::entity::EntityId,
2246 pub title: String,
2247 pub entity_type: String,
2248 pub mem: String,
2249 pub violations: Vec<UnsatisfiedConstraint>,
2250 #[serde(skip_serializing_if = "Vec::is_empty")]
2254 pub format_violations: Vec<crate::section_format::SectionFormatViolation>,
2255}
2256
2257pub fn collect_constraint_findings(
2267 store: &Store,
2268 mem_filter: Option<&str>,
2269 mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
2270 checks: Option<CheckStateProvider<'_>>,
2271) -> Vec<ConstraintFindingReport> {
2272 use memstead_schema::ConstraintDef;
2273 type Bucket = (
2274 Vec<UnsatisfiedConstraint>,
2275 Vec<crate::section_format::SectionFormatViolation>,
2276 );
2277 let mut by_entity: std::collections::BTreeMap<String, Bucket> = Default::default();
2278
2279 let needs_reverse = mem_schemas.values().any(|s| {
2283 s.types.values().any(|t| {
2284 t.must_reach
2285 .iter()
2286 .any(|ob| ob.direction == memstead_schema::ReachDirection::In)
2287 })
2288 });
2289 let reverse: ReverseIndex = if needs_reverse {
2290 build_reverse_index(store)
2291 } else {
2292 ReverseIndex::default()
2293 };
2294
2295 for entity in store.all_entities() {
2296 if entity.stub {
2297 continue;
2298 }
2299 if let Some(v) = mem_filter
2300 && entity.mem != v
2301 {
2302 continue;
2303 }
2304 let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
2305 continue;
2306 };
2307 let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
2308 continue;
2309 };
2310
2311 for def in &td.sections {
2316 if def.compiled_content.is_none() {
2317 continue;
2318 }
2319 let Some(body) = entity.sections.get(def.key.as_str()) else {
2320 continue;
2321 };
2322 let violations = crate::section_format::check_section_format(def, body);
2323 if !violations.is_empty() {
2324 by_entity
2325 .entry(entity.id.0.clone())
2326 .or_default()
2327 .1
2328 .extend(violations);
2329 }
2330 }
2331
2332 for ob in &td.must_reach {
2337 if !reaches_terminal(store, &reverse, &entity.id, ob) {
2338 by_entity.entry(entity.id.0.clone()).or_default().0.push(
2339 UnsatisfiedConstraint::MustReach {
2340 relationships: ob.relationships.clone(),
2341 direction: ob.direction,
2342 terminal_types: ob.terminal_types.clone(),
2343 max_depth: ob.max_depth,
2344 severity: ob.severity,
2345 },
2346 );
2347 }
2348 }
2349
2350 if td.constraints.is_empty() {
2351 continue;
2352 }
2353
2354 let violations = unsatisfied_constraints(store, entity, td, None, checks);
2356 if !violations.is_empty() {
2357 by_entity
2358 .entry(entity.id.0.clone())
2359 .or_default()
2360 .0
2361 .extend(violations);
2362 }
2363
2364 for c in &td.constraints {
2369 let ConstraintDef::StatusPropagation {
2370 field,
2371 value,
2372 rel_type,
2373 rel_types,
2374 direction,
2375 severity,
2376 } = c
2377 else {
2378 continue;
2379 };
2380 let terminal = entity
2381 .metadata
2382 .get(field.as_str())
2383 .is_some_and(|v| v.to_frontmatter_string() == *value);
2384 if !terminal {
2385 continue;
2386 }
2387 let set = c
2388 .propagation_rel_types()
2389 .expect("StatusPropagation always yields a set");
2390 for tainted in reach_transitively(store, &entity.id, &set, *direction) {
2391 if let Some(v) = mem_filter
2392 && tainted.mem() != v
2393 {
2394 continue;
2395 }
2396 by_entity.entry(tainted.0.clone()).or_default().0.push(
2397 UnsatisfiedConstraint::StatusPropagation {
2398 field: field.clone(),
2399 value: value.clone(),
2400 rel_type: rel_type.clone(),
2401 rel_types: rel_types.clone(),
2402 tainted_by: entity.id.to_string(),
2403 severity: *severity,
2404 },
2405 );
2406 }
2407 }
2408 }
2409
2410 let mut out: Vec<ConstraintFindingReport> = by_entity
2411 .into_iter()
2412 .filter_map(|(id, (violations, format_violations))| {
2413 let id = crate::entity::EntityId(id);
2414 let entity = store.get(&id)?;
2415 Some(ConstraintFindingReport {
2416 id,
2417 title: entity.title.clone(),
2418 entity_type: entity.entity_type.clone(),
2419 mem: entity.mem.clone(),
2420 violations,
2421 format_violations,
2422 })
2423 })
2424 .collect();
2425 out.sort_by(|a, b| a.mem.cmp(&b.mem).then_with(|| a.id.0.cmp(&b.id.0)));
2426 out
2427}
2428
2429fn reach_transitively(
2436 store: &Store,
2437 start: &crate::entity::EntityId,
2438 rel_types: &[String],
2439 direction: memstead_schema::PropagationDirection,
2440) -> Vec<crate::entity::EntityId> {
2441 use memstead_schema::PropagationDirection;
2442 let mut seen: std::collections::HashSet<crate::entity::EntityId> =
2443 std::iter::once(start.clone()).collect();
2444 let mut frontier = vec![start.clone()];
2445 let mut reached = Vec::new();
2446 while let Some(current) = frontier.pop() {
2447 let next: Vec<crate::entity::EntityId> = match direction {
2448 PropagationDirection::Incoming => store
2449 .all_entities()
2450 .filter(|e| {
2451 e.relationships
2452 .iter()
2453 .any(|r| rel_types.iter().any(|n| n == &r.rel_type) && r.target == current)
2454 })
2455 .map(|e| e.id.clone())
2456 .collect(),
2457 PropagationDirection::Outgoing => store
2458 .get(¤t)
2459 .map(|e| {
2460 e.relationships
2461 .iter()
2462 .filter(|r| rel_types.iter().any(|n| n == &r.rel_type))
2463 .map(|r| r.target.clone())
2464 .collect()
2465 })
2466 .unwrap_or_default(),
2467 };
2468 for id in next {
2469 if seen.insert(id.clone()) {
2470 if store.get(&id).is_some_and(|e| !e.stub) {
2471 reached.push(id.clone());
2472 }
2473 frontier.push(id);
2474 }
2475 }
2476 }
2477 reached
2478}
2479
2480type ReverseIndex =
2485 std::collections::HashMap<crate::entity::EntityId, Vec<(String, crate::entity::EntityId)>>;
2486
2487fn build_reverse_index(store: &Store) -> ReverseIndex {
2488 let mut idx = ReverseIndex::default();
2489 for entity in store.all_entities() {
2490 for rel in &entity.relationships {
2491 idx.entry(rel.target.clone())
2492 .or_default()
2493 .push((rel.rel_type.clone(), entity.id.clone()));
2494 }
2495 }
2496 idx
2497}
2498
2499fn reaches_terminal(
2508 store: &Store,
2509 reverse: &ReverseIndex,
2510 start: &crate::entity::EntityId,
2511 ob: &memstead_schema::MustReach,
2512) -> bool {
2513 use memstead_schema::ReachDirection;
2514 let mut seen: std::collections::HashSet<crate::entity::EntityId> =
2515 std::iter::once(start.clone()).collect();
2516 let mut frontier = vec![start.clone()];
2517 let mut depth: u32 = 0;
2518 while !frontier.is_empty() {
2519 if let Some(max) = ob.max_depth
2520 && depth >= max
2521 {
2522 return false;
2523 }
2524 depth += 1;
2525 let mut next_frontier = Vec::new();
2526 for current in frontier {
2527 let next: Vec<crate::entity::EntityId> = match ob.direction {
2528 ReachDirection::Out => store
2529 .get(¤t)
2530 .map(|e| {
2531 e.relationships
2532 .iter()
2533 .filter(|r| ob.relationships.iter().any(|n| n == &r.rel_type))
2534 .map(|r| r.target.clone())
2535 .collect()
2536 })
2537 .unwrap_or_default(),
2538 ReachDirection::In => reverse
2539 .get(¤t)
2540 .map(|sources| {
2541 sources
2542 .iter()
2543 .filter(|(rel, _)| ob.relationships.iter().any(|n| n == rel))
2544 .map(|(_, src)| src.clone())
2545 .collect()
2546 })
2547 .unwrap_or_default(),
2548 };
2549 for id in next {
2550 if seen.insert(id.clone()) {
2551 if store.get(&id).is_some_and(|e| {
2552 !e.stub && ob.terminal_types.iter().any(|t| t == &e.entity_type)
2553 }) {
2554 return true;
2555 }
2556 next_frontier.push(id);
2557 }
2558 }
2559 }
2560 frontier = next_frontier;
2561 }
2562 false
2563}
2564
2565#[derive(Debug, Clone, serde::Serialize)]
2570pub struct SignalReport {
2571 pub id: crate::entity::EntityId,
2572 pub title: String,
2573 pub entity_type: String,
2574 pub mem: String,
2575 pub signals: Vec<super::signals::ComputedSignal>,
2577}
2578
2579impl SignalReport {
2580 pub fn has_warn(&self) -> bool {
2584 self.signals
2585 .iter()
2586 .any(|s| s.level == Some(memstead_schema::SignalLevel::Warn))
2587 }
2588}
2589
2590pub fn collect_signal_reports(
2594 store: &Store,
2595 mem_filter: Option<&str>,
2596 mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
2597) -> Vec<SignalReport> {
2598 let mut out = Vec::new();
2599 for entity in store.all_entities() {
2600 if entity.stub {
2601 continue;
2602 }
2603 if let Some(v) = mem_filter
2604 && entity.mem != v
2605 {
2606 continue;
2607 }
2608 let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
2609 continue;
2610 };
2611 let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
2612 continue;
2613 };
2614 if td.signals.is_empty() {
2615 continue;
2616 }
2617 let above: Vec<super::signals::ComputedSignal> =
2618 super::signals::compute_signals(store, td, &entity.id)
2619 .into_iter()
2620 .filter(|s| s.level.is_some())
2621 .collect();
2622 if above.is_empty() {
2623 continue;
2624 }
2625 out.push(SignalReport {
2626 id: entity.id.clone(),
2627 title: entity.title.clone(),
2628 entity_type: entity.entity_type.clone(),
2629 mem: entity.mem.clone(),
2630 signals: above,
2631 });
2632 }
2633 out.sort_by(|a, b| a.mem.cmp(&b.mem).then_with(|| a.id.0.cmp(&b.id.0)));
2634 out
2635}
2636
2637#[derive(Debug, Clone, serde::Serialize)]
2642pub struct SchemaFormatDefect {
2643 pub schema: String,
2644 pub type_name: String,
2645 pub section: String,
2646 pub problems: Vec<String>,
2647}
2648
2649pub fn collect_schema_format_defects(
2653 mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
2654) -> Vec<SchemaFormatDefect> {
2655 let mut seen: std::collections::BTreeSet<String> = Default::default();
2656 let mut out = Vec::new();
2657 let mut schemas: Vec<&Arc<memstead_schema::Schema>> = mem_schemas.values().collect();
2658 schemas.sort_by_key(|s| (s.manifest.name.clone(), s.version.clone()));
2659 for schema in schemas {
2660 let schema_ref = format!("{}@{}", schema.manifest.name, schema.version);
2661 if !seen.insert(schema_ref.clone()) {
2662 continue;
2663 }
2664 for td in schema.types.values() {
2665 for section in &td.sections {
2666 if !section.format_problems.is_empty() {
2667 out.push(SchemaFormatDefect {
2668 schema: schema_ref.clone(),
2669 type_name: td.name.clone(),
2670 section: section.key.clone(),
2671 problems: section.format_problems.clone(),
2672 });
2673 }
2674 }
2675 }
2676 }
2677 out.sort_by(|a, b| {
2678 (&a.schema, &a.type_name, &a.section).cmp(&(&b.schema, &b.type_name, &b.section))
2679 });
2680 out
2681}
2682
2683#[derive(Debug, Clone, serde::Serialize)]
2691pub struct MissingRequiredOutgoingReport {
2692 pub id: crate::entity::EntityId,
2693 pub title: String,
2694 pub entity_type: String,
2695 pub mem: String,
2696 pub missing: Vec<super::MissingRequiredOutgoingBlock>,
2697}
2698
2699pub fn config_projection(
2712 engine: &crate::Engine,
2713 writable_mems: &[String],
2714 mutations: serde_json::Value,
2715 plugin: serde_json::Value,
2716) -> serde_json::Map<String, serde_json::Value> {
2717 let backend_by_mem: std::collections::HashMap<&str, (&'static str, bool)> = engine
2722 .mounts()
2723 .iter()
2724 .map(|m| {
2725 (
2726 m.mem.as_str(),
2727 (m.storage.backend_id(), m.storage.is_durable()),
2728 )
2729 })
2730 .collect();
2731 let mems_detail: Vec<serde_json::Value> = writable_mems
2732 .iter()
2733 .map(|name| {
2734 let origin = engine
2735 .mem_router()
2736 .origin_for_mem(name)
2737 .map(|o| o.kind())
2738 .unwrap_or("explicit");
2739 let mut entry = serde_json::Map::new();
2740 entry.insert("name".into(), serde_json::json!(name));
2741 entry.insert("origin".into(), serde_json::json!(origin));
2742 if let Some((storage, durable)) = backend_by_mem.get(name.as_str()).copied() {
2743 entry.insert("storage".into(), serde_json::json!(storage));
2744 entry.insert("durable".into(), serde_json::json!(durable));
2745 }
2746 let mut vcs_obj = serde_json::Map::new();
2747 if let Ok(gitdir) = engine.gitdir_for(name) {
2748 vcs_obj.insert("gitdir".into(), serde_json::json!(gitdir));
2749 }
2750 if let Ok(worktree) = engine.worktree_for(name) {
2751 vcs_obj.insert("worktree".into(), serde_json::json!(worktree));
2752 }
2753 if let Some(sha) = engine.mem_head_sha(name).ok().flatten() {
2754 vcs_obj.insert("head".into(), serde_json::json!(sha));
2755 }
2756 if !vcs_obj.is_empty() {
2757 entry.insert("vcs".into(), serde_json::Value::Object(vcs_obj));
2758 }
2759 if let Some(cfg) = engine.mem_config_for(name) {
2760 if let Some(title) = &cfg.title {
2764 entry.insert("title".into(), serde_json::json!(title));
2765 }
2766 if let Some(subject) = &cfg.subject {
2767 entry.insert("subject".into(), serde_json::json!(subject));
2768 }
2769 let guidance = serde_json::Map::from_iter(
2770 cfg.write_guidance
2771 .iter()
2772 .map(|(k, v)| (k.clone(), v.clone())),
2773 );
2774 entry.insert("write_guidance".into(), serde_json::Value::Object(guidance));
2775 let extra = serde_json::Map::from_iter(
2776 cfg.extra.iter().map(|(k, v)| (k.clone(), v.clone())),
2777 );
2778 entry.insert("extra".into(), serde_json::Value::Object(extra));
2779 }
2780 serde_json::Value::Object(entry)
2781 })
2782 .collect();
2783
2784 let mut out = serde_json::Map::new();
2785 out.insert("mems".into(), serde_json::json!(mems_detail));
2786 out.insert("mutations".into(), mutations);
2787 out.insert("plugin".into(), plugin);
2788 out
2789}
2790
2791pub fn config_projection_from_settings(
2797 settings: &crate::workspace::WorkspaceSettings,
2798) -> (serde_json::Value, serde_json::Value) {
2799 let mutations = serde_json::json!({ "require_notes": settings.mutations.require_notes });
2800 let plugin_map: serde_json::Map<String, serde_json::Value> = settings
2801 .plugin
2802 .iter()
2803 .map(|(k, v)| {
2804 (
2805 k.clone(),
2806 serde_json::to_value(v).unwrap_or(serde_json::Value::Null),
2807 )
2808 })
2809 .collect();
2810 (mutations, serde_json::Value::Object(plugin_map))
2811}
2812
2813pub(crate) fn section_heading_mismatch_issue(
2828 entity: &crate::entity::Entity,
2829 schema: &TypeDefinition,
2830 key: &str,
2831) -> Option<HealthIssue> {
2832 let def = schema.section(key)?;
2833 let derived = memstead_schema::derive_section_key(&def.heading);
2834 if derived == key {
2835 return None;
2836 }
2837 if !entity
2838 .raw_section_headings
2839 .iter()
2840 .any(|h| h == &def.heading)
2841 {
2842 return None;
2843 }
2844 let landing = match schema.catch_all_section() {
2845 Some(c) => format!(
2846 "the content was absorbed into catch-all section '{}'",
2847 c.key
2848 ),
2849 None => "the content is unreachable under any declared key".to_string(),
2850 };
2851 Some(HealthIssue {
2852 field: key.to_string(),
2853 code: super::HealthIssueCode::SectionHeadingMismatch,
2854 message: format!(
2855 "SECTION_HEADING_MISMATCH: section '{key}' is not missing — its content sits \
2856 under heading '{found}', which derives to '{derived}', not '{key}'; {landing}. \
2857 The schema's declared heading cannot round-trip to its key (expected a heading \
2858 that derives to '{key}'); fix the schema's heading/key pair — new installs of \
2859 such a schema are refused",
2860 found = def.heading,
2861 ),
2862 })
2863}
2864
2865pub fn entity_health(entity: &crate::entity::Entity, schema: &TypeDefinition) -> HealthReport {
2867 let mut issues = Vec::new();
2868
2869 for field in &schema.health_required_fields {
2870 if schema.section(field).is_some() {
2871 let content = entity.sections.get(field.as_str());
2872 if content.is_none_or(|c| c.trim().is_empty()) {
2873 if let Some(issue) = section_heading_mismatch_issue(entity, schema, field) {
2874 issues.push(issue);
2875 } else {
2876 issues.push(HealthIssue {
2877 field: field.clone(),
2878 code: super::HealthIssueCode::Missing,
2879 message: format!("required section '{field}' is empty"),
2880 });
2881 }
2882 }
2883 } else {
2884 let value = entity.metadata.get(field.as_str());
2885 if value.is_none() {
2886 issues.push(HealthIssue {
2887 field: field.clone(),
2888 code: super::HealthIssueCode::Missing,
2889 message: format!("required field '{field}' is missing"),
2890 });
2891 }
2892 }
2893 }
2894
2895 for s in schema.sections.iter().filter(|s| !s.catch_all) {
2899 if schema.health_required_fields.contains(&s.key) {
2900 continue; }
2902 let content = entity.sections.get(s.key.as_str());
2903 if content.is_none_or(|c| c.trim().is_empty())
2904 && let Some(issue) = section_heading_mismatch_issue(entity, schema, &s.key)
2905 {
2906 issues.push(issue);
2907 }
2908 }
2909
2910 let total = schema.health_required_fields.len();
2911 let score = if total > 0 {
2912 (total.saturating_sub(issues.len()) as f32) / (total as f32)
2913 } else {
2914 1.0
2915 };
2916
2917 HealthReport {
2918 id: entity.id.clone(),
2919 title: entity.title.clone(),
2920 score,
2921 issues,
2922 }
2923}
2924
2925pub fn days_since_epoch() -> u64 {
2940 if let Some(pinned) = std::env::var("MEMSTEAD_TODAY")
2941 .ok()
2942 .and_then(|s| crate::engine::due::pinned_days_since_epoch(&s))
2943 {
2944 return pinned;
2945 }
2946 #[cfg(target_arch = "wasm32")]
2947 {
2948 (js_sys::Date::now() / 1000.0) as u64 / 86400
2949 }
2950 #[cfg(not(target_arch = "wasm32"))]
2951 {
2952 std::time::SystemTime::now()
2953 .duration_since(std::time::UNIX_EPOCH)
2954 .unwrap_or_default()
2955 .as_secs()
2956 / 86400
2957 }
2958}
2959
2960pub fn parse_iso_to_days(date: &str) -> Option<u64> {
2963 let date_part = date.split('T').next()?;
2964 let parts: Vec<&str> = date_part.split('-').collect();
2965 if parts.len() != 3 {
2966 return None;
2967 }
2968 let year: u64 = parts[0].parse().ok()?;
2969 let month: u64 = parts[1].parse().ok()?;
2970 let day: u64 = parts[2].parse().ok()?;
2971 Some(ymd_to_days(year, month, day))
2972}
2973
2974fn ymd_to_days(year: u64, month: u64, day: u64) -> u64 {
2977 let y = if month <= 2 { year - 1 } else { year };
2979 let m = if month <= 2 { month + 9 } else { month - 3 };
2980 let era = y / 400;
2981 let yoe = y - era * 400;
2982 let doy = (153 * m + 2) / 5 + day - 1;
2983 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
2984 let days = era * 146097 + doe;
2985 days - 719468
2986}
2987
2988#[cfg(test)]
2989mod tests;