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(
89 engine: &mut crate::Engine,
90 args: &HealthArgs,
91 drift_warnings: Vec<crate::WarningHint>,
92 config: &HealthConfig,
93) -> Result<serde_json::Value, ComposeHealthError> {
94 let health = engine.health();
95 let stats = engine.status();
96 let effective_include: Vec<String> = if args.strict {
99 let mut v: Vec<String> = args.include.to_vec();
100 for key in crate::ops::strict::STRICT_INCLUDES {
101 if !v.iter().any(|s| s == key) {
102 v.push((*key).to_string());
103 }
104 }
105 v
106 } else {
107 args.include.to_vec()
108 };
109 let include: &[String] = &effective_include;
110 const HEALTH_LIMIT_MAX: usize = 100;
111 let requested_limit = args.limit.unwrap_or(10);
112 let limit = requested_limit.min(HEALTH_LIMIT_MAX);
113
114 let mut warnings: Vec<crate::WarningHint> = drift_warnings;
115 warnings.extend(health.warnings.clone());
116 if requested_limit > HEALTH_LIMIT_MAX {
117 warnings.push(crate::WarningHint::LimitClamped {
118 requested: requested_limit,
119 actual: HEALTH_LIMIT_MAX,
120 });
121 }
122
123 for key in include {
124 if !crate::ops::health::HEALTH_INCLUDE_KEYS.contains(&key.as_str()) {
125 warnings.push(crate::WarningHint::UnknownIncludeKey {
126 key: key.clone(),
127 allowed: crate::ops::health::HEALTH_INCLUDE_KEYS
128 .iter()
129 .map(|s| s.to_string())
130 .collect(),
131 });
132 }
133 }
134
135 let mem_filter: Option<String> = match args.mem {
137 Some(v) if engine.mem_router().is_writable(v) => Some(v.to_string()),
138 Some(v) if engine.quarantine_reason(v).is_some() => {
139 return Err(ComposeHealthError::MemQuarantined(v.to_string()));
140 }
141 Some(v) => {
142 let mut names: Vec<String> = engine
143 .mem_router()
144 .writable_mems()
145 .iter()
146 .cloned()
147 .collect();
148 names.sort();
149 return Err(ComposeHealthError::UnknownMem {
150 name: v.to_string(),
151 writable_mems: names,
152 });
153 }
154 None => None,
155 };
156 let vf = mem_filter.as_deref();
157
158 if let Some(v) = vf {
165 warnings.retain(|w| w.concerns_mem(v));
166 }
167
168 let in_mem = |e: &crate::Entity| -> bool {
169 match vf {
170 Some(v) => e.mem == v,
171 None => true,
172 }
173 };
174 let real_count = engine
175 .store()
176 .all_entities()
177 .filter(|e| !e.stub && in_mem(e))
178 .count();
179 let stub_count = engine
180 .store()
181 .all_entities()
182 .filter(|e| e.stub && in_mem(e))
183 .count();
184 let total_count = real_count + stub_count;
185
186 let orphan_ids: Vec<crate::EntityId> = engine
187 .orphans()
188 .into_iter()
189 .filter(|id| match vf {
190 Some(v) => engine.store().get(id).map(|e| e.mem == v).unwrap_or(false),
191 None => true,
192 })
193 .collect();
194 let stub_pairs: Vec<(crate::EntityId, Vec<crate::EntityId>)> = engine
195 .stubs()
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
203 let community_count = match vf {
209 Some(v) => {
210 crate::graph::community::clusters_in_mem(engine.store(), engine.communities(), v).len()
211 }
212 None => engine.communities().count,
213 };
214
215 let (edge_count, edge_types) = {
218 if let Some(v) = vf {
219 let mut counts: HashMap<String, usize> = HashMap::new();
220 let mut total: usize = 0;
221 for id in engine.store().all_ids() {
222 let source_mem = engine.store().get(id).map(|e| e.mem.clone());
223 if let Some(source) = source_mem.as_deref()
224 && source != v
225 {
226 continue;
227 }
228 for edge in engine.store().outgoing(id) {
229 *counts.entry(edge.rel_type.clone()).or_insert(0) += 1;
230 total += 1;
231 }
232 }
233 let mut pairs: Vec<_> = counts.into_iter().collect();
235 pairs.sort_by(|a, b| a.0.cmp(&b.0));
236 let arr: Vec<serde_json::Value> = pairs
237 .into_iter()
238 .map(|(t, c)| serde_json::json!({"type": t, "count": c}))
239 .collect();
240 (total, arr)
241 } else {
242 let arr: Vec<serde_json::Value> = stats
244 .edge_types
245 .iter()
246 .map(|(t, c)| serde_json::json!({"type": t, "count": c}))
247 .collect();
248 (stats.edge_count, arr)
249 }
250 };
251
252 let type_distribution: Vec<serde_json::Value> = {
253 let mut counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
254 for e in engine
255 .store()
256 .all_entities()
257 .filter(|e| !e.stub && in_mem(e))
258 {
259 *counts.entry(&e.entity_type).or_default() += 1;
260 }
261 let mut pairs: Vec<_> = counts.into_iter().collect();
262 pairs.sort_by(|a, b| a.0.cmp(b.0));
263 pairs
264 .into_iter()
265 .map(|(s, c)| serde_json::json!({"type": s, "count": c}))
266 .collect()
267 };
268
269 let writable_mems: Vec<String> = {
270 let mut names: Vec<String> = engine
271 .mem_router()
272 .writable_mems()
273 .iter()
274 .cloned()
275 .collect();
276 names.sort();
277 names
278 };
279 let default_writable_mem: Option<String> = engine.default_writable_mem().map(|s| s.to_string());
284 let read_mems: Vec<String> = {
285 let writable_set: std::collections::HashSet<&String> =
286 engine.mem_router().writable_mems().iter().collect();
287 let mut names: Vec<String> = engine
288 .mem_router()
289 .visible_mems()
290 .iter()
291 .filter(|n| !writable_set.contains(*n))
292 .cloned()
293 .collect();
294 names.sort();
295 names
296 };
297
298 let mem_schemas: Vec<serde_json::Value> = {
311 let mut entries: Vec<serde_json::Value> = Vec::new();
312 let writable_set: std::collections::HashSet<&String> = writable_mems.iter().collect();
313 for name in writable_mems.iter().chain(read_mems.iter()) {
314 if let Some(v) = vf
315 && name != v
316 {
317 continue;
318 }
319 if let Some(m) = engine.mount(name) {
320 let schema_ref = m
325 .schema
326 .as_ref()
327 .map(|s| s.as_display())
328 .unwrap_or_default();
329 let mut entry = serde_json::json!({
330 "mem": name,
331 "schema": schema_ref,
332 "writable": writable_set.contains(name),
333 });
334 if let Some(target) = &m.migration_target {
338 entry["migration_target"] = serde_json::json!(target.as_display());
339 }
340 entries.push(entry);
341 }
342 }
343 entries
344 };
345
346 let orphans_by_schema = engine.orphans_by_schema(&orphan_ids);
357 let scope_mems: Vec<String> = match vf {
358 Some(v) => vec![v.to_string()],
359 None => writable_mems
360 .iter()
361 .chain(read_mems.iter())
362 .cloned()
363 .collect(),
364 };
365 let communities_by_schema = engine.communities_by_schema(&scope_mems);
366
367 let mut result = serde_json::json!({
368 "mem": mem_filter,
369 "verdict_coverage": crate::ops::coverage::HEALTH_COVERAGE.wire_line_for_includes(
386 &include.iter().map(String::as_str).collect::<Vec<_>>(),
387 ),
388 "summary": {
389 "total_entities": real_count,
390 "total_orphans": orphan_ids.len(),
391 "total_stubs": stub_pairs.len(),
392 "total_stale": health.stale_entities.iter().filter(|e| match vf {
393 Some(v) => engine.store().get(&e.id).map(|ent| ent.mem == v).unwrap_or(false),
394 None => true,
395 }).count(),
396 "total_missing_fields": health.missing_fields.iter().filter(|h| match vf {
397 Some(v) => engine.store().get(&h.id).map(|ent| ent.mem == v).unwrap_or(false),
398 None => true,
399 }).count(),
400 "total_communities": community_count,
401 "orphans_by_schema": orphans_by_schema,
402 "communities_by_schema": communities_by_schema,
403 },
404 "total_nodes": total_count,
405 "real_nodes": real_count,
406 "stub_nodes": stub_count,
407 "total_edges": edge_count,
408 "edge_types": edge_types,
409 "type_distribution": type_distribution,
410 "writable_mems": writable_mems,
411 "default_writable_mem": default_writable_mem,
412 "read_mems": read_mems,
413 "mem_schemas": mem_schemas,
414 });
415 let obj = result.as_object_mut().unwrap();
416 if let Some(v) = vf
420 && let Some(schema) = crate::overview::mem_schema_ref(engine, v)
421 {
422 obj.insert("_mem_schema".into(), serde_json::Value::String(schema));
423 }
424 if !warnings.is_empty() {
425 obj.insert("warnings".into(), serde_json::json!(warnings));
426 }
427 if !health.quarantined.is_empty() {
430 obj.insert(
431 "quarantined".into(),
432 serde_json::to_value(&health.quarantined).unwrap_or_default(),
433 );
434 }
435 if !health.load_errors.is_empty() {
440 obj.insert(
441 "load_errors".into(),
442 serde_json::to_value(&health.load_errors).unwrap_or_default(),
443 );
444 }
445 if let Some(diag) = &health.boot_diagnosis {
446 obj.insert("boot_diagnosis".into(), diag.clone());
447 }
448 if !health.leaf_entities_by_type.is_empty() {
451 obj.insert(
452 "leaf_entities_by_type".into(),
453 serde_json::to_value(&health.leaf_entities_by_type).unwrap_or_default(),
454 );
455 }
456
457 if include.iter().any(|s| s == "orphans") {
458 let orphans_list: Vec<serde_json::Value> = orphan_ids
459 .into_iter()
460 .map(|id| {
461 let title = engine
462 .get_entity(&id)
463 .map(|e| e.title.clone())
464 .unwrap_or_default();
465 serde_json::json!({"id": id.to_string(), "title": title})
466 })
467 .collect();
468 obj.insert("orphans".into(), serde_json::json!(orphans_list));
469 }
470 if include.iter().any(|s| s == "stubs") {
471 let stubs_list: Vec<serde_json::Value> = stub_pairs
472 .into_iter()
473 .map(|(id, refs)| {
474 serde_json::json!({
475 "id": id.to_string(),
476 "referenced_by": refs.iter().map(|r| r.to_string()).collect::<Vec<_>>(),
477 })
478 })
479 .collect();
480 obj.insert("stubs".into(), serde_json::json!(stubs_list));
481 }
482 if include.iter().any(|s| s == "most_connected") {
483 use crate::graph::query::{Connectivity, cmp_by_dependency, connectivity_for};
484 let to_json = |c: Connectivity| {
489 let title = engine
490 .get_entity(&c.id)
491 .map(|e| e.title.clone())
492 .unwrap_or_default();
493 serde_json::json!({
494 "id": c.id.to_string(),
495 "title": title,
496 "total": c.total,
497 "incoming": c.incoming,
498 "outgoing": c.outgoing,
499 "typed_total": c.typed_total,
500 "typed_incoming": c.typed_incoming,
501 "typed_outgoing": c.typed_outgoing,
502 })
503 };
504 let connected: Vec<serde_json::Value> = if let Some(v) = vf {
505 let mut entries: Vec<Connectivity> = engine
511 .store()
512 .all_entities()
513 .filter(|e| !e.stub && e.mem == v)
514 .map(|e| connectivity_for(engine.store(), &e.id, |in_edge| in_edge.from.mem() == v))
515 .collect();
516 entries.sort_by(cmp_by_dependency);
517 entries.truncate(limit);
518 entries.into_iter().map(to_json).collect()
519 } else {
520 engine
521 .most_connected(limit)
522 .into_iter()
523 .map(to_json)
524 .collect()
525 };
526 obj.insert("most_connected".into(), serde_json::json!(connected));
527 }
528 if include.iter().any(|s| s == "missing_fields") {
529 let missing_fields: Vec<serde_json::Value> = health
530 .missing_fields
531 .iter()
532 .filter(|h| match vf {
533 Some(v) => engine
534 .store()
535 .get(&h.id)
536 .map(|e| e.mem == v)
537 .unwrap_or(false),
538 None => true,
539 })
540 .map(|h| {
541 let missing: Vec<&str> = h.issues.iter().map(|i| i.field.as_str()).collect();
547 let issues: Vec<serde_json::Value> = h
548 .issues
549 .iter()
550 .map(|i| {
551 serde_json::json!({
552 "field": i.field,
553 "code": i.code,
554 "message": i.message,
555 })
556 })
557 .collect();
558 serde_json::json!({
559 "id": h.id.to_string(),
560 "title": h.title,
561 "missing": missing,
562 "issues": issues,
563 })
564 })
565 .collect();
566 obj.insert("missing_fields".into(), serde_json::json!(missing_fields));
567 }
568 if include.iter().any(|s| s == "stale") {
569 let stale: Vec<serde_json::Value> = health
570 .stale_entities
571 .iter()
572 .filter(|e| match vf {
573 Some(v) => engine
574 .store()
575 .get(&e.id)
576 .map(|ent| ent.mem == v)
577 .unwrap_or(false),
578 None => true,
579 })
580 .map(stale_row)
581 .collect();
582 obj.insert("stale".into(), serde_json::json!(stale));
583 let fresh: Vec<serde_json::Value> = health
586 .anchor_fresh
587 .iter()
588 .filter(|e| match vf {
589 Some(v) => engine
590 .store()
591 .get(&e.id)
592 .map(|ent| ent.mem == v)
593 .unwrap_or(false),
594 None => true,
595 })
596 .map(stale_row)
597 .collect();
598 if !fresh.is_empty() {
599 obj.insert("anchor_fresh".into(), serde_json::json!(fresh));
600 }
601 }
602 if include.iter().any(|s| s == "dangling_links") {
603 let dangling = crate::ops::health::collect_dangling_links(engine.store(), vf);
604 let arr: Vec<serde_json::Value> = dangling
605 .into_iter()
606 .map(|dl| serde_json::to_value(&dl).unwrap())
607 .collect();
608 obj.insert("dangling_links".into(), serde_json::json!(arr));
609 }
610 if include.iter().any(|s| s == "anchors") {
611 obj.insert(
612 "anchors".into(),
613 crate::ops::health::health_anchors_axis(engine, vf),
614 );
615 }
616 if include.iter().any(|s| s == "stale_derivations") {
617 obj.insert(
618 "stale_derivations".into(),
619 crate::ops::health::health_stale_derivations_axis(engine, args.mem),
620 );
621 }
622 if include.iter().any(|s| s == "checks") {
623 obj.insert(
624 "checks".into(),
625 crate::ops::health::health_checks_axis(engine, args.mem),
626 );
627 }
628 if include.iter().any(|s| s == "signals") {
629 obj.insert("signals".into(), engine.health_signals_axis(args.mem));
633 }
634 if include.iter().any(|s| s == "labelling") {
635 obj.insert("labelling".into(), engine.health_labelling_axis(args.mem));
639 }
640 if include.iter().any(|s| s == "open_questions") {
641 obj.insert(
642 "open_questions".into(),
643 crate::ops::health::health_open_questions_axis(engine, args.mem),
644 );
645 }
646 if include.iter().any(|s| s == "vital_signs") {
647 obj.insert(
650 "vital_signs".into(),
651 crate::ops::health::health_vital_signs_axis(engine, args.mem),
652 );
653 }
654 if include.iter().any(|s| s == "due") {
655 let today = match args.today {
661 Some(t) => t.to_string(),
662 None => {
663 let now = engine.now_iso();
664 now.get(..10).unwrap_or(&now).to_string()
665 }
666 };
667 let brief = engine
668 .due_brief(&today, &crate::engine::due::DueWindow::Days(90), vf)
669 .map_err(|e| ComposeHealthError::InvalidTargetSchema {
670 raw: today.clone(),
671 reason: e,
672 })?;
673 obj.insert(
674 "due".into(),
675 serde_json::to_value(&brief).unwrap_or_default(),
676 );
677 }
678 if include.iter().any(|s| s == "friction") {
679 let summary = match engine.workspace_root() {
685 Some(root) => crate::friction::FrictionLedger::for_workspace(root).summarize(),
686 None => serde_json::json!({
687 "total": 0,
688 "by_code": {},
689 "by_verb": {},
690 "recent_24h": { "total": 0, "by_code": {} },
691 "ledger_bytes": 0,
692 }),
693 };
694 obj.insert("friction".into(), summary);
695 }
696 if include.iter().any(|s| s == "missing_required_outgoing") {
697 let reports = engine.missing_required_outgoing(vf);
698 let arr: Vec<serde_json::Value> = reports
699 .into_iter()
700 .map(|r| serde_json::to_value(&r).unwrap())
701 .collect();
702 obj.insert("missing_required_outgoing".into(), serde_json::json!(arr));
703 }
704 if include.iter().any(|s| s == "constraints") {
705 let reports = engine.constraint_findings(vf);
706 let arr: Vec<serde_json::Value> = reports
707 .into_iter()
708 .map(|r| serde_json::to_value(&r).unwrap())
709 .collect();
710 obj.insert("constraints".into(), serde_json::json!(arr));
711 let defects = engine.schema_format_defects();
712 if !defects.is_empty() {
713 obj.insert(
714 "schema_format_defects".into(),
715 serde_json::to_value(&defects).unwrap(),
716 );
717 }
718 }
719 if include.iter().any(|s| s == "tags") {
720 let (distribution, folded, untagged) =
721 crate::ops::health::collect_tag_distribution(engine.store(), vf, limit);
722 obj.insert(
723 "tag_distribution".into(),
724 serde_json::to_value(&distribution).unwrap(),
725 );
726 obj.insert(
727 "tag_distribution_folded".into(),
728 serde_json::to_value(&folded).unwrap(),
729 );
730 obj.insert(
731 "untagged_entities".into(),
732 serde_json::to_value(&untagged).unwrap(),
733 );
734 }
735 let wants_conformance = include
741 .iter()
742 .any(|s| s == "conformance" || s == "integrity");
743 if wants_conformance {
744 let wants_consistency = include.iter().any(|s| s == "integrity");
745 let target: Option<memstead_schema::SchemaRef> = match args.target_schema {
746 None => None,
747 Some(raw) => match raw.parse::<memstead_schema::SchemaRef>() {
748 Ok(r) => Some(r),
749 Err(reason) => {
750 return Err(ComposeHealthError::InvalidTargetSchema {
751 raw: raw.to_string(),
752 reason,
753 });
754 }
755 },
756 };
757 let scan_mems: Vec<String> = match vf {
758 Some(v) => vec![v.to_string()],
759 None => {
760 let mut all = writable_mems.clone();
761 all.sort();
762 all
763 }
764 };
765 let mut findings = Vec::new();
766 let mut observations = Vec::new();
767 for v in &scan_mems {
768 findings.extend(engine.conformance_findings(v, target.as_ref())?);
769 observations.extend(engine.body_observations(v, target.as_ref())?);
773 if wants_consistency {
774 findings.extend(engine.consistency_findings(v)?);
775 }
776 }
777 obj.insert("findings".into(), serde_json::to_value(&findings).unwrap());
778 obj.insert(
779 "body_observations".into(),
780 serde_json::to_value(&observations).unwrap(),
781 );
782 }
783
784 if include.iter().any(|s| s == "ledger") {
791 let mut ledger = engine.ledger_reconciliation();
792 if let Some(v) = vf {
793 ledger.retain(|mem, _| mem == v);
794 }
795 obj.insert(
796 "ledger".into(),
797 serde_json::to_value(ledger).unwrap_or_default(),
798 );
799 }
800
801 if args.include_config || include.iter().any(|s| s == "config") {
810 let config_mems: Vec<String> = match vf {
813 Some(v) => writable_mems.iter().filter(|m| *m == v).cloned().collect(),
814 None => writable_mems.clone(),
815 };
816 let entries = crate::ops::health::config_projection(
817 engine,
818 &config_mems,
819 config.mutations.clone(),
820 config.plugin.clone(),
821 );
822 for (k, v) in entries {
823 obj.insert(k, v);
824 }
825 }
826
827 if args.strict {
830 let ledger = engine
831 .workspace_root()
832 .map(crate::check::CheckLedger::for_workspace);
833 let axis = crate::ops::strict::compose_strict_axis(obj, ledger.as_ref(), vf);
834 obj.insert(
835 "strict".into(),
836 serde_json::to_value(&axis).unwrap_or_default(),
837 );
838 }
839
840 Ok(result)
841}
842
843pub fn render_health_markdown(v: &serde_json::Value) -> String {
851 use std::fmt::Write as _;
852 let mut s = String::new();
853 let _ = writeln!(s, "# Graph health");
854 if let Some(mem) = v.get("mem").and_then(|x| x.as_str()) {
855 let _ = writeln!(s, "\nMem filter: `{mem}`");
856 }
857
858 if let Some(sum) = v.get("summary").and_then(|x| x.as_object()) {
859 let _ = writeln!(s, "\n## Summary");
860 for key in [
861 "total_entities",
862 "total_orphans",
863 "total_stubs",
864 "total_stale",
865 "total_missing_fields",
866 "total_communities",
867 ] {
868 if let Some(n) = sum.get(key).and_then(|x| x.as_u64()) {
869 let _ = writeln!(s, "- {}: {n}", key.replace('_', " "));
870 }
871 }
872 render_count_map(&mut s, sum.get("orphans_by_schema"), "Orphans by schema");
873 render_count_map(
874 &mut s,
875 sum.get("communities_by_schema"),
876 "Communities by schema",
877 );
878 }
879
880 for key in ["total_nodes", "real_nodes", "stub_nodes", "total_edges"] {
881 if let Some(n) = v.get(key).and_then(|x| x.as_u64()) {
882 let _ = writeln!(s, "- {}: {n}", key.replace('_', " "));
883 }
884 }
885
886 for (key, title) in [
888 ("orphans", "Orphans"),
889 ("stubs", "Stubs"),
890 ("most_connected", "Most connected"),
891 ("missing_fields", "Missing fields"),
892 ("stale", "Stale"),
893 ("dangling_links", "Dangling links"),
894 ("missing_required_outgoing", "Missing required outgoing"),
895 ("constraints", "Constraint violations"),
896 ("findings", "Findings"),
897 ] {
898 if let Some(arr) = v.get(key).and_then(|x| x.as_array()) {
899 let _ = writeln!(s, "\n## {title} ({})", arr.len());
900 for item in arr {
901 let _ = writeln!(s, "- {}", summarize_health_item(item));
902 }
903 }
904 }
905
906 if let Some(arr) = v.get("body_observations").and_then(|x| x.as_array()) {
911 let _ = writeln!(s, "\n## Body observations ({})", arr.len());
912 for item in arr {
913 let detail = &item["detail"];
914 let subject = detail
915 .get("heading")
916 .or_else(|| detail.get("key"))
917 .and_then(|x| x.as_str())
918 .unwrap_or("");
919 let _ = writeln!(
920 s,
921 "- {} [{}] `{subject}`: {} ({})",
922 item["id"].as_str().unwrap_or(""),
923 item["code"].as_str().unwrap_or(""),
924 item["fate"].as_str().unwrap_or(""),
925 detail
926 .get("note")
927 .and_then(|x| x.as_str())
928 .unwrap_or("no note"),
929 );
930 }
931 }
932
933 if let Some(due) = v.get("due").and_then(|x| x.as_object()) {
935 let rows = |key: &str| -> Vec<&serde_json::Value> {
936 due.get(key)
937 .and_then(|x| x.as_array())
938 .map(|a| a.iter().collect())
939 .unwrap_or_default()
940 };
941 let overdue = rows("overdue");
942 let soon = rows("due_soon");
943 let _ = writeln!(
944 s,
945 "\n## Due ({} overdue, {} due soon; today {}, through {})",
946 overdue.len(),
947 soon.len(),
948 due.get("today").and_then(|x| x.as_str()).unwrap_or("?"),
949 due.get("through").and_then(|x| x.as_str()).unwrap_or("?"),
950 );
951 for r in overdue {
952 let _ = writeln!(
953 s,
954 "- `{}` — {} — **{}** OVERDUE ({} days past) (status: {}, mem: {})",
955 r["id"].as_str().unwrap_or(""),
956 r["title"].as_str().unwrap_or(""),
957 r["date"].as_str().unwrap_or(""),
958 r["days_past"].as_u64().unwrap_or(0),
959 r["status"].as_str().unwrap_or(""),
960 r["mem"].as_str().unwrap_or(""),
961 );
962 }
963 for r in soon {
964 let _ = writeln!(
965 s,
966 "- `{}` — {} — **{}** (in {} days) (status: {}, mem: {})",
967 r["id"].as_str().unwrap_or(""),
968 r["title"].as_str().unwrap_or(""),
969 r["date"].as_str().unwrap_or(""),
970 r["days_until"].as_u64().unwrap_or(0),
971 r["status"].as_str().unwrap_or(""),
972 r["mem"].as_str().unwrap_or(""),
973 );
974 }
975 }
976
977 if let Some(obj) = v.get("anchors").and_then(|x| x.as_object()) {
983 let _ = writeln!(s, "\n## Anchors ({} mems)", obj.len());
984 for (mem, counts) in obj {
985 if let Some(c) = counts.get("condition").filter(|c| !c.is_null()) {
986 let _ = writeln!(
987 s,
988 "- `{mem}`: ANCHORS_SIDECAR_UNREADABLE — {} — {}",
989 c["reason"].as_str().unwrap_or("reason not stated"),
990 counts["population"]
991 .as_str()
992 .unwrap_or("population not stated"),
993 );
994 continue;
995 }
996 let figure = crate::anchor::AnchorResolutionFigure::from_json(counts)
999 .map(|f| f.to_string())
1000 .unwrap_or_else(|| "resolution figure not stated with its population".to_string());
1001 let _ = writeln!(
1002 s,
1003 "- `{mem}`: resolves {figure}; drifted {}, recheck {}, unresolvable (artifact \
1004 gone) {}, unobserved (not measured) {}, dangling (entity gone) {}",
1005 counts["drifted"].as_u64().unwrap_or(0),
1006 counts["recheck"].as_u64().unwrap_or(0),
1007 counts["unresolvable"].as_u64().unwrap_or(0),
1008 counts["unobserved"].as_u64().unwrap_or(0),
1009 counts["dangling"].as_u64().unwrap_or(0),
1010 );
1011 }
1012 }
1013
1014 if let Some(obj) = v.get("vital_signs").and_then(|x| x.as_object()) {
1017 let mems: Vec<(&String, &serde_json::Value)> =
1018 obj.iter().filter(|(k, _)| *k != "_item_cap").collect();
1019 let _ = writeln!(s, "\n## Vital signs ({} mems)", mems.len());
1020 for (mem, sig) in mems {
1021 let count = |k: &str| sig[k]["count"].as_u64().unwrap_or(0);
1022 let share = match sig["type_share_by_community"]["status"].as_str() {
1023 Some("declared") => format!(
1024 "last-resort type `{}` over {} communit{}",
1025 sig["type_share_by_community"]["last_resort_type"]
1026 .as_str()
1027 .unwrap_or("?"),
1028 count("type_share_by_community"),
1029 if count("type_share_by_community") == 1 {
1030 "y"
1031 } else {
1032 "ies"
1033 }
1034 ),
1035 _ => "last-resort type not declared".to_string(),
1036 };
1037 let unclaimed = match sig["unclaimed_source_files"]["status"].as_str() {
1038 Some("enumerated") => format!(
1039 "{} unclaimed source file(s)",
1040 count("unclaimed_source_files")
1041 ),
1042 _ => "no bound source".to_string(),
1043 };
1044 let _ = writeln!(
1045 s,
1046 "- `{mem}`: {share}; {unclaimed}; {} contested unowned file(s); {} zero-outgoing \
1047 entit{} in {} communit{}; {} empty declared section(s)",
1048 count("contested_unowned_files"),
1049 sig["zero_outgoing_entities"]["entities"]
1050 .as_u64()
1051 .unwrap_or(0),
1052 if sig["zero_outgoing_entities"]["entities"]
1053 .as_u64()
1054 .unwrap_or(0)
1055 == 1
1056 {
1057 "y"
1058 } else {
1059 "ies"
1060 },
1061 count("zero_outgoing_entities"),
1062 if count("zero_outgoing_entities") == 1 {
1063 "y"
1064 } else {
1065 "ies"
1066 },
1067 count("empty_declared_sections"),
1068 );
1069 }
1070 }
1071
1072 if let Some(obj) = v.get("checks").and_then(|x| x.as_object()) {
1077 let _ = writeln!(s, "\n## Checks ({} mems)", obj.len());
1078 for (mem, c) in obj {
1079 let count = |key: &str| c.get(key).and_then(|x| x.as_u64()).unwrap_or(0);
1080 let conf = |key: &str| {
1081 c.get("conformance")
1082 .and_then(|g| g.get(key))
1083 .and_then(|x| x.as_u64())
1084 .unwrap_or(0)
1085 };
1086 let gate = |key: &str| {
1087 c.get("independence")
1088 .and_then(|g| g.get(key))
1089 .and_then(|e| e.get("count"))
1090 .and_then(|x| x.as_u64())
1091 .unwrap_or(0)
1092 };
1093 let _ = writeln!(
1094 s,
1095 "- `{mem}`: never_checked {}, checked_ok {}, check_failed {}, \
1096 check_stale {}; conformance: never_checked {}, \
1097 checked_ok {}, check_failed {}, check_stale {}; \
1098 independence: self_checked {}, \
1099 confirmed_independent {}, unconfirmable {}",
1100 count("never_checked"),
1101 count("checked_ok"),
1102 count("check_failed"),
1103 count("check_stale"),
1104 conf("never_checked"),
1105 conf("checked_ok"),
1106 conf("check_failed"),
1107 conf("check_stale"),
1108 gate("self_checked"),
1109 gate("confirmed_independent"),
1110 gate("unconfirmable"),
1111 );
1112 if let Some(foreign) = c.get("foreign_kinds").and_then(|f| f.as_object())
1116 && !foreign.is_empty()
1117 {
1118 let listed: Vec<String> = foreign
1119 .iter()
1120 .map(|(k, n)| format!("{k} {}", n.as_u64().unwrap_or(0)))
1121 .collect();
1122 let _ = writeln!(s, " - foreign kinds: {}", listed.join(", "));
1123 }
1124 if let Some(findings) = c.get("findings").and_then(|f| f.as_object()) {
1125 for (entity, f) in findings {
1126 let code = f["finding"]["code"].as_str().unwrap_or("?");
1127 let section = f["finding"]["section"]
1128 .as_str()
1129 .map(|x| format!(" [{x}]"))
1130 .unwrap_or_default();
1131 let message = f["finding"]["message"].as_str().unwrap_or("");
1132 let _ = writeln!(
1133 s,
1134 " - finding on `{entity}` ({} {}): {code}{section} — {message}",
1135 f["kind"].as_str().unwrap_or("verification"),
1136 f["verdict"].as_str().unwrap_or("?"),
1137 );
1138 }
1139 }
1140 }
1141 }
1142
1143 if let Some(obj) = v.get("stale_derivations").and_then(|x| x.as_object()) {
1146 let total: usize = obj
1147 .values()
1148 .filter_map(|a| a.as_array().map(|a| a.len()))
1149 .sum();
1150 let _ = writeln!(s, "\n## Stale derivations ({total} findings)");
1151 for (mem, findings) in obj {
1152 for f in findings.as_array().into_iter().flatten() {
1153 let _ = writeln!(
1154 s,
1155 "- `{mem}`: {} -[{}]-> {} ({})",
1156 f.get("source").and_then(|x| x.as_str()).unwrap_or(""),
1157 f.get("rel_type").and_then(|x| x.as_str()).unwrap_or(""),
1158 f.get("target").and_then(|x| x.as_str()).unwrap_or(""),
1159 f.get("state").and_then(|x| x.as_str()).unwrap_or(""),
1160 );
1161 }
1162 }
1163 }
1164
1165 if let Some(arr) = v.get("quarantined").and_then(|x| x.as_array()) {
1170 let _ = writeln!(s, "\n## Quarantined mems ({})", arr.len());
1171 for q in arr {
1172 let _ = writeln!(
1173 s,
1174 "- `{}` [{}] {}",
1175 q.get("mem").and_then(|x| x.as_str()).unwrap_or(""),
1176 q.get("reason_code").and_then(|x| x.as_str()).unwrap_or(""),
1177 q.get("reason_message")
1178 .and_then(|x| x.as_str())
1179 .unwrap_or(""),
1180 );
1181 }
1182 }
1183
1184 if let Some(arr) = v.get("warnings").and_then(|x| x.as_array())
1185 && !arr.is_empty()
1186 {
1187 let _ = writeln!(s, "\n## Warnings ({})", arr.len());
1188 for w in arr {
1189 let code = w.get("code").and_then(|x| x.as_str()).unwrap_or("");
1190 let msg = w.get("message").and_then(|x| x.as_str()).unwrap_or("");
1191 let _ = writeln!(s, "- [{code}] {msg}");
1192 }
1193 }
1194
1195 s
1196}
1197
1198fn render_count_map(s: &mut String, val: Option<&serde_json::Value>, title: &str) {
1202 use std::fmt::Write as _;
1203 let Some(map) = val.and_then(|x| x.as_object()) else {
1204 return;
1205 };
1206 if map.is_empty() {
1207 return;
1208 }
1209 let _ = writeln!(s, "- {title}:");
1210 for (k, n) in map {
1211 let label = if k.is_empty() {
1212 "(unpinned)"
1213 } else {
1214 k.as_str()
1215 };
1216 let _ = writeln!(s, " - {label}: {}", n.as_u64().unwrap_or(0));
1217 }
1218}
1219
1220fn summarize_health_item(item: &serde_json::Value) -> String {
1232 if let Some(id) = item.get("id").and_then(|x| x.as_str()) {
1233 match item.get("title").and_then(|x| x.as_str()) {
1234 Some(t) if !t.is_empty() => format!("{id} — {t}"),
1235 _ => id.to_string(),
1236 }
1237 } else if let Some(from) = item.get("from").and_then(|x| x.as_str()) {
1238 let target = item.get("target_id").and_then(|x| x.as_str()).unwrap_or("");
1239 match item.get("kind").and_then(|x| x.as_str()) {
1240 Some(kind) => format!("[{kind}] {from} → {target}"),
1241 None => format!("{from} → {target}"),
1242 }
1243 } else {
1244 serde_json::to_string(item).unwrap_or_default()
1245 }
1246}
1247
1248fn stale_row(e: &crate::ops::StaleEntity) -> serde_json::Value {
1253 let mut row = serde_json::json!({
1254 "id": e.id.to_string(),
1255 "title": e.title,
1256 "days_since_modified": e.days_since_modified,
1257 });
1258 if let Some(state) = &e.anchor_state {
1259 let obj = row.as_object_mut().unwrap();
1260 obj.insert("clock".into(), serde_json::json!("anchors"));
1261 obj.insert("anchor_state".into(), serde_json::json!(state));
1262 }
1263 row
1264}
1265
1266#[cfg(test)]
1267mod tests {
1268 use super::render_health_markdown;
1269 use serde_json::json;
1270
1271 fn base_payload() -> serde_json::Value {
1272 json!({
1273 "summary": { "total_entities": 1 },
1274 "total_nodes": 1,
1275 })
1276 }
1277
1278 #[test]
1285 fn body_observations_render_their_code_and_fate_not_just_an_id() {
1286 let mut v = base_payload();
1287 v["body_observations"] = json!([{
1288 "id": "specs--alpha",
1289 "code": "ABSORBED_SECTION",
1290 "fate": "absorbed",
1291 "detail": { "heading": "Rogue", "note": "survives the next write" },
1292 }, {
1293 "id": "specs--beta",
1294 "code": "UNDECLARED_METADATA_KEY",
1295 "fate": "dropped",
1296 "detail": { "key": "reviewer", "note": "the next write drops it" },
1297 }]);
1298 let md = render_health_markdown(&v);
1299 assert!(md.contains("## Body observations (2)"), "{md}");
1300 assert!(
1301 md.contains(
1302 "- specs--alpha [ABSORBED_SECTION] `Rogue`: absorbed (survives the next write)"
1303 ),
1304 "{md}"
1305 );
1306 assert!(
1307 md.contains(
1308 "- specs--beta [UNDECLARED_METADATA_KEY] `reviewer`: dropped \
1309 (the next write drops it)"
1310 ),
1311 "{md}"
1312 );
1313 assert!(!render_health_markdown(&base_payload()).contains("Body observations"));
1315 }
1316
1317 #[test]
1324 fn render_health_markdown_names_the_dangling_condition() {
1325 let mut v = base_payload();
1326 v["dangling_links"] = json!([
1327 {
1328 "kind": "DANGLING_LINK_TARGET_MISSING",
1329 "from": "specs--a", "target_id": "specs--gone",
1330 "target_path": "gone", "section": "purpose",
1331 },
1332 {
1333 "kind": "DANGLING_RELATION_TARGET_MISSING",
1334 "from": "specs--b", "target_id": "specs--vanished",
1335 "target_path": "vanished", "section": null,
1336 },
1337 ]);
1338 let md = render_health_markdown(&v);
1339 assert!(
1340 md.contains("[DANGLING_LINK_TARGET_MISSING] specs--a → specs--gone"),
1341 "{md}"
1342 );
1343 assert!(
1344 md.contains("[DANGLING_RELATION_TARGET_MISSING] specs--b → specs--vanished"),
1345 "{md}"
1346 );
1347 assert!(
1349 !md.contains("- specs--a → specs--gone"),
1350 "the unprefixed form is what fused them: {md}"
1351 );
1352 }
1353
1354 #[test]
1361 fn render_health_markdown_covers_checks_derivations_and_quarantine() {
1362 let mut v = base_payload();
1364 v["checks"] = json!({
1365 "specs": {
1366 "never_checked": 2, "checked_ok": 1,
1367 "check_failed": 0, "check_stale": 0,
1368 "conformance": {
1369 "never_checked": 3, "checked_ok": 0,
1370 "check_failed": 0, "check_stale": 0,
1371 },
1372 "independence": {
1373 "self_checked": { "count": 0, "items": [] },
1374 "confirmed_independent": { "count": 0, "items": [] },
1375 "unconfirmable": { "count": 1, "items": ["specs--a"] },
1376 },
1377 }
1378 });
1379 v["stale_derivations"] = json!({
1380 "specs": [{
1381 "source": "specs--a", "rel_type": "DERIVES_FROM",
1382 "target": "specs--b", "state": "stale",
1383 "baseline": "aaa", "current": "bbb",
1384 }]
1385 });
1386 v["quarantined"] = json!([{
1387 "mem": "broken",
1388 "reason_code": "SCHEMA_NOT_FOUND",
1389 "reason_message": "no schema; repair via memstead mem set-schema",
1390 }]);
1391 let md = render_health_markdown(&v);
1392 assert!(md.contains("## Checks (1 mems)"), "{md}");
1393 assert!(
1394 md.contains(
1395 "- `specs`: never_checked 2, checked_ok 1, check_failed 0, \
1396 check_stale 0; conformance: never_checked 3, checked_ok 0, \
1397 check_failed 0, check_stale 0; independence: self_checked 0, \
1398 confirmed_independent 0, unconfirmable 1"
1399 ),
1400 "{md}"
1401 );
1402 assert!(md.contains("## Stale derivations (1 findings)"), "{md}");
1403 assert!(
1404 md.contains("- `specs`: specs--a -[DERIVES_FROM]-> specs--b (stale)"),
1405 "{md}"
1406 );
1407 assert!(md.contains("## Quarantined mems (1)"), "{md}");
1408 assert!(
1409 md.contains(
1410 "- `broken` [SCHEMA_NOT_FOUND] no schema; repair via memstead mem set-schema"
1411 ),
1412 "{md}"
1413 );
1414
1415 let mut empty = base_payload();
1417 empty["checks"] = json!({});
1418 empty["stale_derivations"] = json!({ "specs": [] });
1419 let md = render_health_markdown(&empty);
1420 assert!(md.contains("## Checks (0 mems)"), "{md}");
1421 assert!(md.contains("## Stale derivations (0 findings)"), "{md}");
1422
1423 let base_md = render_health_markdown(&base_payload());
1426 for heading in ["## Checks", "## Stale derivations", "## Quarantined mems"] {
1427 assert!(
1428 !base_md.contains(heading),
1429 "absent key must render nothing: {base_md}"
1430 );
1431 }
1432 let appended = render_health_markdown(&v);
1433 assert!(
1434 appended.starts_with(&base_md),
1435 "sections append; the base output stays byte-identical"
1436 );
1437 }
1438}