1use std::collections::HashMap;
18
19#[derive(Debug)]
23pub struct HealthArgs<'a> {
24 pub mem: Option<&'a str>,
25 pub include: &'a [String],
26 pub limit: Option<usize>,
27 pub target_schema: Option<&'a str>,
28 pub include_config: bool,
29 pub strict: bool,
34 pub today: Option<&'a str>,
38}
39
40#[derive(Debug, Clone)]
45pub struct HealthConfig {
46 pub mutations: serde_json::Value,
47 pub plugin: serde_json::Value,
48}
49
50#[allow(clippy::large_enum_variant)]
57#[derive(Debug, thiserror::Error)]
58pub enum ComposeHealthError {
59 #[error("unknown mem: \"{name}\"")]
63 UnknownMem {
64 name: String,
65 writable_mems: Vec<String>,
66 },
67 #[error("mem \"{0}\" is quarantined")]
72 MemQuarantined(String),
73 #[error("invalid target_schema {raw:?}: {reason}")]
77 InvalidTargetSchema { raw: String, reason: String },
78 #[error(transparent)]
81 Engine(#[from] crate::EngineError),
82}
83
84pub fn compose_health(
95 engine: &mut crate::Engine,
96 args: &HealthArgs,
97 drift_warnings: Vec<crate::WarningHint>,
98 loop_warnings: Vec<crate::WarningHint>,
99 config: &HealthConfig,
100) -> Result<serde_json::Value, ComposeHealthError> {
101 let health = engine.health();
102 let stats = engine.status();
103 let effective_include: Vec<String> = if args.strict {
106 let mut v: Vec<String> = args.include.to_vec();
107 for key in crate::ops::strict::STRICT_INCLUDES {
108 if !v.iter().any(|s| s == key) {
109 v.push((*key).to_string());
110 }
111 }
112 v
113 } else {
114 args.include.to_vec()
115 };
116 let include: &[String] = &effective_include;
117 const HEALTH_LIMIT_MAX: usize = 100;
118 let requested_limit = args.limit.unwrap_or(10);
119 let limit = requested_limit.min(HEALTH_LIMIT_MAX);
120
121 let mut warnings: Vec<crate::WarningHint> = drift_warnings;
122 warnings.extend(health.warnings.clone());
123 warnings.extend(loop_warnings);
124 if requested_limit > HEALTH_LIMIT_MAX {
125 warnings.push(crate::WarningHint::LimitClamped {
126 requested: requested_limit,
127 actual: HEALTH_LIMIT_MAX,
128 });
129 }
130
131 for key in include {
132 if !crate::ops::health::HEALTH_INCLUDE_KEYS.contains(&key.as_str()) {
133 warnings.push(crate::WarningHint::UnknownIncludeKey {
134 key: key.clone(),
135 allowed: crate::ops::health::HEALTH_INCLUDE_KEYS
136 .iter()
137 .map(|s| s.to_string())
138 .collect(),
139 });
140 }
141 }
142
143 let mem_filter: Option<String> = match args.mem {
145 Some(v) if engine.mem_router().is_writable(v) => Some(v.to_string()),
146 Some(v) if engine.quarantine_reason(v).is_some() => {
147 return Err(ComposeHealthError::MemQuarantined(v.to_string()));
148 }
149 Some(v) => {
150 let mut names: Vec<String> = engine
151 .mem_router()
152 .writable_mems()
153 .iter()
154 .cloned()
155 .collect();
156 names.sort();
157 return Err(ComposeHealthError::UnknownMem {
158 name: v.to_string(),
159 writable_mems: names,
160 });
161 }
162 None => None,
163 };
164 let vf = mem_filter.as_deref();
165
166 if let Some(v) = vf {
173 warnings.retain(|w| w.concerns_mem(v));
174 }
175
176 let in_mem = |e: &crate::Entity| -> bool {
177 match vf {
178 Some(v) => e.mem == v,
179 None => true,
180 }
181 };
182 let real_count = engine
183 .store()
184 .all_entities()
185 .filter(|e| !e.stub && in_mem(e))
186 .count();
187 let stub_count = engine
188 .store()
189 .all_entities()
190 .filter(|e| e.stub && in_mem(e))
191 .count();
192 let total_count = real_count + stub_count;
193
194 let orphan_ids: Vec<crate::EntityId> = engine
195 .orphans()
196 .into_iter()
197 .filter(|id| match vf {
198 Some(v) => engine.store().get(id).map(|e| e.mem == v).unwrap_or(false),
199 None => true,
200 })
201 .collect();
202 let stub_pairs: Vec<(crate::EntityId, Vec<crate::EntityId>)> = engine
203 .stubs()
204 .into_iter()
205 .filter(|(id, _)| match vf {
206 Some(v) => engine.store().get(id).map(|e| e.mem == v).unwrap_or(false),
207 None => true,
208 })
209 .collect();
210
211 let community_count = match vf {
217 Some(v) => {
218 crate::graph::community::clusters_in_mem(engine.store(), engine.communities(), v).len()
219 }
220 None => engine.communities().count,
221 };
222
223 let (edge_count, edge_types) = {
226 if let Some(v) = vf {
227 let mut counts: HashMap<String, usize> = HashMap::new();
228 let mut total: usize = 0;
229 for id in engine.store().all_ids() {
230 let source_mem = engine.store().get(id).map(|e| e.mem.clone());
231 if let Some(source) = source_mem.as_deref()
232 && source != v
233 {
234 continue;
235 }
236 for edge in engine.store().outgoing(id) {
237 *counts.entry(edge.rel_type.clone()).or_insert(0) += 1;
238 total += 1;
239 }
240 }
241 let mut pairs: Vec<_> = counts.into_iter().collect();
243 pairs.sort_by(|a, b| a.0.cmp(&b.0));
244 let arr: Vec<serde_json::Value> = pairs
245 .into_iter()
246 .map(|(t, c)| serde_json::json!({"type": t, "count": c}))
247 .collect();
248 (total, arr)
249 } else {
250 let arr: Vec<serde_json::Value> = stats
252 .edge_types
253 .iter()
254 .map(|(t, c)| serde_json::json!({"type": t, "count": c}))
255 .collect();
256 (stats.edge_count, arr)
257 }
258 };
259
260 let type_distribution: Vec<serde_json::Value> = {
261 let mut counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
262 for e in engine
263 .store()
264 .all_entities()
265 .filter(|e| !e.stub && in_mem(e))
266 {
267 *counts.entry(&e.entity_type).or_default() += 1;
268 }
269 let mut pairs: Vec<_> = counts.into_iter().collect();
270 pairs.sort_by(|a, b| a.0.cmp(b.0));
271 pairs
272 .into_iter()
273 .map(|(s, c)| serde_json::json!({"type": s, "count": c}))
274 .collect()
275 };
276
277 let writable_mems: Vec<String> = {
278 let mut names: Vec<String> = engine
279 .mem_router()
280 .writable_mems()
281 .iter()
282 .cloned()
283 .collect();
284 names.sort();
285 names
286 };
287 let default_writable_mem: Option<String> = engine.default_writable_mem().map(|s| s.to_string());
292 let read_mems: Vec<String> = {
293 let writable_set: std::collections::HashSet<&String> =
294 engine.mem_router().writable_mems().iter().collect();
295 let mut names: Vec<String> = engine
296 .mem_router()
297 .visible_mems()
298 .iter()
299 .filter(|n| !writable_set.contains(*n))
300 .cloned()
301 .collect();
302 names.sort();
303 names
304 };
305
306 let mem_schemas: Vec<serde_json::Value> = {
319 let mut entries: Vec<serde_json::Value> = Vec::new();
320 let writable_set: std::collections::HashSet<&String> = writable_mems.iter().collect();
321 for name in writable_mems.iter().chain(read_mems.iter()) {
322 if let Some(v) = vf
323 && name != v
324 {
325 continue;
326 }
327 if let Some(m) = engine.mount(name) {
328 let schema_ref = m
333 .schema
334 .as_ref()
335 .map(|s| s.as_display())
336 .unwrap_or_default();
337 let mut entry = serde_json::json!({
338 "mem": name,
339 "schema": schema_ref,
340 "writable": writable_set.contains(name),
341 });
342 if let Some(target) = &m.migration_target {
346 entry["migration_target"] = serde_json::json!(target.as_display());
347 }
348 entries.push(entry);
349 }
350 }
351 entries
352 };
353
354 let orphans_by_schema = engine.orphans_by_schema(&orphan_ids);
365 let scope_mems: Vec<String> = match vf {
366 Some(v) => vec![v.to_string()],
367 None => writable_mems
368 .iter()
369 .chain(read_mems.iter())
370 .cloned()
371 .collect(),
372 };
373 let communities_by_schema = engine.communities_by_schema(&scope_mems);
374
375 let mut result = serde_json::json!({
376 "mem": mem_filter,
377 "verdict_coverage": crate::ops::coverage::HEALTH_COVERAGE.wire_line_for_includes(
394 &include.iter().map(String::as_str).collect::<Vec<_>>(),
395 ),
396 "summary": {
397 "total_entities": real_count,
398 "total_orphans": orphan_ids.len(),
399 "total_stubs": stub_pairs.len(),
400 "total_stale": health.stale_entities.iter().filter(|e| match vf {
401 Some(v) => engine.store().get(&e.id).map(|ent| ent.mem == v).unwrap_or(false),
402 None => true,
403 }).count(),
404 "total_missing_fields": health.missing_fields.iter().filter(|h| match vf {
405 Some(v) => engine.store().get(&h.id).map(|ent| ent.mem == v).unwrap_or(false),
406 None => true,
407 }).count(),
408 "total_communities": community_count,
409 "orphans_by_schema": orphans_by_schema,
410 "communities_by_schema": communities_by_schema,
411 },
412 "total_nodes": total_count,
413 "real_nodes": real_count,
414 "stub_nodes": stub_count,
415 "total_edges": edge_count,
416 "edge_types": edge_types,
417 "type_distribution": type_distribution,
418 "writable_mems": writable_mems,
419 "default_writable_mem": default_writable_mem,
420 "read_mems": read_mems,
421 "mem_schemas": mem_schemas,
422 });
423 let obj = result.as_object_mut().unwrap();
424 if let Some(v) = vf
428 && let Some(schema) = crate::overview::mem_schema_ref(engine, v)
429 {
430 obj.insert("_mem_schema".into(), serde_json::Value::String(schema));
431 }
432 if !warnings.is_empty() {
433 obj.insert("warnings".into(), serde_json::json!(warnings));
434 }
435 if !health.quarantined.is_empty() {
438 obj.insert(
439 "quarantined".into(),
440 serde_json::to_value(&health.quarantined).unwrap_or_default(),
441 );
442 }
443 if !health.load_errors.is_empty() {
448 obj.insert(
449 "load_errors".into(),
450 serde_json::to_value(&health.load_errors).unwrap_or_default(),
451 );
452 }
453 if let Some(diag) = &health.boot_diagnosis {
454 obj.insert("boot_diagnosis".into(), diag.clone());
455 }
456 if !health.leaf_entities_by_type.is_empty() {
459 obj.insert(
460 "leaf_entities_by_type".into(),
461 serde_json::to_value(&health.leaf_entities_by_type).unwrap_or_default(),
462 );
463 }
464
465 if include.iter().any(|s| s == "orphans") {
466 let orphans_list: Vec<serde_json::Value> = orphan_ids
467 .into_iter()
468 .map(|id| {
469 let title = engine
470 .get_entity(&id)
471 .map(|e| e.title.clone())
472 .unwrap_or_default();
473 serde_json::json!({"id": id.to_string(), "title": title})
474 })
475 .collect();
476 obj.insert("orphans".into(), serde_json::json!(orphans_list));
477 }
478 if include.iter().any(|s| s == "stubs") {
479 let stubs_list: Vec<serde_json::Value> = stub_pairs
480 .into_iter()
481 .map(|(id, refs)| {
482 serde_json::json!({
483 "id": id.to_string(),
484 "referenced_by": refs.iter().map(|r| r.to_string()).collect::<Vec<_>>(),
485 })
486 })
487 .collect();
488 obj.insert("stubs".into(), serde_json::json!(stubs_list));
489 }
490 if include.iter().any(|s| s == "most_connected") {
491 use crate::graph::query::{Connectivity, cmp_by_dependency, connectivity_for};
492 let to_json = |c: Connectivity| {
497 let title = engine
498 .get_entity(&c.id)
499 .map(|e| e.title.clone())
500 .unwrap_or_default();
501 serde_json::json!({
502 "id": c.id.to_string(),
503 "title": title,
504 "total": c.total,
505 "incoming": c.incoming,
506 "outgoing": c.outgoing,
507 "typed_total": c.typed_total,
508 "typed_incoming": c.typed_incoming,
509 "typed_outgoing": c.typed_outgoing,
510 })
511 };
512 let connected: Vec<serde_json::Value> = if let Some(v) = vf {
513 let mut entries: Vec<Connectivity> = engine
519 .store()
520 .all_entities()
521 .filter(|e| !e.stub && e.mem == v)
522 .map(|e| connectivity_for(engine.store(), &e.id, |in_edge| in_edge.from.mem() == v))
523 .collect();
524 entries.sort_by(cmp_by_dependency);
525 entries.truncate(limit);
526 entries.into_iter().map(to_json).collect()
527 } else {
528 engine
529 .most_connected(limit)
530 .into_iter()
531 .map(to_json)
532 .collect()
533 };
534 obj.insert("most_connected".into(), serde_json::json!(connected));
535 }
536 if include.iter().any(|s| s == "missing_fields") {
537 let missing_fields: Vec<serde_json::Value> = health
538 .missing_fields
539 .iter()
540 .filter(|h| match vf {
541 Some(v) => engine
542 .store()
543 .get(&h.id)
544 .map(|e| e.mem == v)
545 .unwrap_or(false),
546 None => true,
547 })
548 .map(|h| {
549 let missing: Vec<&str> = h.issues.iter().map(|i| i.field.as_str()).collect();
555 let issues: Vec<serde_json::Value> = h
556 .issues
557 .iter()
558 .map(|i| {
559 serde_json::json!({
560 "field": i.field,
561 "code": i.code,
562 "message": i.message,
563 })
564 })
565 .collect();
566 serde_json::json!({
567 "id": h.id.to_string(),
568 "title": h.title,
569 "missing": missing,
570 "issues": issues,
571 })
572 })
573 .collect();
574 obj.insert("missing_fields".into(), serde_json::json!(missing_fields));
575 }
576 if include.iter().any(|s| s == "stale") {
577 let stale: Vec<serde_json::Value> = health
578 .stale_entities
579 .iter()
580 .filter(|e| match vf {
581 Some(v) => engine
582 .store()
583 .get(&e.id)
584 .map(|ent| ent.mem == v)
585 .unwrap_or(false),
586 None => true,
587 })
588 .map(stale_row)
589 .collect();
590 obj.insert("stale".into(), serde_json::json!(stale));
591 let fresh: Vec<serde_json::Value> = health
594 .anchor_fresh
595 .iter()
596 .filter(|e| match vf {
597 Some(v) => engine
598 .store()
599 .get(&e.id)
600 .map(|ent| ent.mem == v)
601 .unwrap_or(false),
602 None => true,
603 })
604 .map(stale_row)
605 .collect();
606 if !fresh.is_empty() {
607 obj.insert("anchor_fresh".into(), serde_json::json!(fresh));
608 }
609 }
610 if include.iter().any(|s| s == "dangling_links") {
611 let dangling = crate::ops::health::collect_dangling_links(engine.store(), vf);
612 let arr: Vec<serde_json::Value> = dangling
613 .into_iter()
614 .map(|dl| serde_json::to_value(&dl).unwrap())
615 .collect();
616 obj.insert("dangling_links".into(), serde_json::json!(arr));
617 }
618 if include.iter().any(|s| s == "anchors") {
619 obj.insert(
620 "anchors".into(),
621 crate::ops::health::health_anchors_axis(engine, vf),
622 );
623 }
624 if include.iter().any(|s| s == "stale_derivations") {
625 obj.insert(
626 "stale_derivations".into(),
627 crate::ops::health::health_stale_derivations_axis(engine, args.mem),
628 );
629 }
630 if include.iter().any(|s| s == "checks") {
631 obj.insert(
632 "checks".into(),
633 crate::ops::health::health_checks_axis(engine, args.mem),
634 );
635 }
636 if include.iter().any(|s| s == "signals") {
637 obj.insert("signals".into(), engine.health_signals_axis(args.mem));
641 }
642 if include.iter().any(|s| s == "labelling") {
643 obj.insert("labelling".into(), engine.health_labelling_axis(args.mem));
647 }
648 if include.iter().any(|s| s == "open_questions") {
649 obj.insert(
650 "open_questions".into(),
651 crate::ops::health::health_open_questions_axis(engine, args.mem),
652 );
653 }
654 if include.iter().any(|s| s == "vital_signs") {
655 obj.insert(
658 "vital_signs".into(),
659 crate::ops::health::health_vital_signs_axis(engine, args.mem),
660 );
661 }
662 if include.iter().any(|s| s == "due") {
663 let today = match args.today {
669 Some(t) => t.to_string(),
670 None => match crate::ops::health::pinned_today() {
671 Some(pinned) => pinned,
672 None => {
673 let now = engine.now_iso();
674 now.get(..10).unwrap_or(&now).to_string()
675 }
676 },
677 };
678 let brief = engine
679 .due_brief(&today, &crate::engine::due::DueWindow::Days(90), vf)
680 .map_err(|e| ComposeHealthError::InvalidTargetSchema {
681 raw: today.clone(),
682 reason: e,
683 })?;
684 obj.insert(
685 "due".into(),
686 serde_json::to_value(&brief).unwrap_or_default(),
687 );
688 }
689 if include.iter().any(|s| s == "friction") {
690 let summary = match engine.workspace_root() {
696 Some(root) => crate::friction::FrictionLedger::for_workspace(root).summarize(),
697 None => serde_json::json!({
698 "total": 0,
699 "by_code": {},
700 "by_verb": {},
701 "recent_24h": { "total": 0, "by_code": {} },
702 "ledger_bytes": 0,
703 }),
704 };
705 obj.insert("friction".into(), summary);
706 }
707 if include.iter().any(|s| s == "missing_required_outgoing") {
708 let reports = engine.missing_required_outgoing(vf);
709 let arr: Vec<serde_json::Value> = reports
710 .into_iter()
711 .map(|r| serde_json::to_value(&r).unwrap())
712 .collect();
713 obj.insert("missing_required_outgoing".into(), serde_json::json!(arr));
714 }
715 if include.iter().any(|s| s == "constraints") {
716 let reports = engine.constraint_findings(vf);
717 let arr: Vec<serde_json::Value> = reports
718 .into_iter()
719 .map(|r| serde_json::to_value(&r).unwrap())
720 .collect();
721 obj.insert("constraints".into(), serde_json::json!(arr));
722 let defects = engine.schema_format_defects();
723 if !defects.is_empty() {
724 obj.insert(
725 "schema_format_defects".into(),
726 serde_json::to_value(&defects).unwrap(),
727 );
728 }
729 }
730 if include.iter().any(|s| s == "tags") {
731 let (distribution, folded, untagged) =
732 crate::ops::health::collect_tag_distribution(engine.store(), vf, limit);
733 obj.insert(
734 "tag_distribution".into(),
735 serde_json::to_value(&distribution).unwrap(),
736 );
737 obj.insert(
738 "tag_distribution_folded".into(),
739 serde_json::to_value(&folded).unwrap(),
740 );
741 obj.insert(
742 "untagged_entities".into(),
743 serde_json::to_value(&untagged).unwrap(),
744 );
745 }
746 let wants_conformance = include
752 .iter()
753 .any(|s| s == "conformance" || s == "integrity");
754 if wants_conformance {
755 let wants_consistency = include.iter().any(|s| s == "integrity");
756 let target: Option<memstead_schema::SchemaRef> = match args.target_schema {
757 None => None,
758 Some(raw) => match raw.parse::<memstead_schema::SchemaRef>() {
759 Ok(r) => Some(r),
760 Err(reason) => {
761 return Err(ComposeHealthError::InvalidTargetSchema {
762 raw: raw.to_string(),
763 reason,
764 });
765 }
766 },
767 };
768 let scan_mems: Vec<String> = match vf {
769 Some(v) => vec![v.to_string()],
770 None => {
771 let mut all = writable_mems.clone();
772 all.sort();
773 all
774 }
775 };
776 let mut findings = Vec::new();
777 let mut observations = Vec::new();
778 for v in &scan_mems {
779 findings.extend(engine.conformance_findings(v, target.as_ref())?);
780 observations.extend(engine.body_observations(v, target.as_ref())?);
784 if wants_consistency {
785 findings.extend(engine.consistency_findings(v)?);
786 }
787 }
788 obj.insert("findings".into(), serde_json::to_value(&findings).unwrap());
789 obj.insert(
790 "body_observations".into(),
791 serde_json::to_value(&observations).unwrap(),
792 );
793 }
794
795 if include.iter().any(|s| s == "ledger") {
802 let mut ledger = engine.ledger_reconciliation();
803 if let Some(v) = vf {
804 ledger.retain(|mem, _| mem == v);
805 }
806 obj.insert(
807 "ledger".into(),
808 serde_json::to_value(ledger).unwrap_or_default(),
809 );
810 }
811
812 if args.include_config || include.iter().any(|s| s == "config") {
821 let config_mems: Vec<String> = match vf {
824 Some(v) => writable_mems.iter().filter(|m| *m == v).cloned().collect(),
825 None => writable_mems.clone(),
826 };
827 let entries = crate::ops::health::config_projection(
828 engine,
829 &config_mems,
830 config.mutations.clone(),
831 config.plugin.clone(),
832 );
833 for (k, v) in entries {
834 obj.insert(k, v);
835 }
836 }
837
838 if args.strict {
841 let ledger = engine
842 .workspace_root()
843 .map(crate::check::CheckLedger::for_workspace);
844 let axis = crate::ops::strict::compose_strict_axis(obj, ledger.as_ref(), vf);
845 obj.insert(
846 "strict".into(),
847 serde_json::to_value(&axis).unwrap_or_default(),
848 );
849 }
850
851 Ok(result)
852}
853
854pub fn render_health_markdown(v: &serde_json::Value) -> String {
862 use std::fmt::Write as _;
863 let mut s = String::new();
864 let _ = writeln!(s, "# Graph health");
865 if let Some(mem) = v.get("mem").and_then(|x| x.as_str()) {
866 let _ = writeln!(s, "\nMem filter: `{mem}`");
867 }
868
869 if let Some(sum) = v.get("summary").and_then(|x| x.as_object()) {
870 let _ = writeln!(s, "\n## Summary");
871 for key in [
872 "total_entities",
873 "total_orphans",
874 "total_stubs",
875 "total_stale",
876 "total_missing_fields",
877 "total_communities",
878 ] {
879 if let Some(n) = sum.get(key).and_then(|x| x.as_u64()) {
880 let _ = writeln!(s, "- {}: {n}", key.replace('_', " "));
881 }
882 }
883 render_count_map(&mut s, sum.get("orphans_by_schema"), "Orphans by schema");
884 render_count_map(
885 &mut s,
886 sum.get("communities_by_schema"),
887 "Communities by schema",
888 );
889 }
890
891 for key in ["total_nodes", "real_nodes", "stub_nodes", "total_edges"] {
892 if let Some(n) = v.get(key).and_then(|x| x.as_u64()) {
893 let _ = writeln!(s, "- {}: {n}", key.replace('_', " "));
894 }
895 }
896
897 for (key, title) in [
899 ("orphans", "Orphans"),
900 ("stubs", "Stubs"),
901 ("most_connected", "Most connected"),
902 ("missing_fields", "Missing fields"),
903 ("stale", "Stale"),
904 ("dangling_links", "Dangling links"),
905 ("missing_required_outgoing", "Missing required outgoing"),
906 ("constraints", "Constraint violations"),
907 ("findings", "Findings"),
908 ] {
909 if let Some(arr) = v.get(key).and_then(|x| x.as_array()) {
910 let _ = writeln!(s, "\n## {title} ({})", arr.len());
911 for item in arr {
912 let _ = writeln!(s, "- {}", summarize_health_item(item));
913 }
914 }
915 }
916
917 if let Some(arr) = v.get("body_observations").and_then(|x| x.as_array()) {
922 let _ = writeln!(s, "\n## Body observations ({})", arr.len());
923 for item in arr {
924 let detail = &item["detail"];
925 let subject = detail
926 .get("heading")
927 .or_else(|| detail.get("key"))
928 .and_then(|x| x.as_str())
929 .unwrap_or("");
930 let _ = writeln!(
931 s,
932 "- {} [{}] `{subject}`: {} ({})",
933 item["id"].as_str().unwrap_or(""),
934 item["code"].as_str().unwrap_or(""),
935 item["fate"].as_str().unwrap_or(""),
936 detail
937 .get("note")
938 .and_then(|x| x.as_str())
939 .unwrap_or("no note"),
940 );
941 }
942 }
943
944 if let Some(due) = v.get("due").and_then(|x| x.as_object()) {
946 let rows = |key: &str| -> Vec<&serde_json::Value> {
947 due.get(key)
948 .and_then(|x| x.as_array())
949 .map(|a| a.iter().collect())
950 .unwrap_or_default()
951 };
952 let overdue = rows("overdue");
953 let soon = rows("due_soon");
954 let now = rows("due_now");
955 let _ = writeln!(
956 s,
957 "\n## Due ({} overdue, {} due soon{}; today {}, through {})",
958 overdue.len(),
959 soon.len(),
960 if now.is_empty() {
961 String::new()
962 } else {
963 format!(", {} due now", now.len())
964 },
965 due.get("today").and_then(|x| x.as_str()).unwrap_or("?"),
966 due.get("through").and_then(|x| x.as_str()).unwrap_or("?"),
967 );
968 for r in now {
969 let _ = writeln!(
970 s,
971 "- `{}` — {} — **due now**: no confirming `{}` check ({}) (status: {}, mem: {})",
972 r["id"].as_str().unwrap_or(""),
973 r["title"].as_str().unwrap_or(""),
974 r["check_kind"].as_str().unwrap_or(""),
975 r["standing"].as_str().unwrap_or(""),
976 r["status"].as_str().unwrap_or(""),
977 r["mem"].as_str().unwrap_or(""),
978 );
979 }
980 for r in overdue {
981 let _ = writeln!(
982 s,
983 "- `{}` — {} — **{}** OVERDUE ({} days past) (status: {}, mem: {})",
984 r["id"].as_str().unwrap_or(""),
985 r["title"].as_str().unwrap_or(""),
986 r["date"].as_str().unwrap_or(""),
987 r["days_past"].as_u64().unwrap_or(0),
988 r["status"].as_str().unwrap_or(""),
989 r["mem"].as_str().unwrap_or(""),
990 );
991 }
992 for r in soon {
993 let _ = writeln!(
994 s,
995 "- `{}` — {} — **{}** (in {} days) (status: {}, mem: {})",
996 r["id"].as_str().unwrap_or(""),
997 r["title"].as_str().unwrap_or(""),
998 r["date"].as_str().unwrap_or(""),
999 r["days_until"].as_u64().unwrap_or(0),
1000 r["status"].as_str().unwrap_or(""),
1001 r["mem"].as_str().unwrap_or(""),
1002 );
1003 }
1004 }
1005
1006 if let Some(obj) = v.get("anchors").and_then(|x| x.as_object()) {
1012 let _ = writeln!(s, "\n## Anchors ({} mems)", obj.len());
1013 for (mem, counts) in obj {
1014 if let Some(c) = counts.get("condition").filter(|c| !c.is_null()) {
1015 let _ = writeln!(
1016 s,
1017 "- `{mem}`: ANCHORS_SIDECAR_UNREADABLE — {} — {}",
1018 c["reason"].as_str().unwrap_or("reason not stated"),
1019 counts["population"]
1020 .as_str()
1021 .unwrap_or("population not stated"),
1022 );
1023 continue;
1024 }
1025 let figure = crate::anchor::AnchorResolutionFigure::from_json(counts)
1028 .map(|f| f.to_string())
1029 .unwrap_or_else(|| "resolution figure not stated with its population".to_string());
1030 let _ = writeln!(
1031 s,
1032 "- `{mem}`: resolves {figure}; drifted {}, recheck {}, unresolvable (artifact \
1033 gone) {}, unobserved (not measured) {}, dangling (entity gone) {}",
1034 counts["drifted"].as_u64().unwrap_or(0),
1035 counts["recheck"].as_u64().unwrap_or(0),
1036 counts["unresolvable"].as_u64().unwrap_or(0),
1037 counts["unobserved"].as_u64().unwrap_or(0),
1038 counts["dangling"].as_u64().unwrap_or(0),
1039 );
1040 }
1041 }
1042
1043 if let Some(obj) = v.get("vital_signs").and_then(|x| x.as_object()) {
1046 let mems: Vec<(&String, &serde_json::Value)> =
1047 obj.iter().filter(|(k, _)| *k != "_item_cap").collect();
1048 let _ = writeln!(s, "\n## Vital signs ({} mems)", mems.len());
1049 for (mem, sig) in mems {
1050 let count = |k: &str| sig[k]["count"].as_u64().unwrap_or(0);
1051 let share = match sig["type_share_by_community"]["status"].as_str() {
1052 Some("declared") => format!(
1053 "last-resort type `{}` over {} communit{}",
1054 sig["type_share_by_community"]["last_resort_type"]
1055 .as_str()
1056 .unwrap_or("?"),
1057 count("type_share_by_community"),
1058 if count("type_share_by_community") == 1 {
1059 "y"
1060 } else {
1061 "ies"
1062 }
1063 ),
1064 _ => "last-resort type not declared".to_string(),
1065 };
1066 let unclaimed = match sig["unclaimed_source_files"]["status"].as_str() {
1067 Some("enumerated") => format!(
1068 "{} unclaimed source file(s)",
1069 count("unclaimed_source_files")
1070 ),
1071 _ => "no bound source".to_string(),
1072 };
1073 let _ = writeln!(
1074 s,
1075 "- `{mem}`: {share}; {unclaimed}; {} contested unowned file(s); {} zero-outgoing \
1076 entit{} in {} communit{}; {} empty declared section(s)",
1077 count("contested_unowned_files"),
1078 sig["zero_outgoing_entities"]["entities"]
1079 .as_u64()
1080 .unwrap_or(0),
1081 if sig["zero_outgoing_entities"]["entities"]
1082 .as_u64()
1083 .unwrap_or(0)
1084 == 1
1085 {
1086 "y"
1087 } else {
1088 "ies"
1089 },
1090 count("zero_outgoing_entities"),
1091 if count("zero_outgoing_entities") == 1 {
1092 "y"
1093 } else {
1094 "ies"
1095 },
1096 count("empty_declared_sections"),
1097 );
1098 }
1099 }
1100
1101 if let Some(obj) = v.get("checks").and_then(|x| x.as_object()) {
1106 let _ = writeln!(s, "\n## Checks ({} mems)", obj.len());
1107 for (mem, c) in obj {
1108 let count = |key: &str| c.get(key).and_then(|x| x.as_u64()).unwrap_or(0);
1109 let conf = |key: &str| {
1110 c.get("conformance")
1111 .and_then(|g| g.get(key))
1112 .and_then(|x| x.as_u64())
1113 .unwrap_or(0)
1114 };
1115 let gate = |key: &str| {
1116 c.get("independence")
1117 .and_then(|g| g.get(key))
1118 .and_then(|e| e.get("count"))
1119 .and_then(|x| x.as_u64())
1120 .unwrap_or(0)
1121 };
1122 let _ = writeln!(
1123 s,
1124 "- `{mem}`: never_checked {}, checked_ok {}, check_failed {}, \
1125 check_stale {}; conformance: never_checked {}, \
1126 checked_ok {}, check_failed {}, check_stale {}; \
1127 independence: self_checked {}, \
1128 confirmed_independent {}, unconfirmable {}",
1129 count("never_checked"),
1130 count("checked_ok"),
1131 count("check_failed"),
1132 count("check_stale"),
1133 conf("never_checked"),
1134 conf("checked_ok"),
1135 conf("check_failed"),
1136 conf("check_stale"),
1137 gate("self_checked"),
1138 gate("confirmed_independent"),
1139 gate("unconfirmable"),
1140 );
1141 if let Some(foreign) = c.get("foreign_kinds").and_then(|f| f.as_object())
1145 && !foreign.is_empty()
1146 {
1147 let listed: Vec<String> = foreign
1148 .iter()
1149 .map(|(k, n)| format!("{k} {}", n.as_u64().unwrap_or(0)))
1150 .collect();
1151 let _ = writeln!(s, " - foreign kinds: {}", listed.join(", "));
1152 }
1153 if let Some(findings) = c.get("findings").and_then(|f| f.as_object()) {
1154 for (entity, f) in findings {
1155 let _ = writeln!(s, "{}", render_check_finding_line(entity, f));
1156 }
1157 }
1158 }
1159 }
1160
1161 if let Some(obj) = v.get("stale_derivations").and_then(|x| x.as_object()) {
1164 let total: usize = obj
1165 .values()
1166 .filter_map(|a| a.as_array().map(|a| a.len()))
1167 .sum();
1168 let _ = writeln!(s, "\n## Stale derivations ({total} findings)");
1169 for (mem, findings) in obj {
1170 for f in findings.as_array().into_iter().flatten() {
1171 let _ = writeln!(
1172 s,
1173 "- `{mem}`: {} -[{}]-> {} ({})",
1174 f.get("source").and_then(|x| x.as_str()).unwrap_or(""),
1175 f.get("rel_type").and_then(|x| x.as_str()).unwrap_or(""),
1176 f.get("target").and_then(|x| x.as_str()).unwrap_or(""),
1177 f.get("state").and_then(|x| x.as_str()).unwrap_or(""),
1178 );
1179 }
1180 }
1181 }
1182
1183 if let Some(arr) = v.get("quarantined").and_then(|x| x.as_array()) {
1188 let _ = writeln!(s, "\n## Quarantined mems ({})", arr.len());
1189 for q in arr {
1190 let _ = writeln!(
1191 s,
1192 "- `{}` [{}] {}",
1193 q.get("mem").and_then(|x| x.as_str()).unwrap_or(""),
1194 q.get("reason_code").and_then(|x| x.as_str()).unwrap_or(""),
1195 q.get("reason_message")
1196 .and_then(|x| x.as_str())
1197 .unwrap_or(""),
1198 );
1199 }
1200 }
1201
1202 if let Some(arr) = v.get("warnings").and_then(|x| x.as_array())
1203 && !arr.is_empty()
1204 {
1205 let _ = writeln!(s, "\n## Warnings ({})", arr.len());
1206 for w in arr {
1207 let code = w.get("code").and_then(|x| x.as_str()).unwrap_or("");
1208 let msg = w.get("message").and_then(|x| x.as_str()).unwrap_or("");
1209 let _ = writeln!(s, "- [{code}] {msg}");
1210 }
1211 }
1212
1213 s
1214}
1215
1216fn render_count_map(s: &mut String, val: Option<&serde_json::Value>, title: &str) {
1220 use std::fmt::Write as _;
1221 let Some(map) = val.and_then(|x| x.as_object()) else {
1222 return;
1223 };
1224 if map.is_empty() {
1225 return;
1226 }
1227 let _ = writeln!(s, "- {title}:");
1228 for (k, n) in map {
1229 let label = if k.is_empty() {
1230 "(unpinned)"
1231 } else {
1232 k.as_str()
1233 };
1234 let _ = writeln!(s, " - {label}: {}", n.as_u64().unwrap_or(0));
1235 }
1236}
1237
1238fn summarize_health_item(item: &serde_json::Value) -> String {
1250 if let Some(id) = item.get("id").and_then(|x| x.as_str()) {
1251 match item.get("title").and_then(|x| x.as_str()) {
1252 Some(t) if !t.is_empty() => format!("{id} — {t}"),
1253 _ => id.to_string(),
1254 }
1255 } else if let Some(from) = item.get("from").and_then(|x| x.as_str()) {
1256 let target = item.get("target_id").and_then(|x| x.as_str()).unwrap_or("");
1257 match item.get("kind").and_then(|x| x.as_str()) {
1258 Some(kind) => format!("[{kind}] {from} → {target}"),
1259 None => format!("{from} → {target}"),
1260 }
1261 } else {
1262 serde_json::to_string(item).unwrap_or_default()
1263 }
1264}
1265
1266fn stale_row(e: &crate::ops::StaleEntity) -> serde_json::Value {
1271 let mut row = serde_json::json!({
1272 "id": e.id.to_string(),
1273 "title": e.title,
1274 "days_since_modified": e.days_since_modified,
1275 });
1276 if let Some(state) = &e.anchor_state {
1277 let obj = row.as_object_mut().unwrap();
1278 obj.insert("clock".into(), serde_json::json!("anchors"));
1279 obj.insert("anchor_state".into(), serde_json::json!(state));
1280 }
1281 row
1282}
1283
1284pub fn render_check_finding_line(entity: &str, f: &serde_json::Value) -> String {
1298 let code = f["finding"]["code"].as_str().unwrap_or("?");
1299 let section = f["finding"]["section"]
1300 .as_str()
1301 .map(|x| format!(" [{x}]"))
1302 .unwrap_or_default();
1303 let message = f["finding"]["message"].as_str().unwrap_or("");
1304 let third_party =
1309 f["origin"].as_str() == Some(crate::render::OriginClass::ThirdParty.as_wire());
1310 let by = f["identity"]
1311 .as_str()
1312 .map(|i| format!(" by `{i}`"))
1313 .unwrap_or_default();
1314 let (mark, message) = if third_party {
1315 (
1316 crate::render::QUOTE_LABEL,
1317 crate::render::quote_inline(message),
1318 )
1319 } else {
1320 ("", message.to_string())
1321 };
1322 format!(
1323 " - finding on `{entity}` ({} {}){by}{mark}: {code}{section} — {message}",
1324 f["kind"].as_str().unwrap_or("verification"),
1325 f["verdict"].as_str().unwrap_or("?"),
1326 )
1327}
1328
1329impl ComposeHealthError {
1330 pub fn into_engine_error(self, engine: &crate::Engine) -> crate::EngineError {
1334 match self {
1335 ComposeHealthError::UnknownMem { name, .. } => engine.unknown_mem(&name),
1336 ComposeHealthError::MemQuarantined(name) => engine.unknown_mem_error(&name),
1337 ComposeHealthError::InvalidTargetSchema { raw, reason } => {
1338 crate::EngineError::InvalidTargetSchema { raw, reason }
1339 }
1340 ComposeHealthError::Engine(e) => e,
1341 }
1342 }
1343}
1344
1345#[cfg(test)]
1346mod tests {
1347 use super::render_health_markdown;
1348 use serde_json::json;
1349
1350 fn base_payload() -> serde_json::Value {
1351 json!({
1352 "summary": { "total_entities": 1 },
1353 "total_nodes": 1,
1354 })
1355 }
1356
1357 #[test]
1364 fn body_observations_render_their_code_and_fate_not_just_an_id() {
1365 let mut v = base_payload();
1366 v["body_observations"] = json!([{
1367 "id": "specs--alpha",
1368 "code": "ABSORBED_SECTION",
1369 "fate": "absorbed",
1370 "detail": { "heading": "Rogue", "note": "survives the next write" },
1371 }, {
1372 "id": "specs--beta",
1373 "code": "UNDECLARED_METADATA_KEY",
1374 "fate": "dropped",
1375 "detail": { "key": "reviewer", "note": "the next write drops it" },
1376 }]);
1377 let md = render_health_markdown(&v);
1378 assert!(md.contains("## Body observations (2)"), "{md}");
1379 assert!(
1380 md.contains(
1381 "- specs--alpha [ABSORBED_SECTION] `Rogue`: absorbed (survives the next write)"
1382 ),
1383 "{md}"
1384 );
1385 assert!(
1386 md.contains(
1387 "- specs--beta [UNDECLARED_METADATA_KEY] `reviewer`: dropped \
1388 (the next write drops it)"
1389 ),
1390 "{md}"
1391 );
1392 assert!(!render_health_markdown(&base_payload()).contains("Body observations"));
1394 }
1395
1396 #[test]
1403 fn render_health_markdown_names_the_dangling_condition() {
1404 let mut v = base_payload();
1405 v["dangling_links"] = json!([
1406 {
1407 "kind": "DANGLING_LINK_TARGET_MISSING",
1408 "from": "specs--a", "target_id": "specs--gone",
1409 "target_path": "gone", "section": "purpose",
1410 },
1411 {
1412 "kind": "DANGLING_RELATION_TARGET_MISSING",
1413 "from": "specs--b", "target_id": "specs--vanished",
1414 "target_path": "vanished", "section": null,
1415 },
1416 ]);
1417 let md = render_health_markdown(&v);
1418 assert!(
1419 md.contains("[DANGLING_LINK_TARGET_MISSING] specs--a → specs--gone"),
1420 "{md}"
1421 );
1422 assert!(
1423 md.contains("[DANGLING_RELATION_TARGET_MISSING] specs--b → specs--vanished"),
1424 "{md}"
1425 );
1426 assert!(
1428 !md.contains("- specs--a → specs--gone"),
1429 "the unprefixed form is what fused them: {md}"
1430 );
1431 }
1432
1433 #[test]
1440 fn render_health_markdown_covers_checks_derivations_and_quarantine() {
1441 let mut v = base_payload();
1443 v["checks"] = json!({
1444 "specs": {
1445 "never_checked": 2, "checked_ok": 1,
1446 "check_failed": 0, "check_stale": 0,
1447 "conformance": {
1448 "never_checked": 3, "checked_ok": 0,
1449 "check_failed": 0, "check_stale": 0,
1450 },
1451 "independence": {
1452 "self_checked": { "count": 0, "items": [] },
1453 "confirmed_independent": { "count": 0, "items": [] },
1454 "unconfirmable": { "count": 1, "items": ["specs--a"] },
1455 },
1456 }
1457 });
1458 v["stale_derivations"] = json!({
1459 "specs": [{
1460 "source": "specs--a", "rel_type": "DERIVES_FROM",
1461 "target": "specs--b", "state": "stale",
1462 "baseline": "aaa", "current": "bbb",
1463 }]
1464 });
1465 v["quarantined"] = json!([{
1466 "mem": "broken",
1467 "reason_code": "SCHEMA_NOT_FOUND",
1468 "reason_message": "no schema; repair via memstead mem set-schema",
1469 }]);
1470 let md = render_health_markdown(&v);
1471 assert!(md.contains("## Checks (1 mems)"), "{md}");
1472 assert!(
1473 md.contains(
1474 "- `specs`: never_checked 2, checked_ok 1, check_failed 0, \
1475 check_stale 0; conformance: never_checked 3, checked_ok 0, \
1476 check_failed 0, check_stale 0; independence: self_checked 0, \
1477 confirmed_independent 0, unconfirmable 1"
1478 ),
1479 "{md}"
1480 );
1481 assert!(md.contains("## Stale derivations (1 findings)"), "{md}");
1482 assert!(
1483 md.contains("- `specs`: specs--a -[DERIVES_FROM]-> specs--b (stale)"),
1484 "{md}"
1485 );
1486 assert!(md.contains("## Quarantined mems (1)"), "{md}");
1487 assert!(
1488 md.contains(
1489 "- `broken` [SCHEMA_NOT_FOUND] no schema; repair via memstead mem set-schema"
1490 ),
1491 "{md}"
1492 );
1493
1494 let mut empty = base_payload();
1496 empty["checks"] = json!({});
1497 empty["stale_derivations"] = json!({ "specs": [] });
1498 let md = render_health_markdown(&empty);
1499 assert!(md.contains("## Checks (0 mems)"), "{md}");
1500 assert!(md.contains("## Stale derivations (0 findings)"), "{md}");
1501
1502 let base_md = render_health_markdown(&base_payload());
1505 for heading in ["## Checks", "## Stale derivations", "## Quarantined mems"] {
1506 assert!(
1507 !base_md.contains(heading),
1508 "absent key must render nothing: {base_md}"
1509 );
1510 }
1511 let appended = render_health_markdown(&v);
1512 assert!(
1513 appended.starts_with(&base_md),
1514 "sections append; the base output stays byte-identical"
1515 );
1516 }
1517}