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; `loop_warnings` are the
86/// maintenance loop's contribution (the unanchored-mention findings its
87/// verify passes recorded), handed in as data the composer never
88/// interprets and placed where the engine's own report used to carry them;
89/// the composer extends the lot with the health report's own warnings, the
90/// limit-clamp notice, and unknown-include notices, then embeds it under
91/// `warnings`. Every surface reaches this through the loop's one assembly,
92/// `memstead_projection::health::compose_health`, so no surface can forget the
93/// loop's axis.
94pub 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    // Strict evaluates the referee's set whatever the caller included:
104    // the union keeps every explicit include and adds the strict ones.
105    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    // Mem filter validation — only writable mems accepted.
144    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    // Symmetric with the data filter below, and the one rule every warning
167    // follows under a filter: `WarningHint::concerns_mem` keeps a warning
168    // attributed to the scoped mem (or naming it among several), drops one
169    // attributed to another mem, and keeps a warning attributed to no mem
170    // at all (OUTER_REPO_…, UNKNOWN_INCLUDE_KEY, LIMIT_CLAMPED: workspace-
171    // or request-scoped, so they concern every mem, this one included).
172    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    // Under a `mem` filter, scope the community count to clusters with ≥1
212    // member in that mem (filtering the global partition, not re-running
213    // detection) so it can't contradict the scoped `total_entities` — e.g. an
214    // empty mem reports 0 entities and 0 communities. Mirrors
215    // `memstead_overview` via the shared helper.
216    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    // Edge counts: under a mem filter, count only source-in-mem edges
224    // (asymmetric — matches the legacy contract).
225    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            // Name order: the lists are byte-stable across runs.
242            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            // `Status.edge_types` is a `BTreeMap`: already in name order.
251            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    // The stable default an omitted-`mem` mutation lands in — the first
288    // writable mount in declaration order, not `writable_mems[0]` of this
289    // alphabetically-sorted roster. Surfaced so an omitted-`mem` write is
290    // predictable.
291    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    // Per-mem schema pins. Source from `engine.mount(name).schema` which
307    // carries the pinned `SchemaRef`; render via `as_display()` to get the
308    // same `name@version` form full emits.
309    //
310    // Every *visible* mem appears — writable and read-only alike — each
311    // carrying an explicit `writable` attribute. A read-only mount's pinned
312    // schema is real; surfacing it here (rather than filtering to writable
313    // mems) is what keeps health from reporting "no schema" while the
314    // discovery manifest names one. Writable mems render first (sorted),
315    // then read-only ones (sorted), so a normal writable workspace — which
316    // has no read mems — keeps its existing entry order, gaining only the
317    // `writable: true` attribute.
318    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                // The mem's *settled* pin — `Mount.schema` (now an optional
329                // assertion). During a dual-pin migration this stays the
330                // settled pin; the in-flight target is the separate
331                // `migration_target` surface below.
332                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                // Dual-pin confirmation surface: present only while a
343                // migration is in flight, so settled mems' entries stay
344                // byte-identical to before.
345                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    // #49: segment the orphan / community headlines by the owning mem's
355    // schema. A blended total mixes schemas with opposite norms — ingest
356    // mems, where each finding is an isolated entity (orphan by design),
357    // versus code/spec mems, where an orphan is real debt — so a bare
358    // "54 orphans" reads as 54 units of debt when most are by-design
359    // isolates. The raw `total_orphans` / `total_communities` are retained
360    // in `summary`, and a `mem`-scoped call still exposes per-mem counts
361    // (the refusal AC); these maps only attribute the totals by schema.
362    // `orphan_ids` is already mem-scoped above; scope the community
363    // attribution to the same mem set.
364    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        // The coverage rule (crate::ops::coverage): the axes
378        // this report's defect statement answers for, stamped by the
379        // composer itself so every consumer of the composition
380        // carries the same declaration.
381        // Rendered is not examined. `anchors` used to be
382        // promoted into the examined set for any pass that included it, on a
383        // "rendered this pass, therefore examined" rule whose only instance
384        // this was. But `--strict` fails on an unreadable anchors sidecar
385        // alone and never on drift, and its help says drifted anchors stay
386        // advisory, so the promoted line told a gate that the health verdict
387        // polices anchor drift when the verify surfaces do. The line now
388        // renders straight from the registry, which already declares
389        // `anchors` advisory with that reason.
390        // The four include-gated verdict axes are examined on the pass that
391        // included them (a `--strict` pass includes each) and named not
392        // examined otherwise: a default report never computed them.
393        "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    // The schema anchor every mem-scoped read carries (`_mem_schema`),
425    // set by the composer so the CLI and the MCP tool render the same
426    // bytes; the MCP wrapper's own anchor step re-inserts the same value.
427    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    // Quarantine roster — a boot-honesty fact, present whenever
436    // non-empty, never behind an include gate.
437    if !health.quarantined.is_empty() {
438        obj.insert(
439            "quarantined".into(),
440            serde_json::to_value(&health.quarantined).unwrap_or_default(),
441        );
442    }
443    // Per-file load failures — same boot-honesty class: each entry's
444    // message names the remedy (the merge-conflict refusal names
445    // `memstead conflicts resolve`), so the composed report must carry
446    // them for the failure mode to name its door.
447    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    // Leaf populations — visible beside the orphan axis they exempt;
457    // omitted when no type declares leaf.
458    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        // `typed_*` is the dependency degree (excludes auto-emitted mention
493        // edges); the list is ranked by it so a co-mention hub doesn't
494        // outrank a real dependency hub. `total`/`incoming`/`outgoing` keep
495        // the mentions and stay available — mention degree = total - typed.
496        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            // Source-in-mem scoping, to match this response's `edge_types`
514            // / `total_edges`. The node is in-mem, so all of its outgoing
515            // edges are source-in-mem and counted; an incoming edge counts
516            // only when its source is also in-mem, so a cross-mem edge
517            // the aggregate excluded does not inflate the node's degree here.
518            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                // `missing` (bare field names) stays byte-identical for
550                // existing consumers; the per-issue detail rides next
551                // to it so the projection carries WHICH condition each
552                // issue reports (a heading mismatch must never surface
553                // as "missing" only).
554                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        // Fresh by the anchor clock: only present when an anchor overruled
592        // the day threshold, so an anchor-less workspace renders unchanged.
593        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        // Declared aggregate signals above `none`, with per-level
638        // counts — the same composer the CLI and the
639        // MCP server serve.
640        obj.insert("signals".into(), engine.health_signals_axis(args.mem));
641    }
642    if include.iter().any(|s| s == "labelling") {
643        // Grounded labelling per declaring mem — counts per label,
644        // defeated/undecided lists with their attacker evidence, and
645        // the excluded cross-mem attack-edge count.
646        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        // The model-truth signals the remodel skill reads: counts
656        // and capped lists, never a verdict.
657        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        // The due brief as data (`Engine::due_brief`), over the default
664        // 90-day window from today: overdue entities with the days past,
665        // due-soon ones with the days until. A reading, never a verdict;
666        // a workspace where no schema declares a due axis serves the
667        // empty brief with `mems: []`.
668        let today = match args.today {
669            Some(t) => t.to_string(),
670            None => match crate::ops::health::pinned_today() {
671                Some(pinned) => pinned,
672                None => {
673                    let now = engine.now_iso();
674                    now.get(..10).unwrap_or(&now).to_string()
675                }
676            },
677        };
678        let brief = engine
679            .due_brief(&today, &crate::engine::due::DueWindow::Days(90), vf)
680            .map_err(|e| ComposeHealthError::InvalidTargetSchema {
681                raw: today.clone(),
682                reason: e,
683            })?;
684        obj.insert(
685            "due".into(),
686            serde_json::to_value(&brief).unwrap_or_default(),
687        );
688    }
689    if include.iter().any(|s| s == "friction") {
690        // The friction ledger's read surface:
691        // counts per code / per verb over the workspace-local refusal
692        // ledger, whole-ledger plus a recent 24h window. A workspace
693        // without a root (in-memory boots) or without a ledger yet
694        // serves the empty summary — the axis never fails health.
695        let summary = match engine.workspace_root() {
696            Some(root) => crate::friction::FrictionLedger::for_workspace(root).summarize(),
697            None => serde_json::json!({
698                "total": 0,
699                "by_code": {},
700                "by_verb": {},
701                "recent_24h": { "total": 0, "by_code": {} },
702                "ledger_bytes": 0,
703            }),
704        };
705        obj.insert("friction".into(), summary);
706    }
707    if include.iter().any(|s| s == "missing_required_outgoing") {
708        let reports = engine.missing_required_outgoing(vf);
709        let arr: Vec<serde_json::Value> = reports
710            .into_iter()
711            .map(|r| serde_json::to_value(&r).unwrap())
712            .collect();
713        obj.insert("missing_required_outgoing".into(), serde_json::json!(arr));
714    }
715    if include.iter().any(|s| s == "constraints") {
716        let reports = engine.constraint_findings(vf);
717        let arr: Vec<serde_json::Value> = reports
718            .into_iter()
719            .map(|r| serde_json::to_value(&r).unwrap())
720            .collect();
721        obj.insert("constraints".into(), serde_json::json!(arr));
722        let defects = engine.schema_format_defects();
723        if !defects.is_empty() {
724            obj.insert(
725                "schema_format_defects".into(),
726                serde_json::to_value(&defects).unwrap(),
727            );
728        }
729    }
730    if include.iter().any(|s| s == "tags") {
731        let (distribution, folded, untagged) =
732            crate::ops::health::collect_tag_distribution(engine.store(), vf, limit);
733        obj.insert(
734            "tag_distribution".into(),
735            serde_json::to_value(&distribution).unwrap(),
736        );
737        obj.insert(
738            "tag_distribution_folded".into(),
739            serde_json::to_value(&folded).unwrap(),
740        );
741        obj.insert(
742            "untagged_entities".into(),
743            serde_json::to_value(&untagged).unwrap(),
744        );
745    }
746    // Conformance axis (`conformance`), or both axes (`integrity`). Findings
747    // ride one flat `findings` list in the pinned `{ id, axis, code, detail }`
748    // shape; ids are mem-qualified so the flat list stays unambiguous when
749    // unscoped. Mems scan in sorted order and each mem's findings are
750    // deterministic, so the whole list is.
751    let wants_conformance = include
752        .iter()
753        .any(|s| s == "conformance" || s == "integrity");
754    if wants_conformance {
755        let wants_consistency = include.iter().any(|s| s == "integrity");
756        let target: Option<memstead_schema::SchemaRef> = match args.target_schema {
757            None => None,
758            Some(raw) => match raw.parse::<memstead_schema::SchemaRef>() {
759                Ok(r) => Some(r),
760                Err(reason) => {
761                    return Err(ComposeHealthError::InvalidTargetSchema {
762                        raw: raw.to_string(),
763                        reason,
764                    });
765                }
766            },
767        };
768        let scan_mems: Vec<String> = match vf {
769            Some(v) => vec![v.to_string()],
770            None => {
771                let mut all = writable_mems.clone();
772                all.sort();
773                all
774            }
775        };
776        let mut findings = Vec::new();
777        let mut observations = Vec::new();
778        for v in &scan_mems {
779            findings.extend(engine.conformance_findings(v, target.as_ref())?);
780            // Beside `findings`, never among them: an observation says what an
781            // entity body silently loses, and none of it makes the entity
782            // unconformant.
783            observations.extend(engine.body_observations(v, target.as_ref())?);
784            if wants_consistency {
785                findings.extend(engine.consistency_findings(v)?);
786            }
787        }
788        obj.insert("findings".into(), serde_json::to_value(&findings).unwrap());
789        obj.insert(
790            "body_observations".into(),
791            serde_json::to_value(&observations).unwrap(),
792        );
793    }
794
795    // `include=["ledger"]` — a folder mem's ledger set against its file set.
796    // Reads only: no ledger line is written,
797    // rewritten or removed and no file is touched, because writing lines for
798    // edits the engine did not author would fabricate provenance for a change
799    // it cannot attribute. Git-branch mems are absent from the map rather than
800    // present and clean.
801    if include.iter().any(|s| s == "ledger") {
802        let mut ledger = engine.ledger_reconciliation();
803        if let Some(v) = vf {
804            ledger.retain(|mem, _| mem == v);
805        }
806        obj.insert(
807            "ledger".into(),
808            serde_json::to_value(ledger).unwrap_or_default(),
809        );
810    }
811
812    // Workspace policy surface — opt-in via `include_config: true`
813    // (the documented boolean alias) OR the catalogue key
814    // `include=["config"]`; both render the same projection, and
815    // passing both renders it once (a single gate). The rendering
816    // itself is shared with the CLI's `--include config` via
817    // `crate::ops::health::config_projection` — one
818    // implementation, every surface. `mutations` + `plugin` are passed
819    // in via [`HealthConfig`] (server-owned copies, inserted verbatim).
820    if args.include_config || include.iter().any(|s| s == "config") {
821        // Per-mem config entries follow the same scope as every other
822        // section: one mem under a filter, every writable mem without.
823        let config_mems: Vec<String> = match vf {
824            Some(v) => writable_mems.iter().filter(|m| *m == v).cloned().collect(),
825            None => writable_mems.clone(),
826        };
827        let entries = crate::ops::health::config_projection(
828            engine,
829            &config_mems,
830            config.mutations.clone(),
831            config.plugin.clone(),
832        );
833        for (k, v) in entries {
834            obj.insert(k, v);
835        }
836    }
837
838    // The strict axis, read off the sections rendered above and the
839    // workspace check ledger. Last, so every section it reads is there.
840    if args.strict {
841        let ledger = engine
842            .workspace_root()
843            .map(crate::check::CheckLedger::for_workspace);
844        let axis = crate::ops::strict::compose_strict_axis(obj, ledger.as_ref(), vf);
845        obj.insert(
846            "strict".into(),
847            serde_json::to_value(&axis).unwrap_or_default(),
848        );
849    }
850
851    Ok(result)
852}
853
854/// Render a composed health payload as a human-readable markdown report
855/// for the MCP text channel. `structured_content` remains the source of
856/// truth (this is never parsed back); the markdown exists so the text
857/// channel is *chunkable* like `memstead_overview` instead of a wall of
858/// JSON that overflows the response cap under several includes. The
859/// size-driving include arrays each render as their own section so the
860/// chunker can split a large report cleanly.
861pub fn render_health_markdown(v: &serde_json::Value) -> String {
862    use std::fmt::Write as _;
863    let mut s = String::new();
864    let _ = writeln!(s, "# Graph health");
865    if let Some(mem) = v.get("mem").and_then(|x| x.as_str()) {
866        let _ = writeln!(s, "\nMem filter: `{mem}`");
867    }
868
869    if let Some(sum) = v.get("summary").and_then(|x| x.as_object()) {
870        let _ = writeln!(s, "\n## Summary");
871        for key in [
872            "total_entities",
873            "total_orphans",
874            "total_stubs",
875            "total_stale",
876            "total_missing_fields",
877            "total_communities",
878        ] {
879            if let Some(n) = sum.get(key).and_then(|x| x.as_u64()) {
880                let _ = writeln!(s, "- {}: {n}", key.replace('_', " "));
881            }
882        }
883        render_count_map(&mut s, sum.get("orphans_by_schema"), "Orphans by schema");
884        render_count_map(
885            &mut s,
886            sum.get("communities_by_schema"),
887            "Communities by schema",
888        );
889    }
890
891    for key in ["total_nodes", "real_nodes", "stub_nodes", "total_edges"] {
892        if let Some(n) = v.get(key).and_then(|x| x.as_u64()) {
893            let _ = writeln!(s, "- {}: {n}", key.replace('_', " "));
894        }
895    }
896
897    // Size-driving include arrays — one section each so chunking splits them.
898    for (key, title) in [
899        ("orphans", "Orphans"),
900        ("stubs", "Stubs"),
901        ("most_connected", "Most connected"),
902        ("missing_fields", "Missing fields"),
903        ("stale", "Stale"),
904        ("dangling_links", "Dangling links"),
905        ("missing_required_outgoing", "Missing required outgoing"),
906        ("constraints", "Constraint violations"),
907        ("findings", "Findings"),
908    ] {
909        if let Some(arr) = v.get(key).and_then(|x| x.as_array()) {
910            let _ = writeln!(s, "\n## {title} ({})", arr.len());
911            for item in arr {
912                let _ = writeln!(s, "- {}", summarize_health_item(item));
913            }
914        }
915    }
916
917    // Body observations — their own section, not a row in the table above:
918    // `summarize_health_item` prints an entity id and stops, and an
919    // observation whose fate is not stated says nothing at all. This is the
920    // MCP text channel, so it is what a cold agent reads.
921    if let Some(arr) = v.get("body_observations").and_then(|x| x.as_array()) {
922        let _ = writeln!(s, "\n## Body observations ({})", arr.len());
923        for item in arr {
924            let detail = &item["detail"];
925            let subject = detail
926                .get("heading")
927                .or_else(|| detail.get("key"))
928                .and_then(|x| x.as_str())
929                .unwrap_or("");
930            let _ = writeln!(
931                s,
932                "- {} [{}] `{subject}`: {} ({})",
933                item["id"].as_str().unwrap_or(""),
934                item["code"].as_str().unwrap_or(""),
935                item["fate"].as_str().unwrap_or(""),
936                detail
937                    .get("note")
938                    .and_then(|x| x.as_str())
939                    .unwrap_or("no note"),
940            );
941        }
942    }
943
944    // Due axis — the due brief's rows, overdue first.
945    if let Some(due) = v.get("due").and_then(|x| x.as_object()) {
946        let rows = |key: &str| -> Vec<&serde_json::Value> {
947            due.get(key)
948                .and_then(|x| x.as_array())
949                .map(|a| a.iter().collect())
950                .unwrap_or_default()
951        };
952        let overdue = rows("overdue");
953        let soon = rows("due_soon");
954        let now = rows("due_now");
955        let _ = writeln!(
956            s,
957            "\n## Due ({} overdue, {} due soon{}; today {}, through {})",
958            overdue.len(),
959            soon.len(),
960            if now.is_empty() {
961                String::new()
962            } else {
963                format!(", {} due now", now.len())
964            },
965            due.get("today").and_then(|x| x.as_str()).unwrap_or("?"),
966            due.get("through").and_then(|x| x.as_str()).unwrap_or("?"),
967        );
968        for r in now {
969            let _ = writeln!(
970                s,
971                "- `{}` — {} — **due now**: no confirming `{}` check ({}) (status: {}, mem: {})",
972                r["id"].as_str().unwrap_or(""),
973                r["title"].as_str().unwrap_or(""),
974                r["check_kind"].as_str().unwrap_or(""),
975                r["standing"].as_str().unwrap_or(""),
976                r["status"].as_str().unwrap_or(""),
977                r["mem"].as_str().unwrap_or(""),
978            );
979        }
980        for r in overdue {
981            let _ = writeln!(
982                s,
983                "- `{}` — {} — **{}** OVERDUE ({} days past) (status: {}, mem: {})",
984                r["id"].as_str().unwrap_or(""),
985                r["title"].as_str().unwrap_or(""),
986                r["date"].as_str().unwrap_or(""),
987                r["days_past"].as_u64().unwrap_or(0),
988                r["status"].as_str().unwrap_or(""),
989                r["mem"].as_str().unwrap_or(""),
990            );
991        }
992        for r in soon {
993            let _ = writeln!(
994                s,
995                "- `{}` — {} — **{}** (in {} days) (status: {}, mem: {})",
996                r["id"].as_str().unwrap_or(""),
997                r["title"].as_str().unwrap_or(""),
998                r["date"].as_str().unwrap_or(""),
999                r["days_until"].as_u64().unwrap_or(0),
1000                r["status"].as_str().unwrap_or(""),
1001                r["mem"].as_str().unwrap_or(""),
1002            );
1003        }
1004    }
1005
1006    // Anchors axis — an object (mem → counts plus the population they cover),
1007    // not an array, so it renders its own compact section. The figure and the
1008    // population render together:
1009    // this is the MCP text channel, so it is what a cold agent reads, and it
1010    // used to print four numbers and stop.
1011    if let Some(obj) = v.get("anchors").and_then(|x| x.as_object()) {
1012        let _ = writeln!(s, "\n## Anchors ({} mems)", obj.len());
1013        for (mem, counts) in obj {
1014            if let Some(c) = counts.get("condition").filter(|c| !c.is_null()) {
1015                let _ = writeln!(
1016                    s,
1017                    "- `{mem}`: ANCHORS_SIDECAR_UNREADABLE — {} — {}",
1018                    c["reason"].as_str().unwrap_or("reason not stated"),
1019                    counts["population"]
1020                        .as_str()
1021                        .unwrap_or("population not stated"),
1022                );
1023                continue;
1024            }
1025            // The figure prints through its type, from the row's own three
1026            // fields: the count never appears apart from its population.
1027            let figure = crate::anchor::AnchorResolutionFigure::from_json(counts)
1028                .map(|f| f.to_string())
1029                .unwrap_or_else(|| "resolution figure not stated with its population".to_string());
1030            let _ = writeln!(
1031                s,
1032                "- `{mem}`: resolves {figure}; drifted {}, recheck {}, unresolvable (artifact \
1033                 gone) {}, unobserved (not measured) {}, dangling (entity gone) {}",
1034                counts["drifted"].as_u64().unwrap_or(0),
1035                counts["recheck"].as_u64().unwrap_or(0),
1036                counts["unresolvable"].as_u64().unwrap_or(0),
1037                counts["unobserved"].as_u64().unwrap_or(0),
1038                counts["dangling"].as_u64().unwrap_or(0),
1039            );
1040        }
1041    }
1042
1043    // Vital signs — per mem, the five model-truth signal counts;
1044    // the lists stay in the structured payload.
1045    if let Some(obj) = v.get("vital_signs").and_then(|x| x.as_object()) {
1046        let mems: Vec<(&String, &serde_json::Value)> =
1047            obj.iter().filter(|(k, _)| *k != "_item_cap").collect();
1048        let _ = writeln!(s, "\n## Vital signs ({} mems)", mems.len());
1049        for (mem, sig) in mems {
1050            let count = |k: &str| sig[k]["count"].as_u64().unwrap_or(0);
1051            let share = match sig["type_share_by_community"]["status"].as_str() {
1052                Some("declared") => format!(
1053                    "last-resort type `{}` over {} communit{}",
1054                    sig["type_share_by_community"]["last_resort_type"]
1055                        .as_str()
1056                        .unwrap_or("?"),
1057                    count("type_share_by_community"),
1058                    if count("type_share_by_community") == 1 {
1059                        "y"
1060                    } else {
1061                        "ies"
1062                    }
1063                ),
1064                _ => "last-resort type not declared".to_string(),
1065            };
1066            let unclaimed = match sig["unclaimed_source_files"]["status"].as_str() {
1067                Some("enumerated") => format!(
1068                    "{} unclaimed source file(s)",
1069                    count("unclaimed_source_files")
1070                ),
1071                _ => "no bound source".to_string(),
1072            };
1073            let _ = writeln!(
1074                s,
1075                "- `{mem}`: {share}; {unclaimed}; {} contested unowned file(s); {} zero-outgoing \
1076                 entit{} in {} communit{}; {} empty declared section(s)",
1077                count("contested_unowned_files"),
1078                sig["zero_outgoing_entities"]["entities"]
1079                    .as_u64()
1080                    .unwrap_or(0),
1081                if sig["zero_outgoing_entities"]["entities"]
1082                    .as_u64()
1083                    .unwrap_or(0)
1084                    == 1
1085                {
1086                    "y"
1087                } else {
1088                    "ies"
1089                },
1090                count("zero_outgoing_entities"),
1091                if count("zero_outgoing_entities") == 1 {
1092                    "y"
1093                } else {
1094                    "ies"
1095                },
1096                count("empty_declared_sections"),
1097            );
1098        }
1099    }
1100
1101    // Checks axis — an object (mem → state counts + independence
1102    // gate). Null-is-a-statement (the Friction pattern): a requested
1103    // axis with no mems renders the explicit zero heading; an absent
1104    // key (not requested) renders nothing.
1105    if let Some(obj) = v.get("checks").and_then(|x| x.as_object()) {
1106        let _ = writeln!(s, "\n## Checks ({} mems)", obj.len());
1107        for (mem, c) in obj {
1108            let count = |key: &str| c.get(key).and_then(|x| x.as_u64()).unwrap_or(0);
1109            let conf = |key: &str| {
1110                c.get("conformance")
1111                    .and_then(|g| g.get(key))
1112                    .and_then(|x| x.as_u64())
1113                    .unwrap_or(0)
1114            };
1115            let gate = |key: &str| {
1116                c.get("independence")
1117                    .and_then(|g| g.get(key))
1118                    .and_then(|e| e.get("count"))
1119                    .and_then(|x| x.as_u64())
1120                    .unwrap_or(0)
1121            };
1122            let _ = writeln!(
1123                s,
1124                "- `{mem}`: never_checked {}, checked_ok {}, check_failed {}, \
1125                 check_stale {}; conformance: never_checked {}, \
1126                 checked_ok {}, check_failed {}, check_stale {}; \
1127                 independence: self_checked {}, \
1128                 confirmed_independent {}, unconfirmable {}",
1129                count("never_checked"),
1130                count("checked_ok"),
1131                count("check_failed"),
1132                count("check_stale"),
1133                conf("never_checked"),
1134                conf("checked_ok"),
1135                conf("check_failed"),
1136                conf("check_stale"),
1137                gate("self_checked"),
1138                gate("confirmed_independent"),
1139                gate("unconfirmable"),
1140            );
1141            // Foreign `x-` kinds by count and each entity's newest finding —
1142            // the same lines the CLI text surface prints, so the two
1143            // renderers say the same thing.
1144            if let Some(foreign) = c.get("foreign_kinds").and_then(|f| f.as_object())
1145                && !foreign.is_empty()
1146            {
1147                let listed: Vec<String> = foreign
1148                    .iter()
1149                    .map(|(k, n)| format!("{k} {}", n.as_u64().unwrap_or(0)))
1150                    .collect();
1151                let _ = writeln!(s, "  - foreign kinds: {}", listed.join(", "));
1152            }
1153            if let Some(findings) = c.get("findings").and_then(|f| f.as_object()) {
1154                for (entity, f) in findings {
1155                    let _ = writeln!(s, "{}", render_check_finding_line(entity, f));
1156                }
1157            }
1158        }
1159    }
1160
1161    // Stale-derivations axis — an object (mem → findings list). Same
1162    // requested-vs-absent contract as the checks axis above.
1163    if let Some(obj) = v.get("stale_derivations").and_then(|x| x.as_object()) {
1164        let total: usize = obj
1165            .values()
1166            .filter_map(|a| a.as_array().map(|a| a.len()))
1167            .sum();
1168        let _ = writeln!(s, "\n## Stale derivations ({total} findings)");
1169        for (mem, findings) in obj {
1170            for f in findings.as_array().into_iter().flatten() {
1171                let _ = writeln!(
1172                    s,
1173                    "- `{mem}`: {} -[{}]-> {} ({})",
1174                    f.get("source").and_then(|x| x.as_str()).unwrap_or(""),
1175                    f.get("rel_type").and_then(|x| x.as_str()).unwrap_or(""),
1176                    f.get("target").and_then(|x| x.as_str()).unwrap_or(""),
1177                    f.get("state").and_then(|x| x.as_str()).unwrap_or(""),
1178                );
1179            }
1180        }
1181    }
1182
1183    // Quarantine roster — ungated in the JSON (present whenever
1184    // non-empty), so the text channel renders it whenever present:
1185    // per mem the reason code plus the message, which carries the
1186    // repair command.
1187    if let Some(arr) = v.get("quarantined").and_then(|x| x.as_array()) {
1188        let _ = writeln!(s, "\n## Quarantined mems ({})", arr.len());
1189        for q in arr {
1190            let _ = writeln!(
1191                s,
1192                "- `{}` [{}] {}",
1193                q.get("mem").and_then(|x| x.as_str()).unwrap_or(""),
1194                q.get("reason_code").and_then(|x| x.as_str()).unwrap_or(""),
1195                q.get("reason_message")
1196                    .and_then(|x| x.as_str())
1197                    .unwrap_or(""),
1198            );
1199        }
1200    }
1201
1202    if let Some(arr) = v.get("warnings").and_then(|x| x.as_array())
1203        && !arr.is_empty()
1204    {
1205        let _ = writeln!(s, "\n## Warnings ({})", arr.len());
1206        for w in arr {
1207            let code = w.get("code").and_then(|x| x.as_str()).unwrap_or("");
1208            let msg = w.get("message").and_then(|x| x.as_str()).unwrap_or("");
1209            let _ = writeln!(s, "- [{code}] {msg}");
1210        }
1211    }
1212
1213    s
1214}
1215
1216/// Render a `{ key: count }` map as an indented sub-list under `title`,
1217/// skipping an empty/missing map. The empty-string schema key (an unpinned
1218/// mem) renders as `(unpinned)`.
1219fn render_count_map(s: &mut String, val: Option<&serde_json::Value>, title: &str) {
1220    use std::fmt::Write as _;
1221    let Some(map) = val.and_then(|x| x.as_object()) else {
1222        return;
1223    };
1224    if map.is_empty() {
1225        return;
1226    }
1227    let _ = writeln!(s, "- {title}:");
1228    for (k, n) in map {
1229        let label = if k.is_empty() {
1230            "(unpinned)"
1231        } else {
1232            k.as_str()
1233        };
1234        let _ = writeln!(s, "  - {label}: {}", n.as_u64().unwrap_or(0));
1235    }
1236}
1237
1238/// One-line summary of a health detail item: prefer `id` (+ `title`),
1239/// else a dangling reference as `[kind] from → target_id`, else the
1240/// compact JSON.
1241///
1242/// The `kind` prefix matters because this is the health TEXT channel —
1243/// what an agent reads once the JSON exceeds `token_budget`, or whenever
1244/// it passes `chunk`. Without it the three dangling conditions, which
1245/// have three different repairs, render as one identical line shape and
1246/// the reader is back to the fused report the codes were split to end.
1247/// Mirrors `overview.rs`'s rendered section
1248/// and the CLI's markdown block.
1249fn summarize_health_item(item: &serde_json::Value) -> String {
1250    if let Some(id) = item.get("id").and_then(|x| x.as_str()) {
1251        match item.get("title").and_then(|x| x.as_str()) {
1252            Some(t) if !t.is_empty() => format!("{id} — {t}"),
1253            _ => id.to_string(),
1254        }
1255    } else if let Some(from) = item.get("from").and_then(|x| x.as_str()) {
1256        let target = item.get("target_id").and_then(|x| x.as_str()).unwrap_or("");
1257        match item.get("kind").and_then(|x| x.as_str()) {
1258            Some(kind) => format!("[{kind}] {from} → {target}"),
1259            None => format!("{from} → {target}"),
1260        }
1261    } else {
1262        serde_json::to_string(item).unwrap_or_default()
1263    }
1264}
1265
1266/// One stale-axis row. A row the day threshold produced carries the three
1267/// historical keys and nothing else (the anchor-less render is byte for
1268/// byte what it was); a row the anchor clock produced adds `clock:
1269/// "anchors"` and the `anchor_state` that made it.
1270fn stale_row(e: &crate::ops::StaleEntity) -> serde_json::Value {
1271    let mut row = serde_json::json!({
1272        "id": e.id.to_string(),
1273        "title": e.title,
1274        "days_since_modified": e.days_since_modified,
1275    });
1276    if let Some(state) = &e.anchor_state {
1277        let obj = row.as_object_mut().unwrap();
1278        obj.insert("clock".into(), serde_json::json!("anchors"));
1279        obj.insert("anchor_state".into(), serde_json::json!(state));
1280    }
1281    row
1282}
1283
1284/// One `checks` finding line, for every surface that renders the checks
1285/// axis as markdown.
1286///
1287/// Shared rather than copied because the line carries a checker's own
1288/// prose: the message is whatever agent recorded the check wrote, which in
1289/// a workspace that points a foreign model or a transcribed outside finding
1290/// at its ledger is not the workspace itself. A second copy of this
1291/// rendering is a second place for the identity and the containment to go
1292/// missing, and it already had: the CLI's markdown path printed a
1293/// stranger's sentence with no author while the MCP path named one.
1294///
1295/// `f` is one entry of the checks axis's `findings` map, as
1296/// `crate::ops::health` builds it.
1297pub fn render_check_finding_line(entity: &str, f: &serde_json::Value) -> String {
1298    let code = f["finding"]["code"].as_str().unwrap_or("?");
1299    let section = f["finding"]["section"]
1300        .as_str()
1301        .map(|x| format!(" [{x}]"))
1302        .unwrap_or_default();
1303    let message = f["finding"]["message"].as_str().unwrap_or("");
1304    // Who wrote the sentence, and whether they are this workspace. Without
1305    // the identity a reading agent takes a checker's prose for the report's
1306    // own voice; a third-party row is additionally contained, because this
1307    // line is read by the same agent that reads the entities.
1308    let third_party =
1309        f["origin"].as_str() == Some(crate::render::OriginClass::ThirdParty.as_wire());
1310    let by = f["identity"]
1311        .as_str()
1312        .map(|i| format!(" by `{i}`"))
1313        .unwrap_or_default();
1314    let (mark, message) = if third_party {
1315        (
1316            crate::render::QUOTE_LABEL,
1317            crate::render::quote_inline(message),
1318        )
1319    } else {
1320        ("", message.to_string())
1321    };
1322    format!(
1323        "  - finding on `{entity}` ({} {}){by}{mark}: {code}{section} — {message}",
1324        f["kind"].as_str().unwrap_or("verification"),
1325        f["verdict"].as_str().unwrap_or("?"),
1326    )
1327}
1328
1329impl ComposeHealthError {
1330    /// The engine error this refusal is, with the recovery facts the
1331    /// engine supplies (the mounted and writable mems, a quarantine
1332    /// reason): the one value both surfaces render.
1333    pub fn into_engine_error(self, engine: &crate::Engine) -> crate::EngineError {
1334        match self {
1335            ComposeHealthError::UnknownMem { name, .. } => engine.unknown_mem(&name),
1336            ComposeHealthError::MemQuarantined(name) => engine.unknown_mem_error(&name),
1337            ComposeHealthError::InvalidTargetSchema { raw, reason } => {
1338                crate::EngineError::InvalidTargetSchema { raw, reason }
1339            }
1340            ComposeHealthError::Engine(e) => e,
1341        }
1342    }
1343}
1344
1345#[cfg(test)]
1346mod tests {
1347    use super::render_health_markdown;
1348    use serde_json::json;
1349
1350    fn base_payload() -> serde_json::Value {
1351        json!({
1352            "summary": { "total_entities": 1 },
1353            "total_nodes": 1,
1354        })
1355    }
1356
1357    /// The description advertises `body_observations` on the conformance
1358    /// axis, and a description is not a shipped field: the drift gate
1359    /// compares description tokens against an allowlist, so it stayed green
1360    /// while no server emitted the key at all (grade, 2026-08-27). This
1361    /// pins the text channel end of it; the JSON end is pinned by the
1362    /// handler test in `ops::integrity`.
1363    #[test]
1364    fn body_observations_render_their_code_and_fate_not_just_an_id() {
1365        let mut v = base_payload();
1366        v["body_observations"] = json!([{
1367            "id": "specs--alpha",
1368            "code": "ABSORBED_SECTION",
1369            "fate": "absorbed",
1370            "detail": { "heading": "Rogue", "note": "survives the next write" },
1371        }, {
1372            "id": "specs--beta",
1373            "code": "UNDECLARED_METADATA_KEY",
1374            "fate": "dropped",
1375            "detail": { "key": "reviewer", "note": "the next write drops it" },
1376        }]);
1377        let md = render_health_markdown(&v);
1378        assert!(md.contains("## Body observations (2)"), "{md}");
1379        assert!(
1380            md.contains(
1381                "- specs--alpha [ABSORBED_SECTION] `Rogue`: absorbed (survives the next write)"
1382            ),
1383            "{md}"
1384        );
1385        assert!(
1386            md.contains(
1387                "- specs--beta [UNDECLARED_METADATA_KEY] `reviewer`: dropped \
1388                 (the next write drops it)"
1389            ),
1390            "{md}"
1391        );
1392        // Absent key renders nothing at all.
1393        assert!(!render_health_markdown(&base_payload()).contains("Body observations"));
1394    }
1395
1396    /// The text channel names the condition.
1397    /// This is the surface an agent gets once the JSON exceeds
1398    /// `token_budget`, and it rendered all three dangling conditions as
1399    /// one indistinguishable `from → target` line while every other
1400    /// surface had been migrated — the last place the fused report
1401    /// survived.
1402    #[test]
1403    fn render_health_markdown_names_the_dangling_condition() {
1404        let mut v = base_payload();
1405        v["dangling_links"] = json!([
1406            {
1407                "kind": "DANGLING_LINK_TARGET_MISSING",
1408                "from": "specs--a", "target_id": "specs--gone",
1409                "target_path": "gone", "section": "purpose",
1410            },
1411            {
1412                "kind": "DANGLING_RELATION_TARGET_MISSING",
1413                "from": "specs--b", "target_id": "specs--vanished",
1414                "target_path": "vanished", "section": null,
1415            },
1416        ]);
1417        let md = render_health_markdown(&v);
1418        assert!(
1419            md.contains("[DANGLING_LINK_TARGET_MISSING] specs--a → specs--gone"),
1420            "{md}"
1421        );
1422        assert!(
1423            md.contains("[DANGLING_RELATION_TARGET_MISSING] specs--b → specs--vanished"),
1424            "{md}"
1425        );
1426        // The two conditions do not render as the same line shape.
1427        assert!(
1428            !md.contains("- specs--a → specs--gone"),
1429            "the unprefixed form is what fused them: {md}"
1430        );
1431    }
1432
1433    /// Text-channel parity: the `checks` / `stale_derivations` axes
1434    /// and the quarantine roster render their own sections — content
1435    /// when populated, the explicit zero statement when requested but
1436    /// empty (null is a statement), and NOTHING when the JSON key is
1437    /// absent: a payload without the keys renders byte-identically to
1438    /// itself with sections appended, never mutated.
1439    #[test]
1440    fn render_health_markdown_covers_checks_derivations_and_quarantine() {
1441        // Populated.
1442        let mut v = base_payload();
1443        v["checks"] = json!({
1444            "specs": {
1445                "never_checked": 2, "checked_ok": 1,
1446                "check_failed": 0, "check_stale": 0,
1447                "conformance": {
1448                    "never_checked": 3, "checked_ok": 0,
1449                    "check_failed": 0, "check_stale": 0,
1450                },
1451                "independence": {
1452                    "self_checked": { "count": 0, "items": [] },
1453                    "confirmed_independent": { "count": 0, "items": [] },
1454                    "unconfirmable": { "count": 1, "items": ["specs--a"] },
1455                },
1456            }
1457        });
1458        v["stale_derivations"] = json!({
1459            "specs": [{
1460                "source": "specs--a", "rel_type": "DERIVES_FROM",
1461                "target": "specs--b", "state": "stale",
1462                "baseline": "aaa", "current": "bbb",
1463            }]
1464        });
1465        v["quarantined"] = json!([{
1466            "mem": "broken",
1467            "reason_code": "SCHEMA_NOT_FOUND",
1468            "reason_message": "no schema; repair via memstead mem set-schema",
1469        }]);
1470        let md = render_health_markdown(&v);
1471        assert!(md.contains("## Checks (1 mems)"), "{md}");
1472        assert!(
1473            md.contains(
1474                "- `specs`: never_checked 2, checked_ok 1, check_failed 0, \
1475                 check_stale 0; conformance: never_checked 3, checked_ok 0, \
1476                 check_failed 0, check_stale 0; independence: self_checked 0, \
1477                 confirmed_independent 0, unconfirmable 1"
1478            ),
1479            "{md}"
1480        );
1481        assert!(md.contains("## Stale derivations (1 findings)"), "{md}");
1482        assert!(
1483            md.contains("- `specs`: specs--a -[DERIVES_FROM]-> specs--b (stale)"),
1484            "{md}"
1485        );
1486        assert!(md.contains("## Quarantined mems (1)"), "{md}");
1487        assert!(
1488            md.contains(
1489                "- `broken` [SCHEMA_NOT_FOUND] no schema; repair via memstead mem set-schema"
1490            ),
1491            "{md}"
1492        );
1493
1494        // Requested but empty → the explicit zero statement.
1495        let mut empty = base_payload();
1496        empty["checks"] = json!({});
1497        empty["stale_derivations"] = json!({ "specs": [] });
1498        let md = render_health_markdown(&empty);
1499        assert!(md.contains("## Checks (0 mems)"), "{md}");
1500        assert!(md.contains("## Stale derivations (0 findings)"), "{md}");
1501
1502        // Keys absent (not requested) → byte-unchanged: no section,
1503        // and the populated render is the base render plus appendix.
1504        let base_md = render_health_markdown(&base_payload());
1505        for heading in ["## Checks", "## Stale derivations", "## Quarantined mems"] {
1506            assert!(
1507                !base_md.contains(heading),
1508                "absent key must render nothing: {base_md}"
1509            );
1510        }
1511        let appended = render_health_markdown(&v);
1512        assert!(
1513            appended.starts_with(&base_md),
1514            "sections append; the base output stays byte-identical"
1515        );
1516    }
1517}