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 => {
671 let now = engine.now_iso();
672 now.get(..10).unwrap_or(&now).to_string()
673 }
674 };
675 let brief = engine
676 .due_brief(&today, &crate::engine::due::DueWindow::Days(90), vf)
677 .map_err(|e| ComposeHealthError::InvalidTargetSchema {
678 raw: today.clone(),
679 reason: e,
680 })?;
681 obj.insert(
682 "due".into(),
683 serde_json::to_value(&brief).unwrap_or_default(),
684 );
685 }
686 if include.iter().any(|s| s == "friction") {
687 let summary = match engine.workspace_root() {
693 Some(root) => crate::friction::FrictionLedger::for_workspace(root).summarize(),
694 None => serde_json::json!({
695 "total": 0,
696 "by_code": {},
697 "by_verb": {},
698 "recent_24h": { "total": 0, "by_code": {} },
699 "ledger_bytes": 0,
700 }),
701 };
702 obj.insert("friction".into(), summary);
703 }
704 if include.iter().any(|s| s == "missing_required_outgoing") {
705 let reports = engine.missing_required_outgoing(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("missing_required_outgoing".into(), serde_json::json!(arr));
711 }
712 if include.iter().any(|s| s == "constraints") {
713 let reports = engine.constraint_findings(vf);
714 let arr: Vec<serde_json::Value> = reports
715 .into_iter()
716 .map(|r| serde_json::to_value(&r).unwrap())
717 .collect();
718 obj.insert("constraints".into(), serde_json::json!(arr));
719 let defects = engine.schema_format_defects();
720 if !defects.is_empty() {
721 obj.insert(
722 "schema_format_defects".into(),
723 serde_json::to_value(&defects).unwrap(),
724 );
725 }
726 }
727 if include.iter().any(|s| s == "tags") {
728 let (distribution, folded, untagged) =
729 crate::ops::health::collect_tag_distribution(engine.store(), vf, limit);
730 obj.insert(
731 "tag_distribution".into(),
732 serde_json::to_value(&distribution).unwrap(),
733 );
734 obj.insert(
735 "tag_distribution_folded".into(),
736 serde_json::to_value(&folded).unwrap(),
737 );
738 obj.insert(
739 "untagged_entities".into(),
740 serde_json::to_value(&untagged).unwrap(),
741 );
742 }
743 let wants_conformance = include
749 .iter()
750 .any(|s| s == "conformance" || s == "integrity");
751 if wants_conformance {
752 let wants_consistency = include.iter().any(|s| s == "integrity");
753 let target: Option<memstead_schema::SchemaRef> = match args.target_schema {
754 None => None,
755 Some(raw) => match raw.parse::<memstead_schema::SchemaRef>() {
756 Ok(r) => Some(r),
757 Err(reason) => {
758 return Err(ComposeHealthError::InvalidTargetSchema {
759 raw: raw.to_string(),
760 reason,
761 });
762 }
763 },
764 };
765 let scan_mems: Vec<String> = match vf {
766 Some(v) => vec![v.to_string()],
767 None => {
768 let mut all = writable_mems.clone();
769 all.sort();
770 all
771 }
772 };
773 let mut findings = Vec::new();
774 let mut observations = Vec::new();
775 for v in &scan_mems {
776 findings.extend(engine.conformance_findings(v, target.as_ref())?);
777 observations.extend(engine.body_observations(v, target.as_ref())?);
781 if wants_consistency {
782 findings.extend(engine.consistency_findings(v)?);
783 }
784 }
785 obj.insert("findings".into(), serde_json::to_value(&findings).unwrap());
786 obj.insert(
787 "body_observations".into(),
788 serde_json::to_value(&observations).unwrap(),
789 );
790 }
791
792 if include.iter().any(|s| s == "ledger") {
799 let mut ledger = engine.ledger_reconciliation();
800 if let Some(v) = vf {
801 ledger.retain(|mem, _| mem == v);
802 }
803 obj.insert(
804 "ledger".into(),
805 serde_json::to_value(ledger).unwrap_or_default(),
806 );
807 }
808
809 if args.include_config || include.iter().any(|s| s == "config") {
818 let config_mems: Vec<String> = match vf {
821 Some(v) => writable_mems.iter().filter(|m| *m == v).cloned().collect(),
822 None => writable_mems.clone(),
823 };
824 let entries = crate::ops::health::config_projection(
825 engine,
826 &config_mems,
827 config.mutations.clone(),
828 config.plugin.clone(),
829 );
830 for (k, v) in entries {
831 obj.insert(k, v);
832 }
833 }
834
835 if args.strict {
838 let ledger = engine
839 .workspace_root()
840 .map(crate::check::CheckLedger::for_workspace);
841 let axis = crate::ops::strict::compose_strict_axis(obj, ledger.as_ref(), vf);
842 obj.insert(
843 "strict".into(),
844 serde_json::to_value(&axis).unwrap_or_default(),
845 );
846 }
847
848 Ok(result)
849}
850
851pub fn render_health_markdown(v: &serde_json::Value) -> String {
859 use std::fmt::Write as _;
860 let mut s = String::new();
861 let _ = writeln!(s, "# Graph health");
862 if let Some(mem) = v.get("mem").and_then(|x| x.as_str()) {
863 let _ = writeln!(s, "\nMem filter: `{mem}`");
864 }
865
866 if let Some(sum) = v.get("summary").and_then(|x| x.as_object()) {
867 let _ = writeln!(s, "\n## Summary");
868 for key in [
869 "total_entities",
870 "total_orphans",
871 "total_stubs",
872 "total_stale",
873 "total_missing_fields",
874 "total_communities",
875 ] {
876 if let Some(n) = sum.get(key).and_then(|x| x.as_u64()) {
877 let _ = writeln!(s, "- {}: {n}", key.replace('_', " "));
878 }
879 }
880 render_count_map(&mut s, sum.get("orphans_by_schema"), "Orphans by schema");
881 render_count_map(
882 &mut s,
883 sum.get("communities_by_schema"),
884 "Communities by schema",
885 );
886 }
887
888 for key in ["total_nodes", "real_nodes", "stub_nodes", "total_edges"] {
889 if let Some(n) = v.get(key).and_then(|x| x.as_u64()) {
890 let _ = writeln!(s, "- {}: {n}", key.replace('_', " "));
891 }
892 }
893
894 for (key, title) in [
896 ("orphans", "Orphans"),
897 ("stubs", "Stubs"),
898 ("most_connected", "Most connected"),
899 ("missing_fields", "Missing fields"),
900 ("stale", "Stale"),
901 ("dangling_links", "Dangling links"),
902 ("missing_required_outgoing", "Missing required outgoing"),
903 ("constraints", "Constraint violations"),
904 ("findings", "Findings"),
905 ] {
906 if let Some(arr) = v.get(key).and_then(|x| x.as_array()) {
907 let _ = writeln!(s, "\n## {title} ({})", arr.len());
908 for item in arr {
909 let _ = writeln!(s, "- {}", summarize_health_item(item));
910 }
911 }
912 }
913
914 if let Some(arr) = v.get("body_observations").and_then(|x| x.as_array()) {
919 let _ = writeln!(s, "\n## Body observations ({})", arr.len());
920 for item in arr {
921 let detail = &item["detail"];
922 let subject = detail
923 .get("heading")
924 .or_else(|| detail.get("key"))
925 .and_then(|x| x.as_str())
926 .unwrap_or("");
927 let _ = writeln!(
928 s,
929 "- {} [{}] `{subject}`: {} ({})",
930 item["id"].as_str().unwrap_or(""),
931 item["code"].as_str().unwrap_or(""),
932 item["fate"].as_str().unwrap_or(""),
933 detail
934 .get("note")
935 .and_then(|x| x.as_str())
936 .unwrap_or("no note"),
937 );
938 }
939 }
940
941 if let Some(due) = v.get("due").and_then(|x| x.as_object()) {
943 let rows = |key: &str| -> Vec<&serde_json::Value> {
944 due.get(key)
945 .and_then(|x| x.as_array())
946 .map(|a| a.iter().collect())
947 .unwrap_or_default()
948 };
949 let overdue = rows("overdue");
950 let soon = rows("due_soon");
951 let _ = writeln!(
952 s,
953 "\n## Due ({} overdue, {} due soon; today {}, through {})",
954 overdue.len(),
955 soon.len(),
956 due.get("today").and_then(|x| x.as_str()).unwrap_or("?"),
957 due.get("through").and_then(|x| x.as_str()).unwrap_or("?"),
958 );
959 for r in overdue {
960 let _ = writeln!(
961 s,
962 "- `{}` — {} — **{}** OVERDUE ({} days past) (status: {}, mem: {})",
963 r["id"].as_str().unwrap_or(""),
964 r["title"].as_str().unwrap_or(""),
965 r["date"].as_str().unwrap_or(""),
966 r["days_past"].as_u64().unwrap_or(0),
967 r["status"].as_str().unwrap_or(""),
968 r["mem"].as_str().unwrap_or(""),
969 );
970 }
971 for r in soon {
972 let _ = writeln!(
973 s,
974 "- `{}` — {} — **{}** (in {} days) (status: {}, mem: {})",
975 r["id"].as_str().unwrap_or(""),
976 r["title"].as_str().unwrap_or(""),
977 r["date"].as_str().unwrap_or(""),
978 r["days_until"].as_u64().unwrap_or(0),
979 r["status"].as_str().unwrap_or(""),
980 r["mem"].as_str().unwrap_or(""),
981 );
982 }
983 }
984
985 if let Some(obj) = v.get("anchors").and_then(|x| x.as_object()) {
991 let _ = writeln!(s, "\n## Anchors ({} mems)", obj.len());
992 for (mem, counts) in obj {
993 if let Some(c) = counts.get("condition").filter(|c| !c.is_null()) {
994 let _ = writeln!(
995 s,
996 "- `{mem}`: ANCHORS_SIDECAR_UNREADABLE — {} — {}",
997 c["reason"].as_str().unwrap_or("reason not stated"),
998 counts["population"]
999 .as_str()
1000 .unwrap_or("population not stated"),
1001 );
1002 continue;
1003 }
1004 let figure = crate::anchor::AnchorResolutionFigure::from_json(counts)
1007 .map(|f| f.to_string())
1008 .unwrap_or_else(|| "resolution figure not stated with its population".to_string());
1009 let _ = writeln!(
1010 s,
1011 "- `{mem}`: resolves {figure}; drifted {}, recheck {}, unresolvable (artifact \
1012 gone) {}, unobserved (not measured) {}, dangling (entity gone) {}",
1013 counts["drifted"].as_u64().unwrap_or(0),
1014 counts["recheck"].as_u64().unwrap_or(0),
1015 counts["unresolvable"].as_u64().unwrap_or(0),
1016 counts["unobserved"].as_u64().unwrap_or(0),
1017 counts["dangling"].as_u64().unwrap_or(0),
1018 );
1019 }
1020 }
1021
1022 if let Some(obj) = v.get("vital_signs").and_then(|x| x.as_object()) {
1025 let mems: Vec<(&String, &serde_json::Value)> =
1026 obj.iter().filter(|(k, _)| *k != "_item_cap").collect();
1027 let _ = writeln!(s, "\n## Vital signs ({} mems)", mems.len());
1028 for (mem, sig) in mems {
1029 let count = |k: &str| sig[k]["count"].as_u64().unwrap_or(0);
1030 let share = match sig["type_share_by_community"]["status"].as_str() {
1031 Some("declared") => format!(
1032 "last-resort type `{}` over {} communit{}",
1033 sig["type_share_by_community"]["last_resort_type"]
1034 .as_str()
1035 .unwrap_or("?"),
1036 count("type_share_by_community"),
1037 if count("type_share_by_community") == 1 {
1038 "y"
1039 } else {
1040 "ies"
1041 }
1042 ),
1043 _ => "last-resort type not declared".to_string(),
1044 };
1045 let unclaimed = match sig["unclaimed_source_files"]["status"].as_str() {
1046 Some("enumerated") => format!(
1047 "{} unclaimed source file(s)",
1048 count("unclaimed_source_files")
1049 ),
1050 _ => "no bound source".to_string(),
1051 };
1052 let _ = writeln!(
1053 s,
1054 "- `{mem}`: {share}; {unclaimed}; {} contested unowned file(s); {} zero-outgoing \
1055 entit{} in {} communit{}; {} empty declared section(s)",
1056 count("contested_unowned_files"),
1057 sig["zero_outgoing_entities"]["entities"]
1058 .as_u64()
1059 .unwrap_or(0),
1060 if sig["zero_outgoing_entities"]["entities"]
1061 .as_u64()
1062 .unwrap_or(0)
1063 == 1
1064 {
1065 "y"
1066 } else {
1067 "ies"
1068 },
1069 count("zero_outgoing_entities"),
1070 if count("zero_outgoing_entities") == 1 {
1071 "y"
1072 } else {
1073 "ies"
1074 },
1075 count("empty_declared_sections"),
1076 );
1077 }
1078 }
1079
1080 if let Some(obj) = v.get("checks").and_then(|x| x.as_object()) {
1085 let _ = writeln!(s, "\n## Checks ({} mems)", obj.len());
1086 for (mem, c) in obj {
1087 let count = |key: &str| c.get(key).and_then(|x| x.as_u64()).unwrap_or(0);
1088 let conf = |key: &str| {
1089 c.get("conformance")
1090 .and_then(|g| g.get(key))
1091 .and_then(|x| x.as_u64())
1092 .unwrap_or(0)
1093 };
1094 let gate = |key: &str| {
1095 c.get("independence")
1096 .and_then(|g| g.get(key))
1097 .and_then(|e| e.get("count"))
1098 .and_then(|x| x.as_u64())
1099 .unwrap_or(0)
1100 };
1101 let _ = writeln!(
1102 s,
1103 "- `{mem}`: never_checked {}, checked_ok {}, check_failed {}, \
1104 check_stale {}; conformance: never_checked {}, \
1105 checked_ok {}, check_failed {}, check_stale {}; \
1106 independence: self_checked {}, \
1107 confirmed_independent {}, unconfirmable {}",
1108 count("never_checked"),
1109 count("checked_ok"),
1110 count("check_failed"),
1111 count("check_stale"),
1112 conf("never_checked"),
1113 conf("checked_ok"),
1114 conf("check_failed"),
1115 conf("check_stale"),
1116 gate("self_checked"),
1117 gate("confirmed_independent"),
1118 gate("unconfirmable"),
1119 );
1120 if let Some(foreign) = c.get("foreign_kinds").and_then(|f| f.as_object())
1124 && !foreign.is_empty()
1125 {
1126 let listed: Vec<String> = foreign
1127 .iter()
1128 .map(|(k, n)| format!("{k} {}", n.as_u64().unwrap_or(0)))
1129 .collect();
1130 let _ = writeln!(s, " - foreign kinds: {}", listed.join(", "));
1131 }
1132 if let Some(findings) = c.get("findings").and_then(|f| f.as_object()) {
1133 for (entity, f) in findings {
1134 let _ = writeln!(s, "{}", render_check_finding_line(entity, f));
1135 }
1136 }
1137 }
1138 }
1139
1140 if let Some(obj) = v.get("stale_derivations").and_then(|x| x.as_object()) {
1143 let total: usize = obj
1144 .values()
1145 .filter_map(|a| a.as_array().map(|a| a.len()))
1146 .sum();
1147 let _ = writeln!(s, "\n## Stale derivations ({total} findings)");
1148 for (mem, findings) in obj {
1149 for f in findings.as_array().into_iter().flatten() {
1150 let _ = writeln!(
1151 s,
1152 "- `{mem}`: {} -[{}]-> {} ({})",
1153 f.get("source").and_then(|x| x.as_str()).unwrap_or(""),
1154 f.get("rel_type").and_then(|x| x.as_str()).unwrap_or(""),
1155 f.get("target").and_then(|x| x.as_str()).unwrap_or(""),
1156 f.get("state").and_then(|x| x.as_str()).unwrap_or(""),
1157 );
1158 }
1159 }
1160 }
1161
1162 if let Some(arr) = v.get("quarantined").and_then(|x| x.as_array()) {
1167 let _ = writeln!(s, "\n## Quarantined mems ({})", arr.len());
1168 for q in arr {
1169 let _ = writeln!(
1170 s,
1171 "- `{}` [{}] {}",
1172 q.get("mem").and_then(|x| x.as_str()).unwrap_or(""),
1173 q.get("reason_code").and_then(|x| x.as_str()).unwrap_or(""),
1174 q.get("reason_message")
1175 .and_then(|x| x.as_str())
1176 .unwrap_or(""),
1177 );
1178 }
1179 }
1180
1181 if let Some(arr) = v.get("warnings").and_then(|x| x.as_array())
1182 && !arr.is_empty()
1183 {
1184 let _ = writeln!(s, "\n## Warnings ({})", arr.len());
1185 for w in arr {
1186 let code = w.get("code").and_then(|x| x.as_str()).unwrap_or("");
1187 let msg = w.get("message").and_then(|x| x.as_str()).unwrap_or("");
1188 let _ = writeln!(s, "- [{code}] {msg}");
1189 }
1190 }
1191
1192 s
1193}
1194
1195fn render_count_map(s: &mut String, val: Option<&serde_json::Value>, title: &str) {
1199 use std::fmt::Write as _;
1200 let Some(map) = val.and_then(|x| x.as_object()) else {
1201 return;
1202 };
1203 if map.is_empty() {
1204 return;
1205 }
1206 let _ = writeln!(s, "- {title}:");
1207 for (k, n) in map {
1208 let label = if k.is_empty() {
1209 "(unpinned)"
1210 } else {
1211 k.as_str()
1212 };
1213 let _ = writeln!(s, " - {label}: {}", n.as_u64().unwrap_or(0));
1214 }
1215}
1216
1217fn summarize_health_item(item: &serde_json::Value) -> String {
1229 if let Some(id) = item.get("id").and_then(|x| x.as_str()) {
1230 match item.get("title").and_then(|x| x.as_str()) {
1231 Some(t) if !t.is_empty() => format!("{id} — {t}"),
1232 _ => id.to_string(),
1233 }
1234 } else if let Some(from) = item.get("from").and_then(|x| x.as_str()) {
1235 let target = item.get("target_id").and_then(|x| x.as_str()).unwrap_or("");
1236 match item.get("kind").and_then(|x| x.as_str()) {
1237 Some(kind) => format!("[{kind}] {from} → {target}"),
1238 None => format!("{from} → {target}"),
1239 }
1240 } else {
1241 serde_json::to_string(item).unwrap_or_default()
1242 }
1243}
1244
1245fn stale_row(e: &crate::ops::StaleEntity) -> serde_json::Value {
1250 let mut row = serde_json::json!({
1251 "id": e.id.to_string(),
1252 "title": e.title,
1253 "days_since_modified": e.days_since_modified,
1254 });
1255 if let Some(state) = &e.anchor_state {
1256 let obj = row.as_object_mut().unwrap();
1257 obj.insert("clock".into(), serde_json::json!("anchors"));
1258 obj.insert("anchor_state".into(), serde_json::json!(state));
1259 }
1260 row
1261}
1262
1263pub fn render_check_finding_line(entity: &str, f: &serde_json::Value) -> String {
1277 let code = f["finding"]["code"].as_str().unwrap_or("?");
1278 let section = f["finding"]["section"]
1279 .as_str()
1280 .map(|x| format!(" [{x}]"))
1281 .unwrap_or_default();
1282 let message = f["finding"]["message"].as_str().unwrap_or("");
1283 let third_party =
1288 f["origin"].as_str() == Some(crate::render::OriginClass::ThirdParty.as_wire());
1289 let by = f["identity"]
1290 .as_str()
1291 .map(|i| format!(" by `{i}`"))
1292 .unwrap_or_default();
1293 let (mark, message) = if third_party {
1294 (
1295 crate::render::QUOTE_LABEL,
1296 crate::render::quote_inline(message),
1297 )
1298 } else {
1299 ("", message.to_string())
1300 };
1301 format!(
1302 " - finding on `{entity}` ({} {}){by}{mark}: {code}{section} — {message}",
1303 f["kind"].as_str().unwrap_or("verification"),
1304 f["verdict"].as_str().unwrap_or("?"),
1305 )
1306}
1307
1308#[cfg(test)]
1309mod tests {
1310 use super::render_health_markdown;
1311 use serde_json::json;
1312
1313 fn base_payload() -> serde_json::Value {
1314 json!({
1315 "summary": { "total_entities": 1 },
1316 "total_nodes": 1,
1317 })
1318 }
1319
1320 #[test]
1327 fn body_observations_render_their_code_and_fate_not_just_an_id() {
1328 let mut v = base_payload();
1329 v["body_observations"] = json!([{
1330 "id": "specs--alpha",
1331 "code": "ABSORBED_SECTION",
1332 "fate": "absorbed",
1333 "detail": { "heading": "Rogue", "note": "survives the next write" },
1334 }, {
1335 "id": "specs--beta",
1336 "code": "UNDECLARED_METADATA_KEY",
1337 "fate": "dropped",
1338 "detail": { "key": "reviewer", "note": "the next write drops it" },
1339 }]);
1340 let md = render_health_markdown(&v);
1341 assert!(md.contains("## Body observations (2)"), "{md}");
1342 assert!(
1343 md.contains(
1344 "- specs--alpha [ABSORBED_SECTION] `Rogue`: absorbed (survives the next write)"
1345 ),
1346 "{md}"
1347 );
1348 assert!(
1349 md.contains(
1350 "- specs--beta [UNDECLARED_METADATA_KEY] `reviewer`: dropped \
1351 (the next write drops it)"
1352 ),
1353 "{md}"
1354 );
1355 assert!(!render_health_markdown(&base_payload()).contains("Body observations"));
1357 }
1358
1359 #[test]
1366 fn render_health_markdown_names_the_dangling_condition() {
1367 let mut v = base_payload();
1368 v["dangling_links"] = json!([
1369 {
1370 "kind": "DANGLING_LINK_TARGET_MISSING",
1371 "from": "specs--a", "target_id": "specs--gone",
1372 "target_path": "gone", "section": "purpose",
1373 },
1374 {
1375 "kind": "DANGLING_RELATION_TARGET_MISSING",
1376 "from": "specs--b", "target_id": "specs--vanished",
1377 "target_path": "vanished", "section": null,
1378 },
1379 ]);
1380 let md = render_health_markdown(&v);
1381 assert!(
1382 md.contains("[DANGLING_LINK_TARGET_MISSING] specs--a → specs--gone"),
1383 "{md}"
1384 );
1385 assert!(
1386 md.contains("[DANGLING_RELATION_TARGET_MISSING] specs--b → specs--vanished"),
1387 "{md}"
1388 );
1389 assert!(
1391 !md.contains("- specs--a → specs--gone"),
1392 "the unprefixed form is what fused them: {md}"
1393 );
1394 }
1395
1396 #[test]
1403 fn render_health_markdown_covers_checks_derivations_and_quarantine() {
1404 let mut v = base_payload();
1406 v["checks"] = json!({
1407 "specs": {
1408 "never_checked": 2, "checked_ok": 1,
1409 "check_failed": 0, "check_stale": 0,
1410 "conformance": {
1411 "never_checked": 3, "checked_ok": 0,
1412 "check_failed": 0, "check_stale": 0,
1413 },
1414 "independence": {
1415 "self_checked": { "count": 0, "items": [] },
1416 "confirmed_independent": { "count": 0, "items": [] },
1417 "unconfirmable": { "count": 1, "items": ["specs--a"] },
1418 },
1419 }
1420 });
1421 v["stale_derivations"] = json!({
1422 "specs": [{
1423 "source": "specs--a", "rel_type": "DERIVES_FROM",
1424 "target": "specs--b", "state": "stale",
1425 "baseline": "aaa", "current": "bbb",
1426 }]
1427 });
1428 v["quarantined"] = json!([{
1429 "mem": "broken",
1430 "reason_code": "SCHEMA_NOT_FOUND",
1431 "reason_message": "no schema; repair via memstead mem set-schema",
1432 }]);
1433 let md = render_health_markdown(&v);
1434 assert!(md.contains("## Checks (1 mems)"), "{md}");
1435 assert!(
1436 md.contains(
1437 "- `specs`: never_checked 2, checked_ok 1, check_failed 0, \
1438 check_stale 0; conformance: never_checked 3, checked_ok 0, \
1439 check_failed 0, check_stale 0; independence: self_checked 0, \
1440 confirmed_independent 0, unconfirmable 1"
1441 ),
1442 "{md}"
1443 );
1444 assert!(md.contains("## Stale derivations (1 findings)"), "{md}");
1445 assert!(
1446 md.contains("- `specs`: specs--a -[DERIVES_FROM]-> specs--b (stale)"),
1447 "{md}"
1448 );
1449 assert!(md.contains("## Quarantined mems (1)"), "{md}");
1450 assert!(
1451 md.contains(
1452 "- `broken` [SCHEMA_NOT_FOUND] no schema; repair via memstead mem set-schema"
1453 ),
1454 "{md}"
1455 );
1456
1457 let mut empty = base_payload();
1459 empty["checks"] = json!({});
1460 empty["stale_derivations"] = json!({ "specs": [] });
1461 let md = render_health_markdown(&empty);
1462 assert!(md.contains("## Checks (0 mems)"), "{md}");
1463 assert!(md.contains("## Stale derivations (0 findings)"), "{md}");
1464
1465 let base_md = render_health_markdown(&base_payload());
1468 for heading in ["## Checks", "## Stale derivations", "## Quarantined mems"] {
1469 assert!(
1470 !base_md.contains(heading),
1471 "absent key must render nothing: {base_md}"
1472 );
1473 }
1474 let appended = render_health_markdown(&v);
1475 assert!(
1476 appended.starts_with(&base_md),
1477 "sections append; the base output stays byte-identical"
1478 );
1479 }
1480}