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 path: Vec<String>,
1773 severity: memstead_schema::ConstraintSeverity,
1774 },
1775 TransitionRequiresChecks {
1778 field: String,
1779 to_value: String,
1780 relationships: Vec<String>,
1781 direction: memstead_schema::PropagationDirection,
1782 unchecked: Vec<UncheckedRelated>,
1785 related: usize,
1787 min_related: usize,
1790 severity: memstead_schema::ConstraintSeverity,
1791 },
1792 TransitionRequiresSelfCheck {
1795 field: String,
1796 to_value: String,
1797 check_kind: String,
1798 state: String,
1802 severity: memstead_schema::ConstraintSeverity,
1803 },
1804 MustReach {
1809 relationships: Vec<String>,
1810 direction: memstead_schema::ReachDirection,
1811 terminal_types: Vec<String>,
1812 #[serde(skip_serializing_if = "Option::is_none")]
1813 max_depth: Option<u32>,
1814 severity: memstead_schema::ConstraintSeverity,
1815 },
1816}
1817
1818impl UnsatisfiedConstraint {
1819 pub fn severity(&self) -> memstead_schema::ConstraintSeverity {
1820 match self {
1821 Self::RequiresWhen { severity, .. }
1822 | Self::Unique { severity, .. }
1823 | Self::EnumFromNeighbour { severity, .. }
1824 | Self::StatusPropagation { severity, .. }
1825 | Self::MustReach { severity, .. }
1826 | Self::TransitionRequiresChecks { severity, .. }
1827 | Self::TransitionRequiresSelfCheck { severity, .. } => *severity,
1828 }
1829 }
1830
1831 pub fn describe(&self) -> String {
1833 match self {
1834 Self::RequiresWhen {
1835 field,
1836 when_field,
1837 when_value,
1838 ..
1839 } => format!(
1840 "requires_when: '{field}' is required when {when_field}={when_value} and is unset"
1841 ),
1842 Self::Unique {
1843 fields, colliding, ..
1844 } => format!(
1845 "unique: tuple ({}) collides with '{colliding}'",
1846 fields.join(", ")
1847 ),
1848 Self::EnumFromNeighbour {
1849 field,
1850 value,
1851 rel_type,
1852 section,
1853 ..
1854 } => format!(
1855 "enum_from_neighbour: '{field}' value '{value}' has no backing entry in any \
1856 `{section}` section reached via {rel_type}"
1857 ),
1858 Self::StatusPropagation {
1859 field,
1860 value,
1861 tainted_by,
1862 path,
1863 ..
1864 } => {
1865 format!(
1866 "status_propagation: tainted by '{tainted_by}' ({field}={value}) via {}",
1867 path.join(" → ")
1868 )
1869 }
1870 Self::MustReach {
1871 relationships,
1872 direction,
1873 terminal_types,
1874 max_depth,
1875 ..
1876 } => {
1877 let depth = match max_depth {
1878 Some(d) => format!(" within {d} hop(s)"),
1879 None => String::new(),
1880 };
1881 format!(
1882 "must_reach: no path via [{}] ({direction}) reaches a [{}] entity{depth}",
1883 relationships.join(", "),
1884 terminal_types.join(", ")
1885 )
1886 }
1887 Self::TransitionRequiresChecks {
1888 field,
1889 to_value,
1890 relationships,
1891 unchecked,
1892 related,
1893 min_related,
1894 ..
1895 } => {
1896 if related < min_related {
1897 return format!(
1898 "transition_requires_checks: {field}={to_value} requires at least \
1899 {min_related} related entit{} via [{}] — found {related}",
1900 if *min_related == 1 { "y" } else { "ies" },
1901 relationships.join(", ")
1902 );
1903 }
1904 let listed: Vec<String> = unchecked
1905 .iter()
1906 .map(|u| format!("'{}' ({})", u.id, u.state))
1907 .collect();
1908 format!(
1909 "transition_requires_checks: {field}={to_value} requires a fresh confirming \
1910 check record on every entity related via [{}] — unconfirmed: {}",
1911 relationships.join(", "),
1912 listed.join(", ")
1913 )
1914 }
1915 Self::TransitionRequiresSelfCheck {
1916 field,
1917 to_value,
1918 check_kind,
1919 state,
1920 ..
1921 } => format!(
1922 "transition_requires_self_check: {field}={to_value} requires a fresh confirming \
1923 `{check_kind}` check record on this entity under an identity other than its \
1924 author — derived: {state}"
1925 ),
1926 }
1927 }
1928}
1929
1930#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
1934pub struct UncheckedRelated {
1935 pub id: String,
1936 pub state: String,
1937}
1938
1939pub type CheckStateProvider<'a> =
1947 &'a dyn Fn(&crate::entity::Entity, &str) -> crate::engine::independence::CheckStanding;
1948
1949pub fn unsatisfied_constraints(
1973 store: &Store,
1974 entity: &crate::entity::Entity,
1975 td: &TypeDefinition,
1976 exclude: Option<&crate::entity::EntityId>,
1977 checks: Option<CheckStateProvider<'_>>,
1978) -> Vec<UnsatisfiedConstraint> {
1979 use memstead_schema::ConstraintDef;
1980 td.constraints
1981 .iter()
1982 .filter_map(|c| match c {
1983 ConstraintDef::RequiresWhen {
1984 field,
1985 when_field,
1986 when_value,
1987 severity,
1988 } => {
1989 let triggered = entity
1990 .metadata
1991 .get(when_field.as_str())
1992 .is_some_and(|v| v.to_frontmatter_string() == *when_value);
1993 if !triggered {
1994 return None;
1995 }
1996 let satisfied = entity
1997 .metadata
1998 .get(field.as_str())
1999 .is_some_and(|v| !v.to_frontmatter_string().trim().is_empty())
2000 || entity
2001 .sections
2002 .get(field.as_str())
2003 .is_some_and(|body| !body.trim().is_empty());
2004 if satisfied {
2005 return None;
2006 }
2007 Some(UnsatisfiedConstraint::RequiresWhen {
2008 field: field.clone(),
2009 when_field: when_field.clone(),
2010 when_value: when_value.clone(),
2011 severity: *severity,
2012 })
2013 }
2014 ConstraintDef::Unique { fields, severity } => {
2015 let tuple = tuple_of(entity, fields)?;
2016 let mut colliding: Vec<&str> = store
2017 .all_entities()
2018 .filter(|other| {
2019 !other.stub
2020 && other.mem == entity.mem
2021 && other.entity_type == entity.entity_type
2022 && Some(&other.id) != exclude
2023 && other.id != entity.id
2024 && tuple_of(other, fields).as_ref() == Some(&tuple)
2025 })
2026 .map(|other| other.id.0.as_str())
2027 .collect();
2028 colliding.sort_unstable();
2029 let first = colliding.first()?;
2030 Some(UnsatisfiedConstraint::Unique {
2031 fields: fields.clone(),
2032 values: tuple,
2033 colliding: first.to_string(),
2034 severity: *severity,
2035 })
2036 }
2037 ConstraintDef::EnumFromNeighbour {
2038 field,
2039 rel_type,
2040 section,
2041 severity,
2042 } => {
2043 let value = entity
2044 .metadata
2045 .get(field.as_str())
2046 .map(|v| v.to_frontmatter_string())
2047 .filter(|v| !v.trim().is_empty())?;
2048 let backed = entity
2049 .relationships
2050 .iter()
2051 .filter(|rel| rel.rel_type == *rel_type)
2052 .filter_map(|rel| store.get(&rel.target))
2053 .filter_map(|neighbour| neighbour.sections.get(section.as_str()))
2054 .any(|body| bullet_entries(body).contains(&value));
2055 if backed {
2056 return None;
2057 }
2058 Some(UnsatisfiedConstraint::EnumFromNeighbour {
2059 field: field.clone(),
2060 value,
2061 rel_type: rel_type.clone(),
2062 section: section.clone(),
2063 severity: *severity,
2064 })
2065 }
2066 ConstraintDef::StatusPropagation { .. } => None,
2067 ConstraintDef::TransitionRequiresChecks {
2068 field,
2069 to_value,
2070 relationships,
2071 direction,
2072 min_related,
2073 severity,
2074 } => {
2075 let triggered = entity
2076 .metadata
2077 .get(field.as_str())
2078 .is_some_and(|v| v.to_frontmatter_string() == *to_value);
2079 if !triggered {
2080 return None;
2081 }
2082 let (related, unchecked) = transition_gate_standing(
2083 store,
2084 entity,
2085 relationships,
2086 *direction,
2087 exclude,
2088 checks,
2089 );
2090 if unchecked.is_empty() && related >= *min_related {
2091 return None;
2092 }
2093 Some(UnsatisfiedConstraint::TransitionRequiresChecks {
2094 field: field.clone(),
2095 to_value: to_value.clone(),
2096 relationships: relationships.clone(),
2097 direction: *direction,
2098 unchecked,
2099 related,
2100 min_related: *min_related,
2101 severity: *severity,
2102 })
2103 }
2104 ConstraintDef::TransitionRequiresSelfCheck {
2105 field,
2106 to_value,
2107 check_kind,
2108 severity,
2109 } => {
2110 let triggered = entity
2111 .metadata
2112 .get(field.as_str())
2113 .is_some_and(|v| v.to_frontmatter_string() == *to_value);
2114 if !triggered {
2115 return None;
2116 }
2117 let standing = match checks {
2122 Some(provider) => provider(entity, check_kind),
2123 None => crate::engine::independence::CheckStanding {
2124 state: crate::check::CheckState::NeverChecked,
2125 independence: None,
2126 role: crate::vcs::Role::Unspecified,
2127 },
2128 };
2129 if standing.confirms() {
2130 return None;
2131 }
2132 Some(UnsatisfiedConstraint::TransitionRequiresSelfCheck {
2133 field: field.clone(),
2134 to_value: to_value.clone(),
2135 check_kind: check_kind.clone(),
2136 state: standing.label().to_string(),
2137 severity: *severity,
2138 })
2139 }
2140 })
2141 .collect()
2142}
2143
2144pub fn transition_gate_standing(
2155 store: &Store,
2156 entity: &crate::entity::Entity,
2157 relationships: &[String],
2158 direction: memstead_schema::PropagationDirection,
2159 exclude: Option<&crate::entity::EntityId>,
2160 checks: Option<CheckStateProvider<'_>>,
2161) -> (usize, Vec<UncheckedRelated>) {
2162 let related: Vec<&crate::entity::Entity> = match direction {
2163 memstead_schema::PropagationDirection::Outgoing => entity
2164 .relationships
2165 .iter()
2166 .filter(|rel| relationships.contains(&rel.rel_type))
2167 .filter_map(|rel| store.get(&rel.target))
2168 .collect(),
2169 memstead_schema::PropagationDirection::Incoming => store
2170 .all_entities()
2171 .filter(|other| {
2172 other.id != entity.id
2173 && Some(&other.id) != exclude
2174 && other
2175 .relationships
2176 .iter()
2177 .any(|rel| rel.target == entity.id && relationships.contains(&rel.rel_type))
2178 })
2179 .collect(),
2180 };
2181 let total = related.len();
2182 let mut unchecked: Vec<UncheckedRelated> = related
2183 .into_iter()
2184 .filter_map(|rel_entity| {
2185 let standing = match checks {
2189 Some(provider) => {
2190 provider(rel_entity, crate::check::CheckKind::Verification.as_str())
2191 }
2192 None => crate::engine::independence::CheckStanding {
2193 state: crate::check::CheckState::NeverChecked,
2194 independence: None,
2195 role: crate::vcs::Role::Unspecified,
2196 },
2197 };
2198 if standing.confirms() {
2199 None
2200 } else {
2201 Some(UncheckedRelated {
2202 id: rel_entity.id.0.clone(),
2203 state: standing.label().to_string(),
2204 })
2205 }
2206 })
2207 .collect();
2208 unchecked.sort_by(|a, b| a.id.cmp(&b.id));
2209 (total, unchecked)
2210}
2211
2212fn tuple_of(entity: &crate::entity::Entity, fields: &[String]) -> Option<Vec<String>> {
2216 fields
2217 .iter()
2218 .map(|f| {
2219 entity
2220 .metadata
2221 .get(f.as_str())
2222 .map(|v| v.to_frontmatter_string())
2223 .filter(|v| !v.trim().is_empty())
2224 })
2225 .collect()
2226}
2227
2228fn bullet_entries(body: &str) -> Vec<String> {
2231 let masked = crate::markdown::mask_code_blocks_and_spans(body);
2236 body.lines()
2237 .zip(masked.lines())
2238 .filter_map(|(line, masked_line)| {
2239 let m = masked_line.trim_start();
2240 if m.starts_with("- ") || m.starts_with("* ") {
2241 let t = line.trim_start();
2242 t.strip_prefix("- ")
2243 .or_else(|| t.strip_prefix("* "))
2244 .map(|e| e.trim().to_string())
2245 } else {
2246 None
2247 }
2248 })
2249 .collect()
2250}
2251
2252#[derive(Debug, Clone, serde::Serialize)]
2257pub struct ConstraintFindingReport {
2258 pub id: crate::entity::EntityId,
2259 pub title: String,
2260 pub entity_type: String,
2261 pub mem: String,
2262 pub violations: Vec<UnsatisfiedConstraint>,
2263 #[serde(skip_serializing_if = "Vec::is_empty")]
2267 pub format_violations: Vec<crate::section_format::SectionFormatViolation>,
2268}
2269
2270pub fn collect_constraint_findings(
2280 store: &Store,
2281 mem_filter: Option<&str>,
2282 mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
2283 checks: Option<CheckStateProvider<'_>>,
2284) -> Vec<ConstraintFindingReport> {
2285 use memstead_schema::ConstraintDef;
2286 type Bucket = (
2287 Vec<UnsatisfiedConstraint>,
2288 Vec<crate::section_format::SectionFormatViolation>,
2289 );
2290 let mut by_entity: std::collections::BTreeMap<String, Bucket> = Default::default();
2291
2292 let needs_reverse = mem_schemas.values().any(|s| {
2296 s.types.values().any(|t| {
2297 t.must_reach
2298 .iter()
2299 .any(|ob| ob.direction == memstead_schema::ReachDirection::In)
2300 })
2301 });
2302 let reverse: ReverseIndex = if needs_reverse {
2303 build_reverse_index(store)
2304 } else {
2305 ReverseIndex::default()
2306 };
2307
2308 for entity in store.all_entities() {
2309 if entity.stub {
2310 continue;
2311 }
2312 if let Some(v) = mem_filter
2313 && entity.mem != v
2314 {
2315 continue;
2316 }
2317 let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
2318 continue;
2319 };
2320 let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
2321 continue;
2322 };
2323
2324 for def in &td.sections {
2329 if def.compiled_content.is_none() {
2330 continue;
2331 }
2332 let Some(body) = entity.sections.get(def.key.as_str()) else {
2333 continue;
2334 };
2335 let violations = crate::section_format::check_section_format(def, body);
2336 if !violations.is_empty() {
2337 by_entity
2338 .entry(entity.id.0.clone())
2339 .or_default()
2340 .1
2341 .extend(violations);
2342 }
2343 }
2344
2345 for ob in &td.must_reach {
2350 if !reaches_terminal(store, &reverse, &entity.id, ob) {
2351 by_entity.entry(entity.id.0.clone()).or_default().0.push(
2352 UnsatisfiedConstraint::MustReach {
2353 relationships: ob.relationships.clone(),
2354 direction: ob.direction,
2355 terminal_types: ob.terminal_types.clone(),
2356 max_depth: ob.max_depth,
2357 severity: ob.severity,
2358 },
2359 );
2360 }
2361 }
2362
2363 if td.constraints.is_empty() {
2364 continue;
2365 }
2366
2367 let violations = unsatisfied_constraints(store, entity, td, None, checks);
2369 if !violations.is_empty() {
2370 by_entity
2371 .entry(entity.id.0.clone())
2372 .or_default()
2373 .0
2374 .extend(violations);
2375 }
2376 }
2377
2378 let mut sources: Vec<&crate::entity::Entity> =
2391 store.all_entities().filter(|e| !e.stub).collect();
2392 sources.sort_by(|a, b| a.id.0.cmp(&b.id.0));
2393 for entity in sources {
2394 let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
2395 continue;
2396 };
2397 let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
2398 continue;
2399 };
2400 for c in &td.constraints {
2401 let ConstraintDef::StatusPropagation {
2402 field,
2403 value,
2404 rel_type,
2405 rel_types,
2406 direction,
2407 severity,
2408 } = c
2409 else {
2410 continue;
2411 };
2412 let terminal = entity
2413 .metadata
2414 .get(field.as_str())
2415 .is_some_and(|v| v.to_frontmatter_string() == *value);
2416 if !terminal {
2417 continue;
2418 }
2419 let set = c
2420 .propagation_rel_types()
2421 .expect("StatusPropagation always yields a set");
2422 for (tainted, path) in reach_transitively(store, &entity.id, &set, *direction) {
2423 if let Some(v) = mem_filter
2424 && tainted.mem() != v
2425 {
2426 continue;
2427 }
2428 by_entity.entry(tainted.0.clone()).or_default().0.push(
2429 UnsatisfiedConstraint::StatusPropagation {
2430 field: field.clone(),
2431 value: value.clone(),
2432 rel_type: rel_type.clone(),
2433 rel_types: rel_types.clone(),
2434 tainted_by: entity.id.to_string(),
2435 path: path.iter().map(ToString::to_string).collect(),
2436 severity: *severity,
2437 },
2438 );
2439 }
2440 }
2441 }
2442
2443 let mut out: Vec<ConstraintFindingReport> = by_entity
2444 .into_iter()
2445 .filter_map(|(id, (violations, format_violations))| {
2446 let id = crate::entity::EntityId(id);
2447 let entity = store.get(&id)?;
2448 Some(ConstraintFindingReport {
2449 id,
2450 title: entity.title.clone(),
2451 entity_type: entity.entity_type.clone(),
2452 mem: entity.mem.clone(),
2453 violations,
2454 format_violations,
2455 })
2456 })
2457 .collect();
2458 out.sort_by(|a, b| a.mem.cmp(&b.mem).then_with(|| a.id.0.cmp(&b.id.0)));
2459 out
2460}
2461
2462fn reach_transitively(
2472 store: &Store,
2473 start: &crate::entity::EntityId,
2474 rel_types: &[String],
2475 direction: memstead_schema::PropagationDirection,
2476) -> Vec<(crate::entity::EntityId, Vec<crate::entity::EntityId>)> {
2477 use memstead_schema::PropagationDirection;
2478 let mut parent: std::collections::HashMap<crate::entity::EntityId, crate::entity::EntityId> =
2479 Default::default();
2480 let mut seen: std::collections::HashSet<crate::entity::EntityId> =
2481 std::iter::once(start.clone()).collect();
2482 let mut frontier = std::collections::VecDeque::from([start.clone()]);
2483 let mut reached = Vec::new();
2484 while let Some(current) = frontier.pop_front() {
2485 let mut next: Vec<crate::entity::EntityId> = match direction {
2486 PropagationDirection::Incoming => store
2487 .all_entities()
2488 .filter(|e| {
2489 e.relationships
2490 .iter()
2491 .any(|r| rel_types.iter().any(|n| n == &r.rel_type) && r.target == current)
2492 })
2493 .map(|e| e.id.clone())
2494 .collect(),
2495 PropagationDirection::Outgoing => store
2496 .get(¤t)
2497 .map(|e| {
2498 e.relationships
2499 .iter()
2500 .filter(|r| rel_types.iter().any(|n| n == &r.rel_type))
2501 .map(|r| r.target.clone())
2502 .collect()
2503 })
2504 .unwrap_or_default(),
2505 };
2506 next.sort_by(|a, b| a.0.cmp(&b.0));
2507 for id in next {
2508 if seen.insert(id.clone()) {
2509 parent.insert(id.clone(), current.clone());
2510 if store.get(&id).is_some_and(|e| !e.stub) {
2511 let mut path = vec![id.clone()];
2512 let mut at = id.clone();
2513 while let Some(p) = parent.get(&at) {
2514 path.push(p.clone());
2515 at = p.clone();
2516 }
2517 path.reverse();
2518 reached.push((id.clone(), path));
2519 }
2520 frontier.push_back(id);
2521 }
2522 }
2523 }
2524 reached
2525}
2526
2527type ReverseIndex =
2532 std::collections::HashMap<crate::entity::EntityId, Vec<(String, crate::entity::EntityId)>>;
2533
2534fn build_reverse_index(store: &Store) -> ReverseIndex {
2535 let mut idx = ReverseIndex::default();
2536 for entity in store.all_entities() {
2537 for rel in &entity.relationships {
2538 idx.entry(rel.target.clone())
2539 .or_default()
2540 .push((rel.rel_type.clone(), entity.id.clone()));
2541 }
2542 }
2543 idx
2544}
2545
2546fn reaches_terminal(
2555 store: &Store,
2556 reverse: &ReverseIndex,
2557 start: &crate::entity::EntityId,
2558 ob: &memstead_schema::MustReach,
2559) -> bool {
2560 use memstead_schema::ReachDirection;
2561 let mut seen: std::collections::HashSet<crate::entity::EntityId> =
2562 std::iter::once(start.clone()).collect();
2563 let mut frontier = vec![start.clone()];
2564 let mut depth: u32 = 0;
2565 while !frontier.is_empty() {
2566 if let Some(max) = ob.max_depth
2567 && depth >= max
2568 {
2569 return false;
2570 }
2571 depth += 1;
2572 let mut next_frontier = Vec::new();
2573 for current in frontier {
2574 let next: Vec<crate::entity::EntityId> = match ob.direction {
2575 ReachDirection::Out => store
2576 .get(¤t)
2577 .map(|e| {
2578 e.relationships
2579 .iter()
2580 .filter(|r| ob.relationships.iter().any(|n| n == &r.rel_type))
2581 .map(|r| r.target.clone())
2582 .collect()
2583 })
2584 .unwrap_or_default(),
2585 ReachDirection::In => reverse
2586 .get(¤t)
2587 .map(|sources| {
2588 sources
2589 .iter()
2590 .filter(|(rel, _)| ob.relationships.iter().any(|n| n == rel))
2591 .map(|(_, src)| src.clone())
2592 .collect()
2593 })
2594 .unwrap_or_default(),
2595 };
2596 for id in next {
2597 if seen.insert(id.clone()) {
2598 if store.get(&id).is_some_and(|e| {
2599 !e.stub && ob.terminal_types.iter().any(|t| t == &e.entity_type)
2600 }) {
2601 return true;
2602 }
2603 next_frontier.push(id);
2604 }
2605 }
2606 }
2607 frontier = next_frontier;
2608 }
2609 false
2610}
2611
2612#[derive(Debug, Clone, serde::Serialize)]
2617pub struct SignalReport {
2618 pub id: crate::entity::EntityId,
2619 pub title: String,
2620 pub entity_type: String,
2621 pub mem: String,
2622 pub signals: Vec<super::signals::ComputedSignal>,
2624}
2625
2626impl SignalReport {
2627 pub fn has_warn(&self) -> bool {
2631 self.signals
2632 .iter()
2633 .any(|s| s.level == Some(memstead_schema::SignalLevel::Warn))
2634 }
2635}
2636
2637pub fn collect_signal_reports(
2641 store: &Store,
2642 mem_filter: Option<&str>,
2643 mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
2644) -> Vec<SignalReport> {
2645 let mut out = Vec::new();
2646 for entity in store.all_entities() {
2647 if entity.stub {
2648 continue;
2649 }
2650 if let Some(v) = mem_filter
2651 && entity.mem != v
2652 {
2653 continue;
2654 }
2655 let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
2656 continue;
2657 };
2658 let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
2659 continue;
2660 };
2661 if td.signals.is_empty() {
2662 continue;
2663 }
2664 let above: Vec<super::signals::ComputedSignal> =
2665 super::signals::compute_signals(store, td, &entity.id)
2666 .into_iter()
2667 .filter(|s| s.level.is_some())
2668 .collect();
2669 if above.is_empty() {
2670 continue;
2671 }
2672 out.push(SignalReport {
2673 id: entity.id.clone(),
2674 title: entity.title.clone(),
2675 entity_type: entity.entity_type.clone(),
2676 mem: entity.mem.clone(),
2677 signals: above,
2678 });
2679 }
2680 out.sort_by(|a, b| a.mem.cmp(&b.mem).then_with(|| a.id.0.cmp(&b.id.0)));
2681 out
2682}
2683
2684#[derive(Debug, Clone, serde::Serialize)]
2689pub struct SchemaFormatDefect {
2690 pub schema: String,
2691 pub type_name: String,
2692 pub section: String,
2693 pub problems: Vec<String>,
2694}
2695
2696pub fn collect_schema_format_defects(
2700 mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
2701) -> Vec<SchemaFormatDefect> {
2702 let mut seen: std::collections::BTreeSet<String> = Default::default();
2703 let mut out = Vec::new();
2704 let mut schemas: Vec<&Arc<memstead_schema::Schema>> = mem_schemas.values().collect();
2705 schemas.sort_by_key(|s| (s.manifest.name.clone(), s.version.clone()));
2706 for schema in schemas {
2707 let schema_ref = format!("{}@{}", schema.manifest.name, schema.version);
2708 if !seen.insert(schema_ref.clone()) {
2709 continue;
2710 }
2711 for td in schema.types.values() {
2712 for section in &td.sections {
2713 if !section.format_problems.is_empty() {
2714 out.push(SchemaFormatDefect {
2715 schema: schema_ref.clone(),
2716 type_name: td.name.clone(),
2717 section: section.key.clone(),
2718 problems: section.format_problems.clone(),
2719 });
2720 }
2721 }
2722 }
2723 }
2724 out.sort_by(|a, b| {
2725 (&a.schema, &a.type_name, &a.section).cmp(&(&b.schema, &b.type_name, &b.section))
2726 });
2727 out
2728}
2729
2730#[derive(Debug, Clone, serde::Serialize)]
2738pub struct MissingRequiredOutgoingReport {
2739 pub id: crate::entity::EntityId,
2740 pub title: String,
2741 pub entity_type: String,
2742 pub mem: String,
2743 pub missing: Vec<super::MissingRequiredOutgoingBlock>,
2744}
2745
2746pub fn config_projection(
2759 engine: &crate::Engine,
2760 writable_mems: &[String],
2761 mutations: serde_json::Value,
2762 plugin: serde_json::Value,
2763) -> serde_json::Map<String, serde_json::Value> {
2764 let backend_by_mem: std::collections::HashMap<&str, (&'static str, bool)> = engine
2769 .mounts()
2770 .iter()
2771 .map(|m| {
2772 (
2773 m.mem.as_str(),
2774 (m.storage.backend_id(), m.storage.is_durable()),
2775 )
2776 })
2777 .collect();
2778 let mems_detail: Vec<serde_json::Value> = writable_mems
2779 .iter()
2780 .map(|name| {
2781 let origin = engine
2782 .mem_router()
2783 .origin_for_mem(name)
2784 .map(|o| o.kind())
2785 .unwrap_or("explicit");
2786 let mut entry = serde_json::Map::new();
2787 entry.insert("name".into(), serde_json::json!(name));
2788 entry.insert("origin".into(), serde_json::json!(origin));
2789 if let Some((storage, durable)) = backend_by_mem.get(name.as_str()).copied() {
2790 entry.insert("storage".into(), serde_json::json!(storage));
2791 entry.insert("durable".into(), serde_json::json!(durable));
2792 }
2793 let mut vcs_obj = serde_json::Map::new();
2794 if let Ok(gitdir) = engine.gitdir_for(name) {
2795 vcs_obj.insert("gitdir".into(), serde_json::json!(gitdir));
2796 }
2797 if let Ok(worktree) = engine.worktree_for(name) {
2798 vcs_obj.insert("worktree".into(), serde_json::json!(worktree));
2799 }
2800 if let Some(sha) = engine.mem_head_sha(name).ok().flatten() {
2801 vcs_obj.insert("head".into(), serde_json::json!(sha));
2802 }
2803 if !vcs_obj.is_empty() {
2804 entry.insert("vcs".into(), serde_json::Value::Object(vcs_obj));
2805 }
2806 if let Some(cfg) = engine.mem_config_for(name) {
2807 if let Some(title) = &cfg.title {
2811 entry.insert("title".into(), serde_json::json!(title));
2812 }
2813 if let Some(subject) = &cfg.subject {
2814 entry.insert("subject".into(), serde_json::json!(subject));
2815 }
2816 let guidance = serde_json::Map::from_iter(
2817 cfg.write_guidance
2818 .iter()
2819 .map(|(k, v)| (k.clone(), v.clone())),
2820 );
2821 entry.insert("write_guidance".into(), serde_json::Value::Object(guidance));
2822 let extra = serde_json::Map::from_iter(
2823 cfg.extra.iter().map(|(k, v)| (k.clone(), v.clone())),
2824 );
2825 entry.insert("extra".into(), serde_json::Value::Object(extra));
2826 }
2827 serde_json::Value::Object(entry)
2828 })
2829 .collect();
2830
2831 let mut out = serde_json::Map::new();
2832 out.insert("mems".into(), serde_json::json!(mems_detail));
2833 out.insert("mutations".into(), mutations);
2834 out.insert("plugin".into(), plugin);
2835 out
2836}
2837
2838pub fn config_projection_from_settings(
2844 settings: &crate::workspace::WorkspaceSettings,
2845) -> (serde_json::Value, serde_json::Value) {
2846 let mutations = serde_json::json!({ "require_notes": settings.mutations.require_notes });
2847 let plugin_map: serde_json::Map<String, serde_json::Value> = settings
2848 .plugin
2849 .iter()
2850 .map(|(k, v)| {
2851 (
2852 k.clone(),
2853 serde_json::to_value(v).unwrap_or(serde_json::Value::Null),
2854 )
2855 })
2856 .collect();
2857 (mutations, serde_json::Value::Object(plugin_map))
2858}
2859
2860pub(crate) fn section_heading_mismatch_issue(
2875 entity: &crate::entity::Entity,
2876 schema: &TypeDefinition,
2877 key: &str,
2878) -> Option<HealthIssue> {
2879 let def = schema.section(key)?;
2880 let derived = memstead_schema::derive_section_key(&def.heading);
2881 if derived == key {
2882 return None;
2883 }
2884 if !entity
2885 .raw_section_headings
2886 .iter()
2887 .any(|h| h == &def.heading)
2888 {
2889 return None;
2890 }
2891 let landing = match schema.catch_all_section() {
2892 Some(c) => format!(
2893 "the content was absorbed into catch-all section '{}'",
2894 c.key
2895 ),
2896 None => "the content is unreachable under any declared key".to_string(),
2897 };
2898 Some(HealthIssue {
2899 field: key.to_string(),
2900 code: super::HealthIssueCode::SectionHeadingMismatch,
2901 message: format!(
2902 "SECTION_HEADING_MISMATCH: section '{key}' is not missing — its content sits \
2903 under heading '{found}', which derives to '{derived}', not '{key}'; {landing}. \
2904 The schema's declared heading cannot round-trip to its key (expected a heading \
2905 that derives to '{key}'); fix the schema's heading/key pair — new installs of \
2906 such a schema are refused",
2907 found = def.heading,
2908 ),
2909 })
2910}
2911
2912pub fn entity_health(entity: &crate::entity::Entity, schema: &TypeDefinition) -> HealthReport {
2914 let mut issues = Vec::new();
2915
2916 for field in &schema.health_required_fields {
2917 if schema.section(field).is_some() {
2918 let content = entity.sections.get(field.as_str());
2919 if content.is_none_or(|c| c.trim().is_empty()) {
2920 if let Some(issue) = section_heading_mismatch_issue(entity, schema, field) {
2921 issues.push(issue);
2922 } else {
2923 issues.push(HealthIssue {
2924 field: field.clone(),
2925 code: super::HealthIssueCode::Missing,
2926 message: format!("required section '{field}' is empty"),
2927 });
2928 }
2929 }
2930 } else {
2931 let value = entity.metadata.get(field.as_str());
2932 if value.is_none() {
2933 issues.push(HealthIssue {
2934 field: field.clone(),
2935 code: super::HealthIssueCode::Missing,
2936 message: format!("required field '{field}' is missing"),
2937 });
2938 }
2939 }
2940 }
2941
2942 for s in schema.sections.iter().filter(|s| !s.catch_all) {
2946 if schema.health_required_fields.contains(&s.key) {
2947 continue; }
2949 let content = entity.sections.get(s.key.as_str());
2950 if content.is_none_or(|c| c.trim().is_empty())
2951 && let Some(issue) = section_heading_mismatch_issue(entity, schema, &s.key)
2952 {
2953 issues.push(issue);
2954 }
2955 }
2956
2957 let total = schema.health_required_fields.len();
2958 let score = if total > 0 {
2959 (total.saturating_sub(issues.len()) as f32) / (total as f32)
2960 } else {
2961 1.0
2962 };
2963
2964 HealthReport {
2965 id: entity.id.clone(),
2966 title: entity.title.clone(),
2967 score,
2968 issues,
2969 }
2970}
2971
2972pub fn days_since_epoch() -> u64 {
2987 if let Some(pinned) = std::env::var("MEMSTEAD_TODAY")
2988 .ok()
2989 .and_then(|s| crate::engine::due::pinned_days_since_epoch(&s))
2990 {
2991 return pinned;
2992 }
2993 #[cfg(target_arch = "wasm32")]
2994 {
2995 (js_sys::Date::now() / 1000.0) as u64 / 86400
2996 }
2997 #[cfg(not(target_arch = "wasm32"))]
2998 {
2999 std::time::SystemTime::now()
3000 .duration_since(std::time::UNIX_EPOCH)
3001 .unwrap_or_default()
3002 .as_secs()
3003 / 86400
3004 }
3005}
3006
3007pub fn parse_iso_to_days(date: &str) -> Option<u64> {
3010 let date_part = date.split('T').next()?;
3011 let parts: Vec<&str> = date_part.split('-').collect();
3012 if parts.len() != 3 {
3013 return None;
3014 }
3015 let year: u64 = parts[0].parse().ok()?;
3016 let month: u64 = parts[1].parse().ok()?;
3017 let day: u64 = parts[2].parse().ok()?;
3018 Some(ymd_to_days(year, month, day))
3019}
3020
3021fn ymd_to_days(year: u64, month: u64, day: u64) -> u64 {
3024 let y = if month <= 2 { year - 1 } else { year };
3026 let m = if month <= 2 { month + 9 } else { month - 3 };
3027 let era = y / 400;
3028 let yoe = y - era * 400;
3029 let doy = (153 * m + 2) / 5 + day - 1;
3030 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
3031 let days = era * 146097 + doe;
3032 days - 719468
3033}
3034
3035#[cfg(test)]
3036mod tests;