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).in_standing_order())
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");
596 let (reading, execs) = engine.independence_of(e, check, &touches);
597 if let Some(execs) = execs {
598 executors.insert(id.clone(), serde_json::json!(execs.identities));
599 }
600 match reading {
601 crate::engine::independence::Independence::SelfChecked => self_checked.push(id),
602 crate::engine::independence::Independence::ConfirmedIndependent => {
603 confirmed_independent.push(id)
604 }
605 crate::engine::independence::Independence::Unconfirmable => unconfirmable.push(id),
606 }
607 }
608 let mut m = serde_json::Map::new();
609 for (k, v) in counts {
610 m.insert(k.to_string(), serde_json::json!(v));
611 }
612 let mut c = serde_json::Map::new();
613 for (k, v) in conformance_counts {
614 c.insert(k.to_string(), serde_json::json!(v));
615 }
616 m.insert("conformance".into(), serde_json::Value::Object(c));
617 m.insert(
621 "foreign_kinds".into(),
622 serde_json::to_value(&foreign_kinds).unwrap_or(serde_json::json!({})),
623 );
624 m.insert("findings".into(), serde_json::Value::Object(findings));
625 if let Some(note) = sealed_note {
628 m.insert("sealed".into(), note);
629 }
630 m.insert(
631 "independence".into(),
632 serde_json::json!({
633 "self_checked": capped(self_checked),
634 "confirmed_independent": capped(confirmed_independent),
635 "unconfirmable": capped(unconfirmable),
636 "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 every identity that wrote it up to the write the check saw",
637 "executors": serde_json::Value::Object(executors),
638 "readings": serde_json::Value::Object(readings),
639 }),
640 );
641 out.insert(mem, serde_json::Value::Object(m));
642 }
643 serde_json::Value::Object(out)
644}
645
646#[derive(Debug, Clone, serde::Serialize)]
652pub struct DerivationFinding {
653 pub source: crate::entity::EntityId,
654 pub rel_type: String,
655 pub target: crate::entity::EntityId,
656 pub state: String,
658 #[serde(skip_serializing_if = "Option::is_none")]
660 pub baseline: Option<String>,
661 pub current: String,
663}
664
665pub fn health_stale_derivations_axis(
670 engine: &crate::engine::Engine,
671 mem_filter: Option<&str>,
672) -> serde_json::Value {
673 let mut mems: Vec<String> = engine.mem_names().iter().map(|s| s.to_string()).collect();
674 mems.sort();
675 let mut out = serde_json::Map::new();
676 for mem in mems {
677 if let Some(f) = mem_filter
678 && f != mem
679 {
680 continue;
681 }
682 let findings = engine.derivation_report(&mem).unwrap_or_default();
683 out.insert(
684 mem,
685 serde_json::to_value(&findings).unwrap_or(serde_json::Value::Array(Vec::new())),
686 );
687 }
688 serde_json::Value::Object(out)
689}
690
691pub const OPEN_QUESTIONS_ITEM_CAP: usize = 20;
695
696pub fn health_open_questions_axis(
712 engine: &crate::engine::Engine,
713 mem_filter: Option<&str>,
714) -> serde_json::Value {
715 let cap = OPEN_QUESTIONS_ITEM_CAP;
716 let capped = |mut items: Vec<serde_json::Value>| -> serde_json::Value {
717 let count = items.len();
718 let more = count.saturating_sub(cap);
719 items.truncate(cap);
720 let mut o = serde_json::Map::new();
721 o.insert("count".into(), serde_json::json!(count));
722 o.insert("items".into(), serde_json::Value::Array(items));
723 if more > 0 {
724 o.insert("more".into(), serde_json::json!(more));
725 }
726 serde_json::Value::Object(o)
727 };
728
729 let bindings: Vec<(String, String)> = engine
733 .workspace_root()
734 .and_then(|root| crate::pipeline_store::load_pipeline_configs(root).ok())
735 .map(|c| {
736 c.bindings
737 .iter()
738 .map(|r| (r.config.destination_mem.clone(), r.name.clone()))
739 .collect()
740 })
741 .unwrap_or_default();
742 let mounted: Vec<String> = engine.mem_names().iter().map(|s| s.to_string()).collect();
743
744 let mut mems: Vec<String> = mounted.clone();
745 mems.sort();
746 let mut out = serde_json::Map::new();
747 for mem in &mems {
748 if let Some(f) = mem_filter
749 && f != mem
750 {
751 continue;
752 }
753
754 let stubs = capped(
756 engine
757 .store()
758 .all_entities()
759 .filter(|e| e.stub && e.id.mem() == mem)
760 .map(|e| serde_json::json!({ "kind": "stub", "id": e.id.to_string() }))
761 .collect(),
762 );
763
764 let (mut recheck, mut unresolvable, mut unobserved, mut dangling_rows) =
777 (Vec::new(), Vec::new(), Vec::new(), Vec::new());
778 let mut span_absent = Vec::new();
782 let mut aging = Vec::new();
785 let mut entity_end_unreconciled: Option<String> = None;
786 if let Ok(report) = engine.verify_mem_anchors(mem) {
787 entity_end_unreconciled = report.unreconciled.clone();
788 for a in &report.anchors {
789 if let Some(days) = a.unobserved_for_days
790 && days > 0
791 {
792 aging.push(serde_json::json!({
793 "kind": "anchor_aging",
794 "id": a.entity_id,
795 "artifact": a.artifact,
796 "state": a.state,
797 "observed_at": a.observed_at,
798 "unobserved_for_days": days,
799 "note": format!("unobserved for {days} days"),
800 }));
801 }
802 let item = serde_json::json!({
803 "kind": format!("anchor_{}", a.state),
804 "id": a.entity_id,
805 "artifact": a.artifact,
806 });
807 match a.state.as_str() {
808 "recheck" => recheck.push(item),
809 "orphaned" => unresolvable.push(item),
812 "span_absent" => span_absent.push(item),
813 "unobserved" => unobserved.push(item),
814 "dangling" => dangling_rows.push(item),
815 _ => {}
816 }
817 }
818 }
819
820 let constraints = capped(
823 engine
824 .constraint_findings(Some(mem))
825 .iter()
826 .map(|r| {
827 serde_json::json!({
828 "kind": "unsatisfied_constraint",
829 "id": r.id.to_string(),
830 "violations": r.violations.len(),
831 })
832 })
833 .collect(),
834 );
835
836 let dangling = capped(
842 collect_dangling_links(engine.store(), Some(mem))
843 .iter()
844 .map(|d| {
845 serde_json::json!({
846 "kind": d.kind.code(),
847 "id": d.from.to_string(),
848 "target": d.target_id.to_string(),
849 "repair": d.kind.repair(),
850 })
851 })
852 .collect(),
853 );
854
855 let mut process = Vec::new();
865 let mem_bindings: Vec<&String> = bindings
866 .iter()
867 .filter(|(d, _)| d == mem)
868 .map(|(_, b)| b)
869 .collect();
870 let mut resolutions: Vec<(Option<String>, crate::binding_run::ProcessMemResolution)> =
871 Vec::new();
872 if mem_bindings.is_empty() {
873 let r = crate::binding_run::resolve_process_mem(engine, mem, "");
874 if r.declared {
875 resolutions.push((None, r));
876 }
877 } else {
878 for binding in &mem_bindings {
879 let derived =
883 crate::binding_run::derived_process_mem_name(&format!("{mem}/{binding}"));
884 resolutions.push((
885 Some((*binding).clone()),
886 crate::binding_run::resolve_process_mem(engine, mem, &derived),
887 ));
888 }
889 }
890 for (binding, r) in resolutions {
891 if r.mounted {
892 let mut open = Vec::new();
893 let mut searched = Vec::new();
894 for e in engine
895 .store()
896 .all_entities()
897 .filter(|e| !e.stub && e.id.mem() == r.mem.as_str())
898 {
899 let item = serde_json::json!({
900 "kind": e.entity_type,
901 "id": e.id.to_string(),
902 "title": e.title,
903 });
904 if e.entity_type == "negative_finding" {
905 searched.push(item);
906 } else {
907 open.push(item);
908 }
909 }
910 let by_id = |a: &serde_json::Value, b: &serde_json::Value| {
915 a["id"].as_str().cmp(&b["id"].as_str())
916 };
917 open.sort_by(by_id);
918 searched.sort_by(by_id);
919 process.push(serde_json::json!({
920 "binding": binding,
921 "process_mem": r.mem,
922 "declared": r.declared,
923 "resolvable": true,
924 "open_entries": capped(open),
925 "already_searched": capped(searched),
926 }));
927 } else if r.declared {
928 process.push(serde_json::json!({
929 "binding": binding,
930 "process_mem": r.mem,
931 "declared": true,
932 "resolvable": false,
933 "finding": "DECLARED_PROCESS_MEM_MISSING",
934 }));
935 } else {
936 process.push(serde_json::json!({
937 "binding": binding,
938 "resolvable": false,
939 }));
940 }
941 }
942
943 let (mut missing, mut unchecked) = (Vec::new(), Vec::new());
949 if let Some(schema) = engine.schema_for(mem) {
950 for entity in engine
951 .store()
952 .all_entities()
953 .filter(|e| !e.stub && e.id.mem() == mem)
954 {
955 let Some(td) = schema.types.get(&entity.entity_type) else {
956 continue;
957 };
958 let Some(res) = &td.resolution else { continue };
959 if let Some(field) = &res.status_field {
960 let open = match entity.metadata.get(field) {
961 Some(crate::entity::MetadataValue::String(s)) => {
962 res.open_values.contains(s)
963 }
964 _ => false,
965 };
966 if !open {
967 continue;
968 }
969 }
970 let has_condition = entity
971 .sections
972 .get(&res.condition_section)
973 .is_some_and(|body| !body.trim().is_empty());
974 if !has_condition {
975 missing.push(serde_json::json!({
976 "kind": "resolution_missing",
977 "id": entity.id.to_string(),
978 "section": res.condition_section,
979 }));
980 continue;
981 }
982 let kind = res.check_kind.as_deref().unwrap_or("verification");
983 let checked = crate::check::RecordKind::from_wire(kind).is_some()
987 && engine
988 .latest_check_record(mem, &entity.id.0, kind)
989 .is_some_and(|r| r.verdict == "ok" && r.entity_hash == entity.content_hash);
990 if !checked {
991 unchecked.push(serde_json::json!({
992 "kind": "resolution_unchecked",
993 "id": entity.id.to_string(),
994 "section": res.condition_section,
995 "check_kind": kind,
996 }));
997 }
998 }
999 }
1000 let resolution_missing = capped(missing);
1001 let resolution_unchecked = capped(unchecked);
1002
1003 let total_open = stubs["count"].as_u64().unwrap_or(0)
1004 + resolution_missing["count"].as_u64().unwrap_or(0)
1005 + resolution_unchecked["count"].as_u64().unwrap_or(0)
1006 + recheck.len() as u64
1007 + unresolvable.len() as u64
1008 + span_absent.len() as u64
1009 + unobserved.len() as u64
1010 + dangling_rows.len() as u64
1011 + aging.len() as u64
1012 + constraints["count"].as_u64().unwrap_or(0)
1013 + dangling["count"].as_u64().unwrap_or(0)
1014 + process
1015 .iter()
1016 .filter_map(|p| p["open_entries"]["count"].as_u64())
1017 .sum::<u64>();
1018
1019 let mut entry = serde_json::Map::new();
1020 entry.insert("stubs".into(), stubs);
1021 entry.insert("anchors_recheck".into(), capped(recheck));
1022 entry.insert("anchors_unresolvable".into(), capped(unresolvable));
1023 entry.insert("anchors_span_absent".into(), capped(span_absent));
1024 entry.insert("anchors_unobserved".into(), capped(unobserved));
1028 entry.insert("anchors_dangling".into(), capped(dangling_rows));
1029 entry.insert("anchors_aging".into(), capped(aging));
1030 if let Some(why) = entity_end_unreconciled {
1031 entry.insert("entity_end_unreconciled".into(), serde_json::json!(why));
1032 }
1033 entry.insert("unsatisfied_constraints".into(), constraints);
1034 entry.insert("dangling_links".into(), dangling);
1035 entry.insert("resolution_missing".into(), resolution_missing);
1036 entry.insert("resolution_unchecked".into(), resolution_unchecked);
1037 if !process.is_empty() {
1038 entry.insert("process".into(), serde_json::Value::Array(process));
1039 } else {
1040 entry.insert("process_mem_resolvable".into(), serde_json::json!(false));
1043 }
1044 entry.insert("total_open".into(), serde_json::json!(total_open));
1045 out.insert(mem.clone(), serde_json::Value::Object(entry));
1046 }
1047 let mut top = serde_json::Map::new();
1048 top.insert("_item_cap".into(), serde_json::json!(cap));
1049 for (k, v) in out {
1050 top.insert(k, v);
1051 }
1052 serde_json::Value::Object(top)
1053}
1054
1055pub fn health_anchors_axis(
1056 engine: &crate::engine::Engine,
1057 mem_filter: Option<&str>,
1058) -> serde_json::Value {
1059 let mut mems: Vec<String> = engine.mem_names().iter().map(|s| s.to_string()).collect();
1060 mems.retain(|m| mem_filter.is_none_or(|v| m == v));
1061 mems.sort();
1062 let mut out = serde_json::Map::new();
1063 for mem in mems {
1064 let Ok(report) = engine.verify_mem_anchors(&mem) else {
1065 continue;
1066 };
1067 let condition = report.sidecar_error.as_ref().map(|why| {
1068 serde_json::json!({
1069 "code": "ANCHORS_SIDECAR_UNREADABLE",
1070 "mem": mem,
1071 "reason": why,
1072 })
1073 });
1074 let mut row = serde_json::json!({
1077 "condition": condition,
1080 "drifted": report.drifted,
1081 "recheck": report.recheck,
1082 "unresolvable": report.unresolvable,
1087 "span_absent": report.span_absent,
1090 "unobserved": report.unobserved,
1091 "dangling": report.dangling,
1096 "entity_end_unreconciled": report.unreconciled,
1097 "aging": report
1102 .anchors
1103 .iter()
1104 .filter(|a| a.observed_at.is_some())
1105 .map(|a| {
1106 let days = a.unobserved_for_days.unwrap_or(0);
1107 serde_json::json!({
1108 "id": a.entity_id,
1109 "artifact": a.artifact,
1110 "state": a.state,
1111 "observed_at": a.observed_at,
1112 "unobserved_for_days": days,
1113 "note": format!("unobserved for {days} days"),
1114 })
1115 })
1116 .collect::<Vec<_>>(),
1117 });
1118 if let (Some(o), Ok(serde_json::Value::Object(f))) =
1119 (row.as_object_mut(), serde_json::to_value(&report.figure))
1120 {
1121 o.extend(f);
1122 }
1123 out.insert(mem, row);
1124 }
1125 serde_json::Value::Object(out)
1126}
1127
1128pub fn compute_health(
1141 store: &Store,
1142 default_schema: &TypeDefinition,
1143 mem_schemas: &HashMap<String, Arc<Schema>>,
1144 mem_filter: Option<&str>,
1145) -> HealthSummary {
1146 let mut missing_fields = Vec::new();
1147 let mut stale_entities = Vec::new();
1148
1149 let today_days = days_since_epoch();
1150
1151 let in_scope = |mem: &str| mem_filter.is_none_or(|v| mem == v);
1152
1153 for entity in store.all_entities() {
1154 if entity.stub || !in_scope(&entity.mem) {
1155 continue;
1156 }
1157
1158 let resolved = mem_schemas
1167 .get(entity.mem.as_str())
1168 .and_then(|s| s.types.get(entity.entity_type.as_str()).cloned())
1169 .or_else(|| type_by_name(&entity.entity_type));
1170 let schema: &TypeDefinition = resolved.as_deref().unwrap_or(default_schema);
1171 let mut issues = Vec::new();
1172
1173 for field in &schema.health_required_fields {
1175 if schema.section(field).is_some() {
1177 let content = entity.sections.get(field.as_str());
1182 if content.is_none_or(|c| c.trim().is_empty()) {
1183 if let Some(issue) = section_heading_mismatch_issue(entity, schema, field) {
1184 issues.push(issue);
1185 } else {
1186 issues.push(HealthIssue {
1187 field: field.clone(),
1188 code: super::HealthIssueCode::Missing,
1189 message: format!("required section '{field}' is empty"),
1190 });
1191 }
1192 }
1193 } else {
1194 let value = entity.metadata.get(field.as_str());
1200 let is_empty = match value {
1201 None => true,
1202 Some(v) => v.to_frontmatter_string().trim().is_empty(),
1203 };
1204 if is_empty {
1205 issues.push(HealthIssue {
1206 field: field.clone(),
1207 code: super::HealthIssueCode::Missing,
1208 message: format!("required field '{field}' is missing"),
1209 });
1210 }
1211 }
1212 }
1213
1214 for s in schema.sections.iter().filter(|s| !s.catch_all) {
1217 if schema.health_required_fields.contains(&s.key) {
1218 continue; }
1220 let content = entity.sections.get(s.key.as_str());
1221 if content.is_none_or(|c| c.trim().is_empty())
1222 && let Some(issue) = section_heading_mismatch_issue(entity, schema, &s.key)
1223 {
1224 issues.push(issue);
1225 }
1226 }
1227
1228 if let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) {
1244 let mut seen_unknown = std::collections::HashSet::new();
1245 for rel in &entity.relationships {
1246 if !mem_schema.relationship_known(&rel.rel_type) {
1247 if seen_unknown.insert(rel.rel_type.clone()) {
1248 let suggestion = mem_schema
1249 .suggest_relationship(&rel.rel_type)
1250 .map(|s| format!(" Did you mean '{s}'?"))
1251 .unwrap_or_default();
1252 let (schema_name, schema_version) = mem_schema.id();
1253 issues.push(HealthIssue {
1254 field: "relationships".to_string(),
1255 code: super::HealthIssueCode::UndeclaredRelationship,
1256 message: format!(
1257 "relationship '{}' is not declared in schema \
1258 '{schema_name}@{schema_version}'.{suggestion}",
1259 rel.rel_type
1260 ),
1261 });
1262 }
1263 continue;
1264 }
1265
1266 let target_type = store
1267 .get(&rel.target)
1268 .map(|t| t.entity_type.clone())
1269 .filter(|t| !t.is_empty());
1270 if let Err(crate::runtime_validator::ValidationError::InvalidRelationshipShape {
1271 rel_type,
1272 from_type,
1273 to_type,
1274 allowed_source_types,
1275 allowed_target_types,
1276 ..
1277 }) = crate::runtime_validator::validate_rel_shape(
1278 &rel.rel_type,
1279 entity.entity_type.as_str(),
1280 target_type.as_deref(),
1281 mem_schema.as_ref(),
1282 ) {
1283 let allowed_src = if allowed_source_types.is_empty() {
1284 "<any>".to_string()
1285 } else {
1286 allowed_source_types.join(", ")
1287 };
1288 let allowed_tgt = if allowed_target_types.is_empty() {
1289 "<any>".to_string()
1290 } else {
1291 allowed_target_types.join(", ")
1292 };
1293 issues.push(HealthIssue {
1294 field: "relationships".to_string(),
1295 code: super::HealthIssueCode::InvalidRelShape,
1296 message: format!(
1297 "INVALID_REL_SHAPE: edge '{rel_type}' from \
1298 '{from_type}' to '{to_type}' (target {target}) \
1299 violates declared shape — allowed_source_types: \
1300 [{allowed_src}], allowed_target_types: \
1301 [{allowed_tgt}]. Remove via \
1302 `memstead_relate from={from_id} to={target} \
1303 type={rel_type} remove=true`.",
1304 target = rel.target,
1305 from_id = entity.id,
1306 ),
1307 });
1308 }
1309 }
1310 }
1311
1312 let auto_ts_field = schema.metadata_fields.iter().find(|f| f.auto_timestamp);
1314
1315 if let Some(ts_field) = auto_ts_field
1316 && let Some(val) = entity.metadata.get(ts_field.key.as_str())
1317 {
1318 let date_str = val.to_frontmatter_string();
1319 if let Some(modified_days) = parse_iso_to_days(&date_str) {
1320 let days_since = today_days.saturating_sub(modified_days);
1321 if days_since > schema.staleness_threshold_days as u64 {
1322 stale_entities.push(StaleEntity {
1323 id: entity.id.clone(),
1324 title: entity.title.clone(),
1325 days_since_modified: days_since,
1326 anchor_state: None,
1327 });
1328 }
1329 }
1330 }
1331
1332 if !issues.is_empty() {
1333 let total = schema.health_required_fields.len();
1339 let score = if total > 0 {
1340 (total.saturating_sub(issues.len()) as f32) / (total as f32)
1341 } else {
1342 1.0
1343 };
1344
1345 missing_fields.push(HealthReport {
1346 id: entity.id.clone(),
1347 title: entity.title.clone(),
1348 score,
1349 issues,
1350 });
1351 }
1352 }
1353
1354 stale_entities.sort_by_key(|e| std::cmp::Reverse(e.days_since_modified));
1356
1357 let orphan_count = query::find_orphans_with_schemas(store, mem_schemas)
1360 .into_iter()
1361 .filter(|id| store.get(id).is_some_and(|e| in_scope(&e.mem)))
1362 .count();
1363 let leaf_entities_by_type = match mem_filter {
1364 None => query::leaf_population(store, mem_schemas),
1365 Some(v) => {
1366 let scoped: HashMap<String, Arc<Schema>> = mem_schemas
1367 .iter()
1368 .filter(|(mem, _)| mem.as_str() == v)
1369 .map(|(mem, s)| (mem.clone(), s.clone()))
1370 .collect();
1371 query::leaf_population(store, &scoped)
1372 }
1373 };
1374 let stub_count = query::find_stubs(store)
1375 .iter()
1376 .filter(|(id, _)| store.get(id).is_some_and(|e| in_scope(&e.mem)))
1377 .count();
1378
1379 stale_entities.sort_by(|a, b| a.id.0.cmp(&b.id.0));
1382 missing_fields.sort_by(|a, b| a.id.0.cmp(&b.id.0));
1383
1384 HealthSummary {
1385 stale_entities,
1386 anchor_fresh: Vec::new(),
1387 missing_fields,
1388 orphan_count,
1389 stub_count,
1390 warnings: Vec::new(),
1391 quarantined: Vec::new(),
1392 load_errors: Vec::new(),
1393 boot_diagnosis: None,
1394 leaf_entities_by_type,
1395 dangling_links: None,
1396 findings: None,
1397 tag_distribution: None,
1398 tag_distribution_folded: None,
1399 untagged_entities: None,
1400 }
1401}
1402
1403pub fn collect_tag_distribution(
1417 store: &Store,
1418 mem_filter: Option<&str>,
1419 limit: usize,
1420) -> (Vec<TagDistribution>, Vec<FoldedTag>, UntaggedStats) {
1421 let mut counts: HashMap<String, (usize, HashMap<String, usize>)> = HashMap::new();
1423 let mut untagged = UntaggedStats {
1424 total: 0,
1425 by_entity_type: HashMap::new(),
1426 };
1427
1428 for entity in store.all_entities() {
1429 if entity.stub {
1430 continue;
1431 }
1432 if let Some(v) = mem_filter
1433 && entity.mem != v
1434 {
1435 continue;
1436 }
1437
1438 let tags_raw = entity
1439 .metadata
1440 .get("tags")
1441 .and_then(|v| match v {
1442 MetadataValue::String(s) => Some(s.as_str()),
1443 _ => None,
1444 })
1445 .unwrap_or("");
1446
1447 let mut any_tag = false;
1448 for tag in tags_raw.split(',').map(str::trim).filter(|s| !s.is_empty()) {
1449 any_tag = true;
1450 let entry = counts
1451 .entry(tag.to_string())
1452 .or_insert_with(|| (0, HashMap::new()));
1453 entry.0 += 1;
1454 *entry.1.entry(entity.entity_type.clone()).or_insert(0) += 1;
1455 }
1456 if !any_tag {
1457 untagged.total += 1;
1458 *untagged
1459 .by_entity_type
1460 .entry(entity.entity_type.clone())
1461 .or_insert(0) += 1;
1462 }
1463 }
1464
1465 let mut entries: Vec<TagDistribution> = counts
1467 .iter()
1468 .map(|(tag, (count, by_type))| TagDistribution {
1469 tag: tag.clone(),
1470 count: *count,
1471 by_entity_type: by_type.clone(),
1472 })
1473 .collect();
1474 entries.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.tag.cmp(&b.tag)));
1475 entries.truncate(limit);
1476
1477 let mut by_canonical: HashMap<String, Vec<(String, usize)>> = HashMap::new();
1482 for (tag, (count, _)) in counts.iter() {
1483 by_canonical
1484 .entry(tag.to_lowercase())
1485 .or_default()
1486 .push((tag.clone(), *count));
1487 }
1488 let mut folded: Vec<FoldedTag> = by_canonical
1489 .into_iter()
1490 .filter(|(_, v)| v.len() > 1)
1491 .map(|(canonical, mut variants)| {
1492 variants.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
1493 let total = variants.iter().map(|(_, c)| *c).sum();
1494 FoldedTag {
1495 canonical,
1496 total,
1497 variants: variants
1498 .into_iter()
1499 .map(|(tag, count)| TagVariant { tag, count })
1500 .collect(),
1501 }
1502 })
1503 .collect();
1504 folded.sort_by(|a, b| {
1505 b.total
1506 .cmp(&a.total)
1507 .then_with(|| a.canonical.cmp(&b.canonical))
1508 });
1509
1510 (entries, folded, untagged)
1511}
1512
1513pub fn collect_dangling_links(store: &Store, mem_filter: Option<&str>) -> Vec<DanglingLink> {
1539 use crate::entity::parser::extract_inline_links_lenient;
1540 use std::collections::HashSet;
1541
1542 let mut out = Vec::new();
1543 for entity in store.all_entities() {
1544 if entity.stub {
1545 continue;
1546 }
1547 if let Some(v) = mem_filter
1548 && entity.mem != v
1549 {
1550 continue;
1551 }
1552 let explicit_targets: HashSet<_> = entity
1553 .relationships
1554 .iter()
1555 .map(|r| r.target.clone())
1556 .collect();
1557 for (section_key, section_body) in &entity.sections {
1558 for target_id in extract_inline_links_lenient(section_body, &entity.mem) {
1559 let target_missing = store.get(&target_id).map(|e| e.stub).unwrap_or(true);
1560 let alias_orphan = !target_missing && !explicit_targets.contains(&target_id);
1561 let kind = if target_missing {
1565 crate::ops::DanglingLinkKind::LinkTargetMissing
1566 } else {
1567 crate::ops::DanglingLinkKind::LinkNotRelated
1568 };
1569 if target_missing || alias_orphan {
1570 out.push(DanglingLink {
1571 kind,
1572 from: entity.id.clone(),
1573 target_id: target_id.clone(),
1574 target_path: target_id.path().to_string(),
1575 section: Some(section_key.clone()),
1576 });
1577 }
1578 }
1579 }
1580 for rel in &entity.relationships {
1597 if store.get(&rel.target).is_some() {
1598 continue;
1599 }
1600 let already_reported = out
1601 .iter()
1602 .any(|d| d.from == entity.id && d.target_id == rel.target);
1603 if already_reported {
1604 continue;
1605 }
1606 out.push(DanglingLink {
1607 kind: crate::ops::DanglingLinkKind::RelationTargetMissing,
1608 from: entity.id.clone(),
1609 target_id: rel.target.clone(),
1610 target_path: rel.target.path().to_string(),
1611 section: None,
1612 });
1613 }
1614 }
1615 out.sort_by(|a, b| {
1620 (&a.from.0, &a.target_id.0, &a.section).cmp(&(&b.from.0, &b.target_id.0, &b.section))
1621 });
1622 out
1623}
1624
1625pub fn collect_missing_required_outgoing(
1636 store: &Store,
1637 mem_filter: Option<&str>,
1638 mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
1639) -> Vec<MissingRequiredOutgoingReport> {
1640 let mut out = Vec::new();
1641 for entity in store.all_entities() {
1642 if entity.stub {
1643 continue;
1644 }
1645 if let Some(v) = mem_filter
1646 && entity.mem != v
1647 {
1648 continue;
1649 }
1650 let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
1651 continue;
1652 };
1653 let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
1654 continue;
1655 };
1656 if td.required_outgoing.is_empty() {
1657 continue;
1658 }
1659 let unsatisfied = unsatisfied_required_outgoing(entity, td);
1660 if unsatisfied.is_empty() {
1661 continue;
1662 }
1663 out.push(MissingRequiredOutgoingReport {
1664 id: entity.id.clone(),
1665 title: entity.title.clone(),
1666 entity_type: entity.entity_type.clone(),
1667 mem: entity.mem.clone(),
1668 missing: unsatisfied,
1669 });
1670 }
1671 out.sort_by(|a, b| a.mem.cmp(&b.mem).then_with(|| a.id.0.cmp(&b.id.0)));
1672 out
1673}
1674
1675pub fn unsatisfied_required_outgoing(
1683 entity: &crate::entity::Entity,
1684 td: &TypeDefinition,
1685) -> Vec<super::MissingRequiredOutgoingBlock> {
1686 td.required_outgoing
1687 .iter()
1688 .filter(|block| {
1689 if let (Some(when_field), Some(when_value)) = (&block.when_field, &block.when_value) {
1694 let armed = entity
1695 .metadata
1696 .get(when_field.as_str())
1697 .is_some_and(|v| v.to_frontmatter_string() == *when_value);
1698 if !armed {
1699 return false;
1700 }
1701 }
1702 let count = entity
1703 .relationships
1704 .iter()
1705 .filter(|rel| block.relationships.iter().any(|name| name == &rel.rel_type))
1706 .count();
1707 !block.admits(count)
1708 })
1709 .map(|block| super::MissingRequiredOutgoingBlock {
1710 relationships: block.relationships.clone(),
1711 cardinality: block.cardinality.to_string(),
1712 severity: block.severity,
1713 when_field: block.when_field.clone(),
1714 when_value: block.when_value.clone(),
1715 })
1716 .collect()
1717}
1718
1719#[derive(Debug, Clone, serde::Serialize)]
1727#[serde(tag = "kind", rename_all = "snake_case")]
1728pub enum UnsatisfiedConstraint {
1729 RequiresWhen {
1730 field: String,
1731 when_field: String,
1732 when_value: String,
1733 severity: memstead_schema::ConstraintSeverity,
1734 },
1735 Unique {
1736 fields: Vec<String>,
1737 values: Vec<String>,
1739 colliding: String,
1742 severity: memstead_schema::ConstraintSeverity,
1743 },
1744 EnumFromNeighbour {
1745 field: String,
1746 value: String,
1748 relationships: Vec<String>,
1749 section: String,
1750 severity: memstead_schema::ConstraintSeverity,
1751 },
1752 StatusPropagation {
1753 field: String,
1754 value: String,
1756 relationships: Vec<String>,
1758 tainted_by: String,
1761 path: Vec<String>,
1768 severity: memstead_schema::ConstraintSeverity,
1769 },
1770 TransitionRequiresChecks {
1773 field: String,
1774 to_value: String,
1775 relationships: Vec<String>,
1776 direction: memstead_schema::ReachDirection,
1777 unchecked: Vec<UncheckedRelated>,
1780 related: usize,
1782 min_related: usize,
1785 severity: memstead_schema::ConstraintSeverity,
1786 },
1787 TransitionRequiresSelfCheck {
1790 field: String,
1791 to_value: String,
1792 check_kind: String,
1793 state: String,
1797 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1804 changed: Vec<String>,
1805 severity: memstead_schema::ConstraintSeverity,
1806 },
1807 MustReach {
1812 relationships: Vec<String>,
1813 direction: memstead_schema::ReachDirection,
1814 terminal_types: Vec<String>,
1815 #[serde(skip_serializing_if = "Option::is_none")]
1816 max_depth: Option<u32>,
1817 severity: memstead_schema::ConstraintSeverity,
1818 },
1819}
1820
1821impl UnsatisfiedConstraint {
1822 pub fn severity(&self) -> memstead_schema::ConstraintSeverity {
1823 match self {
1824 Self::RequiresWhen { severity, .. }
1825 | Self::Unique { severity, .. }
1826 | Self::EnumFromNeighbour { severity, .. }
1827 | Self::StatusPropagation { severity, .. }
1828 | Self::MustReach { severity, .. }
1829 | Self::TransitionRequiresChecks { severity, .. }
1830 | Self::TransitionRequiresSelfCheck { severity, .. } => *severity,
1831 }
1832 }
1833
1834 pub fn describe(&self) -> String {
1836 match self {
1837 Self::RequiresWhen {
1838 field,
1839 when_field,
1840 when_value,
1841 ..
1842 } => format!(
1843 "requires_when: '{field}' is required when {when_field}={when_value} and is unset"
1844 ),
1845 Self::Unique {
1846 fields, colliding, ..
1847 } => format!(
1848 "unique: tuple ({}) collides with '{colliding}'",
1849 fields.join(", ")
1850 ),
1851 Self::EnumFromNeighbour {
1852 field,
1853 value,
1854 relationships,
1855 section,
1856 ..
1857 } => format!(
1858 "enum_from_neighbour: '{field}' value '{value}' has no backing entry in any \
1859 `{section}` section reached via {}",
1860 relationships.join(", ")
1861 ),
1862 Self::StatusPropagation {
1863 field,
1864 value,
1865 tainted_by,
1866 path,
1867 ..
1868 } => {
1869 format!(
1870 "status_propagation: tainted by '{tainted_by}' ({field}={value}) via {}",
1871 path.join(" → ")
1872 )
1873 }
1874 Self::MustReach {
1875 relationships,
1876 direction,
1877 terminal_types,
1878 max_depth,
1879 ..
1880 } => {
1881 let depth = match max_depth {
1882 Some(d) => format!(" within {d} hop(s)"),
1883 None => String::new(),
1884 };
1885 format!(
1886 "must_reach: no path via [{}] ({direction}) reaches a [{}] entity{depth}",
1887 relationships.join(", "),
1888 terminal_types.join(", ")
1889 )
1890 }
1891 Self::TransitionRequiresChecks {
1892 field,
1893 to_value,
1894 relationships,
1895 unchecked,
1896 related,
1897 min_related,
1898 ..
1899 } => {
1900 if related < min_related {
1901 return format!(
1902 "transition_requires_checks: {field}={to_value} requires at least \
1903 {min_related} related entit{} via [{}] — found {related}",
1904 if *min_related == 1 { "y" } else { "ies" },
1905 relationships.join(", ")
1906 );
1907 }
1908 let listed: Vec<String> = unchecked
1909 .iter()
1910 .map(|u| format!("'{}' ({})", u.id, u.state))
1911 .collect();
1912 format!(
1913 "transition_requires_checks: {field}={to_value} requires a fresh confirming \
1914 check record on every entity related via [{}] — unconfirmed: {}",
1915 relationships.join(", "),
1916 listed.join(", ")
1917 )
1918 }
1919 Self::TransitionRequiresSelfCheck {
1920 field,
1921 to_value,
1922 check_kind,
1923 state,
1924 changed,
1925 ..
1926 } => {
1927 let mut m = format!(
1928 "transition_requires_self_check: {field}={to_value} requires a fresh confirming \
1929 `{check_kind}` check record on this entity under an identity other than its \
1930 author — derived: {state}"
1931 );
1932 if !changed.is_empty() {
1933 m.push_str(&format!(
1934 "; the write also changes {}, and a self-check transition write may \
1935 change nothing but `{field}`: write those changes first, check the \
1936 result, then set `{field}`",
1937 changed.join(", ")
1938 ));
1939 }
1940 m
1941 }
1942 }
1943 }
1944}
1945
1946#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
1950pub struct UncheckedRelated {
1951 pub id: String,
1952 pub state: String,
1953}
1954
1955pub type CheckStateProvider<'a> =
1963 &'a dyn Fn(&crate::entity::Entity, &str) -> crate::engine::independence::CheckStanding;
1964
1965pub fn unsatisfied_constraints(
1989 store: &Store,
1990 entity: &crate::entity::Entity,
1991 td: &TypeDefinition,
1992 exclude: Option<&crate::entity::EntityId>,
1993 checks: Option<CheckStateProvider<'_>>,
1994) -> Vec<UnsatisfiedConstraint> {
1995 use memstead_schema::ConstraintDef;
1996 td.constraints
1997 .iter()
1998 .filter_map(|c| match c {
1999 ConstraintDef::RequiresWhen {
2000 field,
2001 when_field,
2002 when_value,
2003 severity,
2004 } => {
2005 let triggered = entity
2006 .metadata
2007 .get(when_field.as_str())
2008 .is_some_and(|v| v.to_frontmatter_string() == *when_value);
2009 if !triggered {
2010 return None;
2011 }
2012 let satisfied = entity
2013 .metadata
2014 .get(field.as_str())
2015 .is_some_and(|v| !v.to_frontmatter_string().trim().is_empty())
2016 || entity
2017 .sections
2018 .get(field.as_str())
2019 .is_some_and(|body| !body.trim().is_empty());
2020 if satisfied {
2021 return None;
2022 }
2023 Some(UnsatisfiedConstraint::RequiresWhen {
2024 field: field.clone(),
2025 when_field: when_field.clone(),
2026 when_value: when_value.clone(),
2027 severity: *severity,
2028 })
2029 }
2030 ConstraintDef::Unique { fields, severity } => {
2031 let tuple = tuple_of(entity, fields)?;
2032 let mut colliding: Vec<&str> = store
2033 .all_entities()
2034 .filter(|other| {
2035 !other.stub
2036 && other.mem == entity.mem
2037 && other.entity_type == entity.entity_type
2038 && Some(&other.id) != exclude
2039 && other.id != entity.id
2040 && tuple_of(other, fields).as_ref() == Some(&tuple)
2041 })
2042 .map(|other| other.id.0.as_str())
2043 .collect();
2044 colliding.sort_unstable();
2045 let first = colliding.first()?;
2046 Some(UnsatisfiedConstraint::Unique {
2047 fields: fields.clone(),
2048 values: tuple,
2049 colliding: first.to_string(),
2050 severity: *severity,
2051 })
2052 }
2053 ConstraintDef::EnumFromNeighbour {
2054 field,
2055 relationships,
2056 section,
2057 severity,
2058 } => {
2059 let value = entity
2060 .metadata
2061 .get(field.as_str())
2062 .map(|v| v.to_frontmatter_string())
2063 .filter(|v| !v.trim().is_empty())?;
2064 let backed = entity
2065 .relationships
2066 .iter()
2067 .filter(|rel| relationships.contains(&rel.rel_type))
2068 .filter_map(|rel| store.get(&rel.target))
2069 .filter_map(|neighbour| neighbour.sections.get(section.as_str()))
2070 .any(|body| bullet_entries(body).contains(&value));
2071 if backed {
2072 return None;
2073 }
2074 Some(UnsatisfiedConstraint::EnumFromNeighbour {
2075 field: field.clone(),
2076 value,
2077 relationships: relationships.clone(),
2078 section: section.clone(),
2079 severity: *severity,
2080 })
2081 }
2082 ConstraintDef::StatusPropagation { .. } => None,
2083 ConstraintDef::TransitionRequiresChecks {
2084 field,
2085 to_value,
2086 relationships,
2087 direction,
2088 min_related,
2089 severity,
2090 } => {
2091 let triggered = entity
2092 .metadata
2093 .get(field.as_str())
2094 .is_some_and(|v| v.to_frontmatter_string() == *to_value);
2095 if !triggered {
2096 return None;
2097 }
2098 let (related, unchecked) = transition_gate_standing(
2099 store,
2100 entity,
2101 relationships,
2102 *direction,
2103 exclude,
2104 checks,
2105 );
2106 if unchecked.is_empty() && related >= *min_related {
2107 return None;
2108 }
2109 Some(UnsatisfiedConstraint::TransitionRequiresChecks {
2110 field: field.clone(),
2111 to_value: to_value.clone(),
2112 relationships: relationships.clone(),
2113 direction: *direction,
2114 unchecked,
2115 related,
2116 min_related: *min_related,
2117 severity: *severity,
2118 })
2119 }
2120 ConstraintDef::TransitionRequiresSelfCheck {
2121 field,
2122 to_value,
2123 check_kind,
2124 severity,
2125 } => {
2126 let triggered = entity
2127 .metadata
2128 .get(field.as_str())
2129 .is_some_and(|v| v.to_frontmatter_string() == *to_value);
2130 if !triggered {
2131 return None;
2132 }
2133 let standing = match checks {
2138 Some(provider) => provider(entity, check_kind),
2139 None => crate::engine::independence::CheckStanding {
2140 state: crate::check::CheckState::NeverChecked,
2141 independence: None,
2142 role: crate::vcs::Role::Unspecified,
2143 },
2144 };
2145 if standing.confirms() {
2146 return None;
2147 }
2148 Some(UnsatisfiedConstraint::TransitionRequiresSelfCheck {
2149 field: field.clone(),
2150 to_value: to_value.clone(),
2151 check_kind: check_kind.clone(),
2152 state: standing.label().to_string(),
2153 changed: Vec::new(),
2154 severity: *severity,
2155 })
2156 }
2157 })
2158 .collect()
2159}
2160
2161pub fn transition_gate_standing(
2172 store: &Store,
2173 entity: &crate::entity::Entity,
2174 relationships: &[String],
2175 direction: memstead_schema::ReachDirection,
2176 exclude: Option<&crate::entity::EntityId>,
2177 checks: Option<CheckStateProvider<'_>>,
2178) -> (usize, Vec<UncheckedRelated>) {
2179 let related: Vec<&crate::entity::Entity> = match direction {
2180 memstead_schema::ReachDirection::Out => entity
2181 .relationships
2182 .iter()
2183 .filter(|rel| relationships.contains(&rel.rel_type))
2184 .filter_map(|rel| store.get(&rel.target))
2185 .collect(),
2186 memstead_schema::ReachDirection::In => store
2187 .all_entities()
2188 .filter(|other| {
2189 other.id != entity.id
2190 && Some(&other.id) != exclude
2191 && other
2192 .relationships
2193 .iter()
2194 .any(|rel| rel.target == entity.id && relationships.contains(&rel.rel_type))
2195 })
2196 .collect(),
2197 };
2198 let total = related.len();
2199 let mut unchecked: Vec<UncheckedRelated> = related
2200 .into_iter()
2201 .filter_map(|rel_entity| {
2202 let standing = match checks {
2206 Some(provider) => {
2207 provider(rel_entity, crate::check::CheckKind::Verification.as_str())
2208 }
2209 None => crate::engine::independence::CheckStanding {
2210 state: crate::check::CheckState::NeverChecked,
2211 independence: None,
2212 role: crate::vcs::Role::Unspecified,
2213 },
2214 };
2215 if standing.confirms() {
2216 None
2217 } else {
2218 Some(UncheckedRelated {
2219 id: rel_entity.id.0.clone(),
2220 state: standing.label().to_string(),
2221 })
2222 }
2223 })
2224 .collect();
2225 unchecked.sort_by(|a, b| a.id.cmp(&b.id));
2226 (total, unchecked)
2227}
2228
2229fn tuple_of(entity: &crate::entity::Entity, fields: &[String]) -> Option<Vec<String>> {
2233 fields
2234 .iter()
2235 .map(|f| {
2236 entity
2237 .metadata
2238 .get(f.as_str())
2239 .map(|v| v.to_frontmatter_string())
2240 .filter(|v| !v.trim().is_empty())
2241 })
2242 .collect()
2243}
2244
2245fn bullet_entries(body: &str) -> Vec<String> {
2248 let masked = crate::markdown::mask_code_blocks_and_spans(body);
2253 body.lines()
2254 .zip(masked.lines())
2255 .filter_map(|(line, masked_line)| {
2256 let m = masked_line.trim_start();
2257 if m.starts_with("- ") || m.starts_with("* ") {
2258 let t = line.trim_start();
2259 t.strip_prefix("- ")
2260 .or_else(|| t.strip_prefix("* "))
2261 .map(|e| e.trim().to_string())
2262 } else {
2263 None
2264 }
2265 })
2266 .collect()
2267}
2268
2269#[derive(Debug, Clone, serde::Serialize)]
2274pub struct ConstraintFindingReport {
2275 pub id: crate::entity::EntityId,
2276 pub title: String,
2277 pub entity_type: String,
2278 pub mem: String,
2279 pub violations: Vec<UnsatisfiedConstraint>,
2280 #[serde(skip_serializing_if = "Vec::is_empty")]
2284 pub format_violations: Vec<crate::section_format::SectionFormatViolation>,
2285}
2286
2287pub fn collect_constraint_findings(
2297 store: &Store,
2298 mem_filter: Option<&str>,
2299 mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
2300 checks: Option<CheckStateProvider<'_>>,
2301) -> Vec<ConstraintFindingReport> {
2302 use memstead_schema::ConstraintDef;
2303 type Bucket = (
2304 Vec<UnsatisfiedConstraint>,
2305 Vec<crate::section_format::SectionFormatViolation>,
2306 );
2307 let mut by_entity: std::collections::BTreeMap<String, Bucket> = Default::default();
2308
2309 let needs_reverse = mem_schemas.values().any(|s| {
2313 s.types.values().any(|t| {
2314 t.must_reach
2315 .iter()
2316 .any(|ob| ob.direction == memstead_schema::ReachDirection::In)
2317 })
2318 });
2319 let reverse: ReverseIndex = if needs_reverse {
2320 build_reverse_index(store)
2321 } else {
2322 ReverseIndex::default()
2323 };
2324
2325 for entity in store.all_entities() {
2326 if entity.stub {
2327 continue;
2328 }
2329 if let Some(v) = mem_filter
2330 && entity.mem != v
2331 {
2332 continue;
2333 }
2334 let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
2335 continue;
2336 };
2337 let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
2338 continue;
2339 };
2340
2341 for def in &td.sections {
2346 if def.compiled_content.is_none() {
2347 continue;
2348 }
2349 let Some(body) = entity.sections.get(def.key.as_str()) else {
2350 continue;
2351 };
2352 let violations = crate::section_format::check_section_format(def, body);
2353 if !violations.is_empty() {
2354 by_entity
2355 .entry(entity.id.0.clone())
2356 .or_default()
2357 .1
2358 .extend(violations);
2359 }
2360 }
2361
2362 for ob in &td.must_reach {
2367 if !reaches_terminal(store, &reverse, &entity.id, ob) {
2368 by_entity.entry(entity.id.0.clone()).or_default().0.push(
2369 UnsatisfiedConstraint::MustReach {
2370 relationships: ob.relationships.clone(),
2371 direction: ob.direction,
2372 terminal_types: ob.terminal_types.clone(),
2373 max_depth: ob.max_depth,
2374 severity: ob.severity,
2375 },
2376 );
2377 }
2378 }
2379
2380 if td.constraints.is_empty() {
2381 continue;
2382 }
2383
2384 let violations = unsatisfied_constraints(store, entity, td, None, checks);
2386 if !violations.is_empty() {
2387 by_entity
2388 .entry(entity.id.0.clone())
2389 .or_default()
2390 .0
2391 .extend(violations);
2392 }
2393 }
2394
2395 let mut sources: Vec<&crate::entity::Entity> =
2408 store.all_entities().filter(|e| !e.stub).collect();
2409 sources.sort_by(|a, b| a.id.0.cmp(&b.id.0));
2410 for entity in sources {
2411 let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
2412 continue;
2413 };
2414 let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
2415 continue;
2416 };
2417 for c in &td.constraints {
2418 let ConstraintDef::StatusPropagation {
2419 field,
2420 value,
2421 relationships,
2422 direction,
2423 severity,
2424 } = c
2425 else {
2426 continue;
2427 };
2428 let terminal = entity
2429 .metadata
2430 .get(field.as_str())
2431 .is_some_and(|v| v.to_frontmatter_string() == *value);
2432 if !terminal {
2433 continue;
2434 }
2435 for (tainted, path) in reach_transitively(store, &entity.id, relationships, *direction)
2436 {
2437 if let Some(v) = mem_filter
2438 && tainted.mem() != v
2439 {
2440 continue;
2441 }
2442 by_entity.entry(tainted.0.clone()).or_default().0.push(
2443 UnsatisfiedConstraint::StatusPropagation {
2444 field: field.clone(),
2445 value: value.clone(),
2446 relationships: relationships.clone(),
2447 tainted_by: entity.id.to_string(),
2448 path: path.iter().map(ToString::to_string).collect(),
2449 severity: *severity,
2450 },
2451 );
2452 }
2453 }
2454 }
2455
2456 let mut out: Vec<ConstraintFindingReport> = by_entity
2457 .into_iter()
2458 .filter_map(|(id, (violations, format_violations))| {
2459 let id = crate::entity::EntityId(id);
2460 let entity = store.get(&id)?;
2461 Some(ConstraintFindingReport {
2462 id,
2463 title: entity.title.clone(),
2464 entity_type: entity.entity_type.clone(),
2465 mem: entity.mem.clone(),
2466 violations,
2467 format_violations,
2468 })
2469 })
2470 .collect();
2471 out.sort_by(|a, b| a.mem.cmp(&b.mem).then_with(|| a.id.0.cmp(&b.id.0)));
2472 out
2473}
2474
2475fn reach_transitively(
2485 store: &Store,
2486 start: &crate::entity::EntityId,
2487 rel_types: &[String],
2488 direction: memstead_schema::ReachDirection,
2489) -> Vec<(crate::entity::EntityId, Vec<crate::entity::EntityId>)> {
2490 use memstead_schema::ReachDirection;
2491 let mut parent: std::collections::HashMap<crate::entity::EntityId, crate::entity::EntityId> =
2492 Default::default();
2493 let mut seen: std::collections::HashSet<crate::entity::EntityId> =
2494 std::iter::once(start.clone()).collect();
2495 let mut frontier = std::collections::VecDeque::from([start.clone()]);
2496 let mut reached = Vec::new();
2497 while let Some(current) = frontier.pop_front() {
2498 let mut next: Vec<crate::entity::EntityId> = match direction {
2499 ReachDirection::In => store
2500 .all_entities()
2501 .filter(|e| {
2502 e.relationships
2503 .iter()
2504 .any(|r| rel_types.iter().any(|n| n == &r.rel_type) && r.target == current)
2505 })
2506 .map(|e| e.id.clone())
2507 .collect(),
2508 ReachDirection::Out => store
2509 .get(¤t)
2510 .map(|e| {
2511 e.relationships
2512 .iter()
2513 .filter(|r| rel_types.iter().any(|n| n == &r.rel_type))
2514 .map(|r| r.target.clone())
2515 .collect()
2516 })
2517 .unwrap_or_default(),
2518 };
2519 next.sort_by(|a, b| a.0.cmp(&b.0));
2520 for id in next {
2521 if seen.insert(id.clone()) {
2522 parent.insert(id.clone(), current.clone());
2523 if store.get(&id).is_some_and(|e| !e.stub) {
2524 let mut path = vec![id.clone()];
2525 let mut at = id.clone();
2526 while let Some(p) = parent.get(&at) {
2527 path.push(p.clone());
2528 at = p.clone();
2529 }
2530 path.reverse();
2531 reached.push((id.clone(), path));
2532 }
2533 frontier.push_back(id);
2534 }
2535 }
2536 }
2537 reached
2538}
2539
2540type ReverseIndex =
2545 std::collections::HashMap<crate::entity::EntityId, Vec<(String, crate::entity::EntityId)>>;
2546
2547fn build_reverse_index(store: &Store) -> ReverseIndex {
2548 let mut idx = ReverseIndex::default();
2549 for entity in store.all_entities() {
2550 for rel in &entity.relationships {
2551 idx.entry(rel.target.clone())
2552 .or_default()
2553 .push((rel.rel_type.clone(), entity.id.clone()));
2554 }
2555 }
2556 idx
2557}
2558
2559fn reaches_terminal(
2568 store: &Store,
2569 reverse: &ReverseIndex,
2570 start: &crate::entity::EntityId,
2571 ob: &memstead_schema::MustReach,
2572) -> bool {
2573 use memstead_schema::ReachDirection;
2574 let mut seen: std::collections::HashSet<crate::entity::EntityId> =
2575 std::iter::once(start.clone()).collect();
2576 let mut frontier = vec![start.clone()];
2577 let mut depth: u32 = 0;
2578 while !frontier.is_empty() {
2579 if let Some(max) = ob.max_depth
2580 && depth >= max
2581 {
2582 return false;
2583 }
2584 depth += 1;
2585 let mut next_frontier = Vec::new();
2586 for current in frontier {
2587 let next: Vec<crate::entity::EntityId> = match ob.direction {
2588 ReachDirection::Out => store
2589 .get(¤t)
2590 .map(|e| {
2591 e.relationships
2592 .iter()
2593 .filter(|r| ob.relationships.iter().any(|n| n == &r.rel_type))
2594 .map(|r| r.target.clone())
2595 .collect()
2596 })
2597 .unwrap_or_default(),
2598 ReachDirection::In => reverse
2599 .get(¤t)
2600 .map(|sources| {
2601 sources
2602 .iter()
2603 .filter(|(rel, _)| ob.relationships.iter().any(|n| n == rel))
2604 .map(|(_, src)| src.clone())
2605 .collect()
2606 })
2607 .unwrap_or_default(),
2608 };
2609 for id in next {
2610 if seen.insert(id.clone()) {
2611 if store.get(&id).is_some_and(|e| {
2612 !e.stub && ob.terminal_types.iter().any(|t| t == &e.entity_type)
2613 }) {
2614 return true;
2615 }
2616 next_frontier.push(id);
2617 }
2618 }
2619 }
2620 frontier = next_frontier;
2621 }
2622 false
2623}
2624
2625#[derive(Debug, Clone, serde::Serialize)]
2630pub struct SignalReport {
2631 pub id: crate::entity::EntityId,
2632 pub title: String,
2633 pub entity_type: String,
2634 pub mem: String,
2635 pub signals: Vec<super::signals::ComputedSignal>,
2637}
2638
2639impl SignalReport {
2640 pub fn has_warn(&self) -> bool {
2644 self.signals
2645 .iter()
2646 .any(|s| s.level == Some(memstead_schema::SignalLevel::Warn))
2647 }
2648}
2649
2650pub fn collect_signal_reports(
2654 store: &Store,
2655 mem_filter: Option<&str>,
2656 mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
2657) -> Vec<SignalReport> {
2658 let mut out = Vec::new();
2659 for entity in store.all_entities() {
2660 if entity.stub {
2661 continue;
2662 }
2663 if let Some(v) = mem_filter
2664 && entity.mem != v
2665 {
2666 continue;
2667 }
2668 let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
2669 continue;
2670 };
2671 let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
2672 continue;
2673 };
2674 if td.signals.is_empty() {
2675 continue;
2676 }
2677 let above: Vec<super::signals::ComputedSignal> =
2678 super::signals::compute_signals(store, td, &entity.id)
2679 .into_iter()
2680 .filter(|s| s.level.is_some())
2681 .collect();
2682 if above.is_empty() {
2683 continue;
2684 }
2685 out.push(SignalReport {
2686 id: entity.id.clone(),
2687 title: entity.title.clone(),
2688 entity_type: entity.entity_type.clone(),
2689 mem: entity.mem.clone(),
2690 signals: above,
2691 });
2692 }
2693 out.sort_by(|a, b| a.mem.cmp(&b.mem).then_with(|| a.id.0.cmp(&b.id.0)));
2694 out
2695}
2696
2697#[derive(Debug, Clone, serde::Serialize)]
2702pub struct SchemaFormatDefect {
2703 pub schema: String,
2704 pub type_name: String,
2705 pub section: String,
2706 pub problems: Vec<String>,
2707}
2708
2709pub fn collect_schema_format_defects(
2713 mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
2714) -> Vec<SchemaFormatDefect> {
2715 let mut seen: std::collections::BTreeSet<String> = Default::default();
2716 let mut out = Vec::new();
2717 let mut schemas: Vec<&Arc<memstead_schema::Schema>> = mem_schemas.values().collect();
2718 schemas.sort_by_key(|s| (s.manifest.name.clone(), s.version.clone()));
2719 for schema in schemas {
2720 let schema_ref = format!("{}@{}", schema.manifest.name, schema.version);
2721 if !seen.insert(schema_ref.clone()) {
2722 continue;
2723 }
2724 for td in schema.types.values() {
2725 for section in &td.sections {
2726 if !section.format_problems.is_empty() {
2727 out.push(SchemaFormatDefect {
2728 schema: schema_ref.clone(),
2729 type_name: td.name.clone(),
2730 section: section.key.clone(),
2731 problems: section.format_problems.clone(),
2732 });
2733 }
2734 }
2735 }
2736 }
2737 out.sort_by(|a, b| {
2738 (&a.schema, &a.type_name, &a.section).cmp(&(&b.schema, &b.type_name, &b.section))
2739 });
2740 out
2741}
2742
2743#[derive(Debug, Clone, serde::Serialize)]
2751pub struct MissingRequiredOutgoingReport {
2752 pub id: crate::entity::EntityId,
2753 pub title: String,
2754 pub entity_type: String,
2755 pub mem: String,
2756 pub missing: Vec<super::MissingRequiredOutgoingBlock>,
2757}
2758
2759pub fn config_projection(
2772 engine: &crate::Engine,
2773 writable_mems: &[String],
2774 mutations: serde_json::Value,
2775 plugin: serde_json::Value,
2776) -> serde_json::Map<String, serde_json::Value> {
2777 let backend_by_mem: std::collections::HashMap<&str, (&'static str, bool)> = engine
2782 .mounts()
2783 .iter()
2784 .map(|m| {
2785 (
2786 m.mem.as_str(),
2787 (m.storage.backend_id(), m.storage.is_durable()),
2788 )
2789 })
2790 .collect();
2791 let mems_detail: Vec<serde_json::Value> = writable_mems
2792 .iter()
2793 .map(|name| {
2794 let origin = engine
2795 .mem_router()
2796 .origin_for_mem(name)
2797 .map(|o| o.kind())
2798 .unwrap_or("explicit");
2799 let mut entry = serde_json::Map::new();
2800 entry.insert("name".into(), serde_json::json!(name));
2801 entry.insert("origin".into(), serde_json::json!(origin));
2802 if let Some((storage, durable)) = backend_by_mem.get(name.as_str()).copied() {
2803 entry.insert("storage".into(), serde_json::json!(storage));
2804 entry.insert("durable".into(), serde_json::json!(durable));
2805 }
2806 let mut vcs_obj = serde_json::Map::new();
2807 if let Ok(gitdir) = engine.gitdir_for(name) {
2808 vcs_obj.insert("gitdir".into(), serde_json::json!(gitdir));
2809 }
2810 if let Ok(worktree) = engine.worktree_for(name) {
2811 vcs_obj.insert("worktree".into(), serde_json::json!(worktree));
2812 }
2813 if let Some(sha) = engine.mem_head_sha(name).ok().flatten() {
2814 vcs_obj.insert("head".into(), serde_json::json!(sha));
2815 }
2816 if !vcs_obj.is_empty() {
2817 entry.insert("vcs".into(), serde_json::Value::Object(vcs_obj));
2818 }
2819 if let Some(cfg) = engine.mem_config_for(name) {
2820 if let Some(title) = &cfg.title {
2824 entry.insert("title".into(), serde_json::json!(title));
2825 }
2826 if let Some(subject) = &cfg.subject {
2827 entry.insert("subject".into(), serde_json::json!(subject));
2828 }
2829 let guidance = serde_json::Map::from_iter(
2830 cfg.write_guidance
2831 .iter()
2832 .map(|(k, v)| (k.clone(), v.clone())),
2833 );
2834 entry.insert("write_guidance".into(), serde_json::Value::Object(guidance));
2835 let extra = serde_json::Map::from_iter(
2836 cfg.extra.iter().map(|(k, v)| (k.clone(), v.clone())),
2837 );
2838 entry.insert("extra".into(), serde_json::Value::Object(extra));
2839 }
2840 serde_json::Value::Object(entry)
2841 })
2842 .collect();
2843
2844 let mut out = serde_json::Map::new();
2845 out.insert("mems".into(), serde_json::json!(mems_detail));
2846 out.insert("mutations".into(), mutations);
2847 out.insert("plugin".into(), plugin);
2848 out
2849}
2850
2851pub fn config_projection_from_settings(
2857 settings: &crate::workspace::WorkspaceSettings,
2858) -> (serde_json::Value, serde_json::Value) {
2859 let mutations = serde_json::json!({ "require_notes": settings.mutations.require_notes });
2860 let plugin_map: serde_json::Map<String, serde_json::Value> = settings
2861 .plugin
2862 .iter()
2863 .map(|(k, v)| {
2864 (
2865 k.clone(),
2866 serde_json::to_value(v).unwrap_or(serde_json::Value::Null),
2867 )
2868 })
2869 .collect();
2870 (mutations, serde_json::Value::Object(plugin_map))
2871}
2872
2873pub(crate) fn section_heading_mismatch_issue(
2888 entity: &crate::entity::Entity,
2889 schema: &TypeDefinition,
2890 key: &str,
2891) -> Option<HealthIssue> {
2892 let def = schema.section(key)?;
2893 let derived = memstead_schema::derive_section_key(&def.heading);
2894 if derived == key {
2895 return None;
2896 }
2897 if !entity
2898 .raw_section_headings
2899 .iter()
2900 .any(|h| h == &def.heading)
2901 {
2902 return None;
2903 }
2904 let landing = match schema.catch_all_section() {
2905 Some(c) => format!(
2906 "the content was absorbed into catch-all section '{}'",
2907 c.key
2908 ),
2909 None => "the content is unreachable under any declared key".to_string(),
2910 };
2911 Some(HealthIssue {
2912 field: key.to_string(),
2913 code: super::HealthIssueCode::SectionHeadingMismatch,
2914 message: format!(
2915 "SECTION_HEADING_MISMATCH: section '{key}' is not missing — its content sits \
2916 under heading '{found}', which derives to '{derived}', not '{key}'; {landing}. \
2917 The schema's declared heading cannot round-trip to its key (expected a heading \
2918 that derives to '{key}'); fix the schema's heading/key pair — new installs of \
2919 such a schema are refused",
2920 found = def.heading,
2921 ),
2922 })
2923}
2924
2925pub fn entity_health(entity: &crate::entity::Entity, schema: &TypeDefinition) -> HealthReport {
2927 let mut issues = Vec::new();
2928
2929 for field in &schema.health_required_fields {
2930 if schema.section(field).is_some() {
2931 let content = entity.sections.get(field.as_str());
2932 if content.is_none_or(|c| c.trim().is_empty()) {
2933 if let Some(issue) = section_heading_mismatch_issue(entity, schema, field) {
2934 issues.push(issue);
2935 } else {
2936 issues.push(HealthIssue {
2937 field: field.clone(),
2938 code: super::HealthIssueCode::Missing,
2939 message: format!("required section '{field}' is empty"),
2940 });
2941 }
2942 }
2943 } else {
2944 let value = entity.metadata.get(field.as_str());
2945 if value.is_none() {
2946 issues.push(HealthIssue {
2947 field: field.clone(),
2948 code: super::HealthIssueCode::Missing,
2949 message: format!("required field '{field}' is missing"),
2950 });
2951 }
2952 }
2953 }
2954
2955 for s in schema.sections.iter().filter(|s| !s.catch_all) {
2959 if schema.health_required_fields.contains(&s.key) {
2960 continue; }
2962 let content = entity.sections.get(s.key.as_str());
2963 if content.is_none_or(|c| c.trim().is_empty())
2964 && let Some(issue) = section_heading_mismatch_issue(entity, schema, &s.key)
2965 {
2966 issues.push(issue);
2967 }
2968 }
2969
2970 let total = schema.health_required_fields.len();
2971 let score = if total > 0 {
2972 (total.saturating_sub(issues.len()) as f32) / (total as f32)
2973 } else {
2974 1.0
2975 };
2976
2977 HealthReport {
2978 id: entity.id.clone(),
2979 title: entity.title.clone(),
2980 score,
2981 issues,
2982 }
2983}
2984
2985pub fn pinned_today() -> Option<String> {
2999 let raw = std::env::var("MEMSTEAD_TODAY").ok()?;
3000 crate::engine::due::pinned_days_since_epoch(&raw)?;
3001 Some(raw)
3002}
3003
3004pub fn days_since_epoch() -> u64 {
3009 if let Some(pinned) = std::env::var("MEMSTEAD_TODAY")
3010 .ok()
3011 .and_then(|s| crate::engine::due::pinned_days_since_epoch(&s))
3012 {
3013 return pinned;
3014 }
3015 #[cfg(target_arch = "wasm32")]
3016 {
3017 (js_sys::Date::now() / 1000.0) as u64 / 86400
3018 }
3019 #[cfg(not(target_arch = "wasm32"))]
3020 {
3021 std::time::SystemTime::now()
3022 .duration_since(std::time::UNIX_EPOCH)
3023 .unwrap_or_default()
3024 .as_secs()
3025 / 86400
3026 }
3027}
3028
3029pub fn parse_iso_to_days(date: &str) -> Option<u64> {
3032 let date_part = date.split('T').next()?;
3033 let parts: Vec<&str> = date_part.split('-').collect();
3034 if parts.len() != 3 {
3035 return None;
3036 }
3037 let year: u64 = parts[0].parse().ok()?;
3038 let month: u64 = parts[1].parse().ok()?;
3039 let day: u64 = parts[2].parse().ok()?;
3040 Some(ymd_to_days(year, month, day))
3041}
3042
3043fn ymd_to_days(year: u64, month: u64, day: u64) -> u64 {
3046 let y = if month <= 2 { year - 1 } else { year };
3048 let m = if month <= 2 { month + 9 } else { month - 3 };
3049 let era = y / 400;
3050 let yoe = y - era * 400;
3051 let doy = (153 * m + 2) / 5 + day - 1;
3052 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
3053 let days = era * 146097 + doe;
3054 days - 719468
3055}
3056
3057#[cfg(test)]
3058mod tests;