Skip to main content

memstead_base/ops/
health_compose.rs

1//! Shared health composer used by the `memstead_health` MCP tool and any
2//! non-MCP caller (CLI, a future HTTP surface).
3//!
4//! Lifted from `memstead-mcp/src/server.rs::memstead_health_unified` so the
5//! health read-envelope is produced by one transport-neutral builder with no
6//! rmcp type in the path — the MCP wrapper handles drift collection, the
7//! schema anchor, the `mem_changed` notice channel, and `CallToolResult`
8//! wrapping; none of that lives here.
9//!
10//! The composer returns the complete health payload as a `serde_json::Value`
11//! (warnings embedded, every `include` detail section applied). Surface state
12//! the engine does not own — the `[mutations]` posture and the opaque
13//! `[plugin.*]` map — is passed in via [`HealthConfig`] as prebuilt JSON so
14//! this crate stays free of the MCP server's config types and the wire bytes
15//! stay identical to the pre-lift handler.
16
17use std::collections::HashMap;
18
19/// Composer input — packed from the MCP `HealthParams` (or a CLI `Args`) at
20/// the call site. Mirrors the field set the pre-lift handler read off
21/// `HealthParams`.
22#[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    /// The referee: evaluate [`crate::ops::strict::STRICT_INCLUDES`]
30    /// whatever `include` says, and serve the `strict` axis (entity
31    /// findings with their acknowledgements, configuration defects,
32    /// stale acknowledgements, the violation count the exit turns on).
33    pub strict: bool,
34    /// The date the `due` axis reads "today" as (`YYYY-MM-DD`); `None`
35    /// reads the engine clock. A testing hook, the same one `memstead due
36    /// --today` exposes, so a recorded rendering can pin the day.
37    pub today: Option<&'a str>,
38}
39
40/// Surface-owned config the engine does not carry — supplied prebuilt so the
41/// composer inserts the bytes verbatim. `mutations` is `{"require_notes": …}`;
42/// `plugin` is the opaque `[plugin.*]` pass-through object. Only consulted
43/// when `args.include_config` is set.
44#[derive(Debug, Clone)]
45pub struct HealthConfig {
46    pub mutations: serde_json::Value,
47    pub plugin: serde_json::Value,
48}
49
50/// Typed input failures the composer surfaces. The MCP wrapper maps each
51/// variant to its existing envelope (`UNKNOWN_MEM`, `INVALID_INPUT`) and
52/// the engine fault to its typed translator, so the wire `code` stays put.
53// The engine-fault variant carries the lower-layer error verbatim so the typed
54// translator keeps its input; the size gap is inherent to that lifting, and a
55// health composition runs once per call.
56#[allow(clippy::large_enum_variant)]
57#[derive(Debug, thiserror::Error)]
58pub enum ComposeHealthError {
59    /// `args.mem` names a mem that isn't writable in this workspace. The
60    /// composer surfaces the sorted writable roster so the wrapper can echo
61    /// it in the `UNKNOWN_MEM` envelope.
62    #[error("unknown mem: \"{name}\"")]
63    UnknownMem {
64        name: String,
65        writable_mems: Vec<String>,
66    },
67    /// `args.mem` names a QUARANTINED mem — the scope refuses with the
68    /// typed quarantine reason rather than reporting the mem unknown
69    ///. The wrapper maps it through its ordinary
70    /// engine-error path via `Engine::unknown_mem_error`.
71    #[error("mem \"{0}\" is quarantined")]
72    MemQuarantined(String),
73    /// `args.target_schema` did not parse as a `name@x.y.z` ref. `reason` is
74    /// the parser's message, surfaced verbatim in the `INVALID_INPUT`
75    /// envelope's `details.reason`.
76    #[error("invalid target_schema {raw:?}: {reason}")]
77    InvalidTargetSchema { raw: String, reason: String },
78    /// A backend fault from the conformance / consistency scan. The wrapper
79    /// routes it through the typed `EngineError` translator unchanged.
80    #[error(transparent)]
81    Engine(#[from] crate::EngineError),
82}
83
84/// Build the complete health payload. `drift_warnings` are the reload warnings
85/// the wrapper collected before calling in; the composer extends them with the
86/// health report's own warnings, the limit-clamp notice, and unknown-include
87/// notices, then embeds the lot under `warnings`.
88pub 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    // Strict evaluates the referee's set whatever the caller included:
97    // the union keeps every explicit include and adds the strict ones.
98    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    // Mem filter validation — only writable mems accepted.
136    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    // Symmetric with the data filter below, and the one rule every warning
159    // follows under a filter: `WarningHint::concerns_mem` keeps a warning
160    // attributed to the scoped mem (or naming it among several), drops one
161    // attributed to another mem, and keeps a warning attributed to no mem
162    // at all (OUTER_REPO_…, UNKNOWN_INCLUDE_KEY, LIMIT_CLAMPED: workspace-
163    // or request-scoped, so they concern every mem, this one included).
164    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    // Under a `mem` filter, scope the community count to clusters with ≥1
204    // member in that mem (filtering the global partition, not re-running
205    // detection) so it can't contradict the scoped `total_entities` — e.g. an
206    // empty mem reports 0 entities and 0 communities. Mirrors
207    // `memstead_overview` via the shared helper.
208    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    // Edge counts: under a mem filter, count only source-in-mem edges
216    // (asymmetric — matches the legacy contract).
217    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            // Name order (A7 AC3): the lists are byte-stable across runs.
234            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            // `Status.edge_types` is a `BTreeMap`: already in name order.
243            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    // The stable default an omitted-`mem` mutation lands in — the first
280    // writable mount in declaration order, not `writable_mems[0]` of this
281    // alphabetically-sorted roster. Surfaced so an omitted-`mem` write is
282    // predictable.
283    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    // Per-mem schema pins. Source from `engine.mount(name).schema` which
299    // carries the pinned `SchemaRef`; render via `as_display()` to get the
300    // same `name@version` form full emits.
301    //
302    // Every *visible* mem appears — writable and read-only alike — each
303    // carrying an explicit `writable` attribute. A read-only mount's pinned
304    // schema is real; surfacing it here (rather than filtering to writable
305    // mems) is what keeps health from reporting "no schema" while the
306    // discovery manifest names one. Writable mems render first (sorted),
307    // then read-only ones (sorted), so a normal writable workspace — which
308    // has no read mems — keeps its existing entry order, gaining only the
309    // `writable: true` attribute.
310    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                // The mem's *settled* pin — `Mount.schema` (now an optional
321                // assertion). During a dual-pin migration this stays the
322                // settled pin; the in-flight target is the separate
323                // `migration_target` surface below.
324                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                // Dual-pin confirmation surface: present only while a
335                // migration is in flight, so settled mems' entries stay
336                // byte-identical to before.
337                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    // #49: segment the orphan / community headlines by the owning mem's
347    // schema. A blended total mixes schemas with opposite norms — ingest
348    // mems, where each finding is an isolated entity (orphan by design),
349    // versus code/spec mems, where an orphan is real debt — so a bare
350    // "54 orphans" reads as 54 units of debt when most are by-design
351    // isolates. The raw `total_orphans` / `total_communities` are retained
352    // in `summary`, and a `mem`-scoped call still exposes per-mem counts
353    // (the refusal AC); these maps only attribute the totals by schema.
354    // `orphan_ids` is already mem-scoped above; scope the community
355    // attribution to the same mem set.
356    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        // The coverage rule (crate::ops::coverage): the axes
370        // this report's defect statement answers for, stamped by the
371        // composer itself so every consumer of the composition
372        // carries the same declaration.
373        // Rendered is not examined (C10, 2026-09-03). `anchors` used to be
374        // promoted into the examined set for any pass that included it, on a
375        // "rendered this pass, therefore examined" rule whose only instance
376        // this was. But `--strict` fails on an unreadable anchors sidecar
377        // alone and never on drift, and its help says drifted anchors stay
378        // advisory, so the promoted line told a gate that the health verdict
379        // polices anchor drift when the verify surfaces do. The line now
380        // renders straight from the registry, which already declares
381        // `anchors` advisory with that reason.
382        // The four include-gated verdict axes are examined on the pass that
383        // included them (a `--strict` pass includes each) and named not
384        // examined otherwise: a default report never computed them.
385        "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    // The schema anchor every mem-scoped read carries (`_mem_schema`),
417    // set by the composer so the CLI and the MCP tool render the same
418    // bytes; the MCP wrapper's own anchor step re-inserts the same value.
419    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    // Quarantine roster — a boot-honesty fact, present whenever
428    // non-empty, never behind an include gate.
429    if !health.quarantined.is_empty() {
430        obj.insert(
431            "quarantined".into(),
432            serde_json::to_value(&health.quarantined).unwrap_or_default(),
433        );
434    }
435    // Per-file load failures — same boot-honesty class: each entry's
436    // message names the remedy (the merge-conflict refusal names
437    // `memstead conflicts resolve`), so the composed report must carry
438    // them for the failure mode to name its door.
439    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    // Leaf populations — visible beside the orphan axis they exempt
449    //; omitted when no type declares leaf.
450    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        // `typed_*` is the dependency degree (excludes auto-emitted mention
485        // edges); the list is ranked by it so a co-mention hub doesn't
486        // outrank a real dependency hub. `total`/`incoming`/`outgoing` keep
487        // the mentions and stay available — mention degree = total - typed.
488        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            // Source-in-mem scoping, to match this response's `edge_types`
506            // / `total_edges`. The node is in-mem, so all of its outgoing
507            // edges are source-in-mem and counted; an incoming edge counts
508            // only when its source is also in-mem, so a cross-mem edge
509            // the aggregate excluded does not inflate the node's degree here.
510            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                // `missing` (bare field names) stays byte-identical for
542                // existing consumers; the per-issue detail rides next
543                // to it so the projection carries WHICH condition each
544                // issue reports (a heading mismatch must never surface
545                // as "missing" only).
546                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        // Fresh by the anchor clock: only present when an anchor overruled
584        // the day threshold, so an anchor-less workspace renders unchanged.
585        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        // Declared aggregate signals above `none`, with per-level
630        // counts — the same composer the CLI and the
631        // MCP server serve.
632        obj.insert("signals".into(), engine.health_signals_axis(args.mem));
633    }
634    if include.iter().any(|s| s == "labelling") {
635        // Grounded labelling per declaring mem — counts per label,
636        // defeated/undecided lists with their attacker evidence, and
637        // the excluded cross-mem attack-edge count.
638        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        // The model-truth signals the remodel skill reads: counts
648        // and capped lists, never a verdict.
649        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        // The due brief as data (`Engine::due_brief`), over the default
656        // 90-day window from today: overdue entities with the days past,
657        // due-soon ones with the days until. A reading, never a verdict;
658        // a workspace where no schema declares a due axis serves the
659        // empty brief with `mems: []`.
660        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        // The friction ledger's read surface:
680        // counts per code / per verb over the workspace-local refusal
681        // ledger, whole-ledger plus a recent 24h window. A workspace
682        // without a root (in-memory boots) or without a ledger yet
683        // serves the empty summary — the axis never fails health.
684        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    // Conformance axis (`conformance`), or both axes (`integrity`). Findings
736    // ride one flat `findings` list in the pinned `{ id, axis, code, detail }`
737    // shape; ids are mem-qualified so the flat list stays unambiguous when
738    // unscoped. Mems scan in sorted order and each mem's findings are
739    // deterministic, so the whole list is.
740    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            // Beside `findings`, never among them: an observation says what an
770            // entity body silently loses, and none of it makes the entity
771            // unconformant.
772            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    // `include=["ledger"]` — a folder mem's ledger set against its file set
785    // (04/04, criteria 1 and 2). Reads only: no ledger line is written,
786    // rewritten or removed and no file is touched, because writing lines for
787    // edits the engine did not author would fabricate provenance for a change
788    // it cannot attribute. Git-branch mems are absent from the map rather than
789    // present and clean.
790    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    // Workspace policy surface — opt-in via `include_config: true`
802    // (the documented boolean alias) OR the catalogue key
803    // `include=["config"]`; both render the same projection, and
804    // passing both renders it once (a single gate). The rendering
805    // itself is shared with the CLI's `--include config` via
806    // `crate::ops::health::config_projection` — one
807    // implementation, every surface. `mutations` + `plugin` are passed
808    // in via [`HealthConfig`] (server-owned copies, inserted verbatim).
809    if args.include_config || include.iter().any(|s| s == "config") {
810        // Per-mem config entries follow the same scope as every other
811        // section: one mem under a filter, every writable mem without.
812        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    // The strict axis, read off the sections rendered above and the
828    // workspace check ledger. Last, so every section it reads is there.
829    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
843/// Render a composed health payload as a human-readable markdown report
844/// for the MCP text channel. `structured_content` remains the source of
845/// truth (this is never parsed back); the markdown exists so the text
846/// channel is *chunkable* like `memstead_overview` instead of a wall of
847/// JSON that overflows the response cap under several includes. The
848/// size-driving include arrays each render as their own section so the
849/// chunker can split a large report cleanly.
850pub 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    // Size-driving include arrays — one section each so chunking splits them.
887    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    // Body observations — their own section, not a row in the table above:
907    // `summarize_health_item` prints an entity id and stops, and an
908    // observation whose fate is not stated says nothing at all. This is the
909    // MCP text channel, so it is what a cold agent reads.
910    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    // Due axis — the due brief's rows, overdue first.
934    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    // Anchors axis — an object (mem → counts plus the population they cover),
978    // not an array, so it renders its own compact section. The figure and the
979    // population render together (consistency-sweep 03/05, criteria 1 and 3):
980    // this is the MCP text channel, so it is what a cold agent reads, and it
981    // used to print four numbers and stop.
982    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            // The figure prints through its type, from the row's own three
997            // fields: the count never appears apart from its population.
998            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    // Vital signs — per mem, the five model-truth signal counts;
1015    // the lists stay in the structured payload.
1016    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    // Checks axis — an object (mem → state counts + independence
1073    // gate). Null-is-a-statement (the Friction pattern): a requested
1074    // axis with no mems renders the explicit zero heading; an absent
1075    // key (not requested) renders nothing.
1076    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            // Foreign `x-` kinds by count and each entity's newest finding —
1113            // the same lines the CLI text surface prints, so the two
1114            // renderers say the same thing.
1115            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    // Stale-derivations axis — an object (mem → findings list). Same
1144    // requested-vs-absent contract as the checks axis above.
1145    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    // Quarantine roster — ungated in the JSON (present whenever
1166    // non-empty), so the text channel renders it whenever present:
1167    // per mem the reason code plus the message, which carries the
1168    // repair command.
1169    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
1198/// Render a `{ key: count }` map as an indented sub-list under `title`,
1199/// skipping an empty/missing map. The empty-string schema key (an unpinned
1200/// mem) renders as `(unpinned)`.
1201fn 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
1220/// One-line summary of a health detail item: prefer `id` (+ `title`),
1221/// else a dangling reference as `[kind] from → target_id`, else the
1222/// compact JSON.
1223///
1224/// The `kind` prefix matters because this is the health TEXT channel —
1225/// what an agent reads once the JSON exceeds `token_budget`, or whenever
1226/// it passes `chunk`. Without it the three dangling conditions, which
1227/// have three different repairs, render as one identical line shape and
1228/// the reader is back to the fused report the codes were split to end
1229/// (04/06, criteria 2 and 4). Mirrors `overview.rs`'s rendered section
1230/// and the CLI's markdown block.
1231fn 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
1248/// One stale-axis row. A row the day threshold produced carries the three
1249/// historical keys and nothing else (the anchor-less render is byte for
1250/// byte what it was); a row the anchor clock produced adds `clock:
1251/// "anchors"` and the `anchor_state` that made it.
1252fn 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    /// The description advertises `body_observations` on the conformance
1279    /// axis, and a description is not a shipped field: the drift gate
1280    /// compares description tokens against an allowlist, so it stayed green
1281    /// while no server emitted the key at all (grade, 2026-08-27). This
1282    /// pins the text channel end of it; the JSON end is pinned by the
1283    /// handler test in `ops::integrity`.
1284    #[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        // Absent key renders nothing at all.
1314        assert!(!render_health_markdown(&base_payload()).contains("Body observations"));
1315    }
1316
1317    /// 04/06, criteria 2 and 4: the text channel names the condition.
1318    /// This is the surface an agent gets once the JSON exceeds
1319    /// `token_budget`, and it rendered all three dangling conditions as
1320    /// one indistinguishable `from → target` line while every other
1321    /// surface had been migrated — the last place the fused report
1322    /// survived.
1323    #[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        // The two conditions do not render as the same line shape.
1348        assert!(
1349            !md.contains("- specs--a → specs--gone"),
1350            "the unprefixed form is what fused them: {md}"
1351        );
1352    }
1353
1354    /// Text-channel parity: the `checks` / `stale_derivations` axes
1355    /// and the quarantine roster render their own sections — content
1356    /// when populated, the explicit zero statement when requested but
1357    /// empty (null is a statement), and NOTHING when the JSON key is
1358    /// absent: a payload without the keys renders byte-identically to
1359    /// itself with sections appended, never mutated.
1360    #[test]
1361    fn render_health_markdown_covers_checks_derivations_and_quarantine() {
1362        // Populated.
1363        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        // Requested but empty → the explicit zero statement.
1416        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        // Keys absent (not requested) → byte-unchanged: no section,
1424        // and the populated render is the base render plus appendix.
1425        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}