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 (A7 AC3): 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 (C10, 2026-09-03). `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 => {
671                let now = engine.now_iso();
672                now.get(..10).unwrap_or(&now).to_string()
673            }
674        };
675        let brief = engine
676            .due_brief(&today, &crate::engine::due::DueWindow::Days(90), vf)
677            .map_err(|e| ComposeHealthError::InvalidTargetSchema {
678                raw: today.clone(),
679                reason: e,
680            })?;
681        obj.insert(
682            "due".into(),
683            serde_json::to_value(&brief).unwrap_or_default(),
684        );
685    }
686    if include.iter().any(|s| s == "friction") {
687        // The friction ledger's read surface:
688        // counts per code / per verb over the workspace-local refusal
689        // ledger, whole-ledger plus a recent 24h window. A workspace
690        // without a root (in-memory boots) or without a ledger yet
691        // serves the empty summary — the axis never fails health.
692        let summary = match engine.workspace_root() {
693            Some(root) => crate::friction::FrictionLedger::for_workspace(root).summarize(),
694            None => serde_json::json!({
695                "total": 0,
696                "by_code": {},
697                "by_verb": {},
698                "recent_24h": { "total": 0, "by_code": {} },
699                "ledger_bytes": 0,
700            }),
701        };
702        obj.insert("friction".into(), summary);
703    }
704    if include.iter().any(|s| s == "missing_required_outgoing") {
705        let reports = engine.missing_required_outgoing(vf);
706        let arr: Vec<serde_json::Value> = reports
707            .into_iter()
708            .map(|r| serde_json::to_value(&r).unwrap())
709            .collect();
710        obj.insert("missing_required_outgoing".into(), serde_json::json!(arr));
711    }
712    if include.iter().any(|s| s == "constraints") {
713        let reports = engine.constraint_findings(vf);
714        let arr: Vec<serde_json::Value> = reports
715            .into_iter()
716            .map(|r| serde_json::to_value(&r).unwrap())
717            .collect();
718        obj.insert("constraints".into(), serde_json::json!(arr));
719        let defects = engine.schema_format_defects();
720        if !defects.is_empty() {
721            obj.insert(
722                "schema_format_defects".into(),
723                serde_json::to_value(&defects).unwrap(),
724            );
725        }
726    }
727    if include.iter().any(|s| s == "tags") {
728        let (distribution, folded, untagged) =
729            crate::ops::health::collect_tag_distribution(engine.store(), vf, limit);
730        obj.insert(
731            "tag_distribution".into(),
732            serde_json::to_value(&distribution).unwrap(),
733        );
734        obj.insert(
735            "tag_distribution_folded".into(),
736            serde_json::to_value(&folded).unwrap(),
737        );
738        obj.insert(
739            "untagged_entities".into(),
740            serde_json::to_value(&untagged).unwrap(),
741        );
742    }
743    // Conformance axis (`conformance`), or both axes (`integrity`). Findings
744    // ride one flat `findings` list in the pinned `{ id, axis, code, detail }`
745    // shape; ids are mem-qualified so the flat list stays unambiguous when
746    // unscoped. Mems scan in sorted order and each mem's findings are
747    // deterministic, so the whole list is.
748    let wants_conformance = include
749        .iter()
750        .any(|s| s == "conformance" || s == "integrity");
751    if wants_conformance {
752        let wants_consistency = include.iter().any(|s| s == "integrity");
753        let target: Option<memstead_schema::SchemaRef> = match args.target_schema {
754            None => None,
755            Some(raw) => match raw.parse::<memstead_schema::SchemaRef>() {
756                Ok(r) => Some(r),
757                Err(reason) => {
758                    return Err(ComposeHealthError::InvalidTargetSchema {
759                        raw: raw.to_string(),
760                        reason,
761                    });
762                }
763            },
764        };
765        let scan_mems: Vec<String> = match vf {
766            Some(v) => vec![v.to_string()],
767            None => {
768                let mut all = writable_mems.clone();
769                all.sort();
770                all
771            }
772        };
773        let mut findings = Vec::new();
774        let mut observations = Vec::new();
775        for v in &scan_mems {
776            findings.extend(engine.conformance_findings(v, target.as_ref())?);
777            // Beside `findings`, never among them: an observation says what an
778            // entity body silently loses, and none of it makes the entity
779            // unconformant.
780            observations.extend(engine.body_observations(v, target.as_ref())?);
781            if wants_consistency {
782                findings.extend(engine.consistency_findings(v)?);
783            }
784        }
785        obj.insert("findings".into(), serde_json::to_value(&findings).unwrap());
786        obj.insert(
787            "body_observations".into(),
788            serde_json::to_value(&observations).unwrap(),
789        );
790    }
791
792    // `include=["ledger"]` — a folder mem's ledger set against its file set
793    // (04/04, criteria 1 and 2). Reads only: no ledger line is written,
794    // rewritten or removed and no file is touched, because writing lines for
795    // edits the engine did not author would fabricate provenance for a change
796    // it cannot attribute. Git-branch mems are absent from the map rather than
797    // present and clean.
798    if include.iter().any(|s| s == "ledger") {
799        let mut ledger = engine.ledger_reconciliation();
800        if let Some(v) = vf {
801            ledger.retain(|mem, _| mem == v);
802        }
803        obj.insert(
804            "ledger".into(),
805            serde_json::to_value(ledger).unwrap_or_default(),
806        );
807    }
808
809    // Workspace policy surface — opt-in via `include_config: true`
810    // (the documented boolean alias) OR the catalogue key
811    // `include=["config"]`; both render the same projection, and
812    // passing both renders it once (a single gate). The rendering
813    // itself is shared with the CLI's `--include config` via
814    // `crate::ops::health::config_projection` — one
815    // implementation, every surface. `mutations` + `plugin` are passed
816    // in via [`HealthConfig`] (server-owned copies, inserted verbatim).
817    if args.include_config || include.iter().any(|s| s == "config") {
818        // Per-mem config entries follow the same scope as every other
819        // section: one mem under a filter, every writable mem without.
820        let config_mems: Vec<String> = match vf {
821            Some(v) => writable_mems.iter().filter(|m| *m == v).cloned().collect(),
822            None => writable_mems.clone(),
823        };
824        let entries = crate::ops::health::config_projection(
825            engine,
826            &config_mems,
827            config.mutations.clone(),
828            config.plugin.clone(),
829        );
830        for (k, v) in entries {
831            obj.insert(k, v);
832        }
833    }
834
835    // The strict axis, read off the sections rendered above and the
836    // workspace check ledger. Last, so every section it reads is there.
837    if args.strict {
838        let ledger = engine
839            .workspace_root()
840            .map(crate::check::CheckLedger::for_workspace);
841        let axis = crate::ops::strict::compose_strict_axis(obj, ledger.as_ref(), vf);
842        obj.insert(
843            "strict".into(),
844            serde_json::to_value(&axis).unwrap_or_default(),
845        );
846    }
847
848    Ok(result)
849}
850
851/// Render a composed health payload as a human-readable markdown report
852/// for the MCP text channel. `structured_content` remains the source of
853/// truth (this is never parsed back); the markdown exists so the text
854/// channel is *chunkable* like `memstead_overview` instead of a wall of
855/// JSON that overflows the response cap under several includes. The
856/// size-driving include arrays each render as their own section so the
857/// chunker can split a large report cleanly.
858pub fn render_health_markdown(v: &serde_json::Value) -> String {
859    use std::fmt::Write as _;
860    let mut s = String::new();
861    let _ = writeln!(s, "# Graph health");
862    if let Some(mem) = v.get("mem").and_then(|x| x.as_str()) {
863        let _ = writeln!(s, "\nMem filter: `{mem}`");
864    }
865
866    if let Some(sum) = v.get("summary").and_then(|x| x.as_object()) {
867        let _ = writeln!(s, "\n## Summary");
868        for key in [
869            "total_entities",
870            "total_orphans",
871            "total_stubs",
872            "total_stale",
873            "total_missing_fields",
874            "total_communities",
875        ] {
876            if let Some(n) = sum.get(key).and_then(|x| x.as_u64()) {
877                let _ = writeln!(s, "- {}: {n}", key.replace('_', " "));
878            }
879        }
880        render_count_map(&mut s, sum.get("orphans_by_schema"), "Orphans by schema");
881        render_count_map(
882            &mut s,
883            sum.get("communities_by_schema"),
884            "Communities by schema",
885        );
886    }
887
888    for key in ["total_nodes", "real_nodes", "stub_nodes", "total_edges"] {
889        if let Some(n) = v.get(key).and_then(|x| x.as_u64()) {
890            let _ = writeln!(s, "- {}: {n}", key.replace('_', " "));
891        }
892    }
893
894    // Size-driving include arrays — one section each so chunking splits them.
895    for (key, title) in [
896        ("orphans", "Orphans"),
897        ("stubs", "Stubs"),
898        ("most_connected", "Most connected"),
899        ("missing_fields", "Missing fields"),
900        ("stale", "Stale"),
901        ("dangling_links", "Dangling links"),
902        ("missing_required_outgoing", "Missing required outgoing"),
903        ("constraints", "Constraint violations"),
904        ("findings", "Findings"),
905    ] {
906        if let Some(arr) = v.get(key).and_then(|x| x.as_array()) {
907            let _ = writeln!(s, "\n## {title} ({})", arr.len());
908            for item in arr {
909                let _ = writeln!(s, "- {}", summarize_health_item(item));
910            }
911        }
912    }
913
914    // Body observations — their own section, not a row in the table above:
915    // `summarize_health_item` prints an entity id and stops, and an
916    // observation whose fate is not stated says nothing at all. This is the
917    // MCP text channel, so it is what a cold agent reads.
918    if let Some(arr) = v.get("body_observations").and_then(|x| x.as_array()) {
919        let _ = writeln!(s, "\n## Body observations ({})", arr.len());
920        for item in arr {
921            let detail = &item["detail"];
922            let subject = detail
923                .get("heading")
924                .or_else(|| detail.get("key"))
925                .and_then(|x| x.as_str())
926                .unwrap_or("");
927            let _ = writeln!(
928                s,
929                "- {} [{}] `{subject}`: {} ({})",
930                item["id"].as_str().unwrap_or(""),
931                item["code"].as_str().unwrap_or(""),
932                item["fate"].as_str().unwrap_or(""),
933                detail
934                    .get("note")
935                    .and_then(|x| x.as_str())
936                    .unwrap_or("no note"),
937            );
938        }
939    }
940
941    // Due axis — the due brief's rows, overdue first.
942    if let Some(due) = v.get("due").and_then(|x| x.as_object()) {
943        let rows = |key: &str| -> Vec<&serde_json::Value> {
944            due.get(key)
945                .and_then(|x| x.as_array())
946                .map(|a| a.iter().collect())
947                .unwrap_or_default()
948        };
949        let overdue = rows("overdue");
950        let soon = rows("due_soon");
951        let _ = writeln!(
952            s,
953            "\n## Due ({} overdue, {} due soon; today {}, through {})",
954            overdue.len(),
955            soon.len(),
956            due.get("today").and_then(|x| x.as_str()).unwrap_or("?"),
957            due.get("through").and_then(|x| x.as_str()).unwrap_or("?"),
958        );
959        for r in overdue {
960            let _ = writeln!(
961                s,
962                "- `{}` — {} — **{}** OVERDUE ({} days past) (status: {}, mem: {})",
963                r["id"].as_str().unwrap_or(""),
964                r["title"].as_str().unwrap_or(""),
965                r["date"].as_str().unwrap_or(""),
966                r["days_past"].as_u64().unwrap_or(0),
967                r["status"].as_str().unwrap_or(""),
968                r["mem"].as_str().unwrap_or(""),
969            );
970        }
971        for r in soon {
972            let _ = writeln!(
973                s,
974                "- `{}` — {} — **{}** (in {} days) (status: {}, mem: {})",
975                r["id"].as_str().unwrap_or(""),
976                r["title"].as_str().unwrap_or(""),
977                r["date"].as_str().unwrap_or(""),
978                r["days_until"].as_u64().unwrap_or(0),
979                r["status"].as_str().unwrap_or(""),
980                r["mem"].as_str().unwrap_or(""),
981            );
982        }
983    }
984
985    // Anchors axis — an object (mem → counts plus the population they cover),
986    // not an array, so it renders its own compact section. The figure and the
987    // population render together (consistency-sweep 03/05, criteria 1 and 3):
988    // this is the MCP text channel, so it is what a cold agent reads, and it
989    // used to print four numbers and stop.
990    if let Some(obj) = v.get("anchors").and_then(|x| x.as_object()) {
991        let _ = writeln!(s, "\n## Anchors ({} mems)", obj.len());
992        for (mem, counts) in obj {
993            if let Some(c) = counts.get("condition").filter(|c| !c.is_null()) {
994                let _ = writeln!(
995                    s,
996                    "- `{mem}`: ANCHORS_SIDECAR_UNREADABLE — {} — {}",
997                    c["reason"].as_str().unwrap_or("reason not stated"),
998                    counts["population"]
999                        .as_str()
1000                        .unwrap_or("population not stated"),
1001                );
1002                continue;
1003            }
1004            // The figure prints through its type, from the row's own three
1005            // fields: the count never appears apart from its population.
1006            let figure = crate::anchor::AnchorResolutionFigure::from_json(counts)
1007                .map(|f| f.to_string())
1008                .unwrap_or_else(|| "resolution figure not stated with its population".to_string());
1009            let _ = writeln!(
1010                s,
1011                "- `{mem}`: resolves {figure}; drifted {}, recheck {}, unresolvable (artifact \
1012                 gone) {}, unobserved (not measured) {}, dangling (entity gone) {}",
1013                counts["drifted"].as_u64().unwrap_or(0),
1014                counts["recheck"].as_u64().unwrap_or(0),
1015                counts["unresolvable"].as_u64().unwrap_or(0),
1016                counts["unobserved"].as_u64().unwrap_or(0),
1017                counts["dangling"].as_u64().unwrap_or(0),
1018            );
1019        }
1020    }
1021
1022    // Vital signs — per mem, the five model-truth signal counts;
1023    // the lists stay in the structured payload.
1024    if let Some(obj) = v.get("vital_signs").and_then(|x| x.as_object()) {
1025        let mems: Vec<(&String, &serde_json::Value)> =
1026            obj.iter().filter(|(k, _)| *k != "_item_cap").collect();
1027        let _ = writeln!(s, "\n## Vital signs ({} mems)", mems.len());
1028        for (mem, sig) in mems {
1029            let count = |k: &str| sig[k]["count"].as_u64().unwrap_or(0);
1030            let share = match sig["type_share_by_community"]["status"].as_str() {
1031                Some("declared") => format!(
1032                    "last-resort type `{}` over {} communit{}",
1033                    sig["type_share_by_community"]["last_resort_type"]
1034                        .as_str()
1035                        .unwrap_or("?"),
1036                    count("type_share_by_community"),
1037                    if count("type_share_by_community") == 1 {
1038                        "y"
1039                    } else {
1040                        "ies"
1041                    }
1042                ),
1043                _ => "last-resort type not declared".to_string(),
1044            };
1045            let unclaimed = match sig["unclaimed_source_files"]["status"].as_str() {
1046                Some("enumerated") => format!(
1047                    "{} unclaimed source file(s)",
1048                    count("unclaimed_source_files")
1049                ),
1050                _ => "no bound source".to_string(),
1051            };
1052            let _ = writeln!(
1053                s,
1054                "- `{mem}`: {share}; {unclaimed}; {} contested unowned file(s); {} zero-outgoing \
1055                 entit{} in {} communit{}; {} empty declared section(s)",
1056                count("contested_unowned_files"),
1057                sig["zero_outgoing_entities"]["entities"]
1058                    .as_u64()
1059                    .unwrap_or(0),
1060                if sig["zero_outgoing_entities"]["entities"]
1061                    .as_u64()
1062                    .unwrap_or(0)
1063                    == 1
1064                {
1065                    "y"
1066                } else {
1067                    "ies"
1068                },
1069                count("zero_outgoing_entities"),
1070                if count("zero_outgoing_entities") == 1 {
1071                    "y"
1072                } else {
1073                    "ies"
1074                },
1075                count("empty_declared_sections"),
1076            );
1077        }
1078    }
1079
1080    // Checks axis — an object (mem → state counts + independence
1081    // gate). Null-is-a-statement (the Friction pattern): a requested
1082    // axis with no mems renders the explicit zero heading; an absent
1083    // key (not requested) renders nothing.
1084    if let Some(obj) = v.get("checks").and_then(|x| x.as_object()) {
1085        let _ = writeln!(s, "\n## Checks ({} mems)", obj.len());
1086        for (mem, c) in obj {
1087            let count = |key: &str| c.get(key).and_then(|x| x.as_u64()).unwrap_or(0);
1088            let conf = |key: &str| {
1089                c.get("conformance")
1090                    .and_then(|g| g.get(key))
1091                    .and_then(|x| x.as_u64())
1092                    .unwrap_or(0)
1093            };
1094            let gate = |key: &str| {
1095                c.get("independence")
1096                    .and_then(|g| g.get(key))
1097                    .and_then(|e| e.get("count"))
1098                    .and_then(|x| x.as_u64())
1099                    .unwrap_or(0)
1100            };
1101            let _ = writeln!(
1102                s,
1103                "- `{mem}`: never_checked {}, checked_ok {}, check_failed {}, \
1104                 check_stale {}; conformance: never_checked {}, \
1105                 checked_ok {}, check_failed {}, check_stale {}; \
1106                 independence: self_checked {}, \
1107                 confirmed_independent {}, unconfirmable {}",
1108                count("never_checked"),
1109                count("checked_ok"),
1110                count("check_failed"),
1111                count("check_stale"),
1112                conf("never_checked"),
1113                conf("checked_ok"),
1114                conf("check_failed"),
1115                conf("check_stale"),
1116                gate("self_checked"),
1117                gate("confirmed_independent"),
1118                gate("unconfirmable"),
1119            );
1120            // Foreign `x-` kinds by count and each entity's newest finding —
1121            // the same lines the CLI text surface prints, so the two
1122            // renderers say the same thing.
1123            if let Some(foreign) = c.get("foreign_kinds").and_then(|f| f.as_object())
1124                && !foreign.is_empty()
1125            {
1126                let listed: Vec<String> = foreign
1127                    .iter()
1128                    .map(|(k, n)| format!("{k} {}", n.as_u64().unwrap_or(0)))
1129                    .collect();
1130                let _ = writeln!(s, "  - foreign kinds: {}", listed.join(", "));
1131            }
1132            if let Some(findings) = c.get("findings").and_then(|f| f.as_object()) {
1133                for (entity, f) in findings {
1134                    let _ = writeln!(s, "{}", render_check_finding_line(entity, f));
1135                }
1136            }
1137        }
1138    }
1139
1140    // Stale-derivations axis — an object (mem → findings list). Same
1141    // requested-vs-absent contract as the checks axis above.
1142    if let Some(obj) = v.get("stale_derivations").and_then(|x| x.as_object()) {
1143        let total: usize = obj
1144            .values()
1145            .filter_map(|a| a.as_array().map(|a| a.len()))
1146            .sum();
1147        let _ = writeln!(s, "\n## Stale derivations ({total} findings)");
1148        for (mem, findings) in obj {
1149            for f in findings.as_array().into_iter().flatten() {
1150                let _ = writeln!(
1151                    s,
1152                    "- `{mem}`: {} -[{}]-> {} ({})",
1153                    f.get("source").and_then(|x| x.as_str()).unwrap_or(""),
1154                    f.get("rel_type").and_then(|x| x.as_str()).unwrap_or(""),
1155                    f.get("target").and_then(|x| x.as_str()).unwrap_or(""),
1156                    f.get("state").and_then(|x| x.as_str()).unwrap_or(""),
1157                );
1158            }
1159        }
1160    }
1161
1162    // Quarantine roster — ungated in the JSON (present whenever
1163    // non-empty), so the text channel renders it whenever present:
1164    // per mem the reason code plus the message, which carries the
1165    // repair command.
1166    if let Some(arr) = v.get("quarantined").and_then(|x| x.as_array()) {
1167        let _ = writeln!(s, "\n## Quarantined mems ({})", arr.len());
1168        for q in arr {
1169            let _ = writeln!(
1170                s,
1171                "- `{}` [{}] {}",
1172                q.get("mem").and_then(|x| x.as_str()).unwrap_or(""),
1173                q.get("reason_code").and_then(|x| x.as_str()).unwrap_or(""),
1174                q.get("reason_message")
1175                    .and_then(|x| x.as_str())
1176                    .unwrap_or(""),
1177            );
1178        }
1179    }
1180
1181    if let Some(arr) = v.get("warnings").and_then(|x| x.as_array())
1182        && !arr.is_empty()
1183    {
1184        let _ = writeln!(s, "\n## Warnings ({})", arr.len());
1185        for w in arr {
1186            let code = w.get("code").and_then(|x| x.as_str()).unwrap_or("");
1187            let msg = w.get("message").and_then(|x| x.as_str()).unwrap_or("");
1188            let _ = writeln!(s, "- [{code}] {msg}");
1189        }
1190    }
1191
1192    s
1193}
1194
1195/// Render a `{ key: count }` map as an indented sub-list under `title`,
1196/// skipping an empty/missing map. The empty-string schema key (an unpinned
1197/// mem) renders as `(unpinned)`.
1198fn render_count_map(s: &mut String, val: Option<&serde_json::Value>, title: &str) {
1199    use std::fmt::Write as _;
1200    let Some(map) = val.and_then(|x| x.as_object()) else {
1201        return;
1202    };
1203    if map.is_empty() {
1204        return;
1205    }
1206    let _ = writeln!(s, "- {title}:");
1207    for (k, n) in map {
1208        let label = if k.is_empty() {
1209            "(unpinned)"
1210        } else {
1211            k.as_str()
1212        };
1213        let _ = writeln!(s, "  - {label}: {}", n.as_u64().unwrap_or(0));
1214    }
1215}
1216
1217/// One-line summary of a health detail item: prefer `id` (+ `title`),
1218/// else a dangling reference as `[kind] from → target_id`, else the
1219/// compact JSON.
1220///
1221/// The `kind` prefix matters because this is the health TEXT channel —
1222/// what an agent reads once the JSON exceeds `token_budget`, or whenever
1223/// it passes `chunk`. Without it the three dangling conditions, which
1224/// have three different repairs, render as one identical line shape and
1225/// the reader is back to the fused report the codes were split to end
1226/// (04/06, criteria 2 and 4). Mirrors `overview.rs`'s rendered section
1227/// and the CLI's markdown block.
1228fn summarize_health_item(item: &serde_json::Value) -> String {
1229    if let Some(id) = item.get("id").and_then(|x| x.as_str()) {
1230        match item.get("title").and_then(|x| x.as_str()) {
1231            Some(t) if !t.is_empty() => format!("{id} — {t}"),
1232            _ => id.to_string(),
1233        }
1234    } else if let Some(from) = item.get("from").and_then(|x| x.as_str()) {
1235        let target = item.get("target_id").and_then(|x| x.as_str()).unwrap_or("");
1236        match item.get("kind").and_then(|x| x.as_str()) {
1237            Some(kind) => format!("[{kind}] {from} → {target}"),
1238            None => format!("{from} → {target}"),
1239        }
1240    } else {
1241        serde_json::to_string(item).unwrap_or_default()
1242    }
1243}
1244
1245/// One stale-axis row. A row the day threshold produced carries the three
1246/// historical keys and nothing else (the anchor-less render is byte for
1247/// byte what it was); a row the anchor clock produced adds `clock:
1248/// "anchors"` and the `anchor_state` that made it.
1249fn stale_row(e: &crate::ops::StaleEntity) -> serde_json::Value {
1250    let mut row = serde_json::json!({
1251        "id": e.id.to_string(),
1252        "title": e.title,
1253        "days_since_modified": e.days_since_modified,
1254    });
1255    if let Some(state) = &e.anchor_state {
1256        let obj = row.as_object_mut().unwrap();
1257        obj.insert("clock".into(), serde_json::json!("anchors"));
1258        obj.insert("anchor_state".into(), serde_json::json!(state));
1259    }
1260    row
1261}
1262
1263/// One `checks` finding line, for every surface that renders the checks
1264/// axis as markdown.
1265///
1266/// Shared rather than copied because the line carries a checker's own
1267/// prose: the message is whatever agent recorded the check wrote, which in
1268/// a workspace that points a foreign model or a transcribed outside finding
1269/// at its ledger is not the workspace itself. A second copy of this
1270/// rendering is a second place for the identity and the containment to go
1271/// missing, and it already had: the CLI's markdown path printed a
1272/// stranger's sentence with no author while the MCP path named one.
1273///
1274/// `f` is one entry of the checks axis's `findings` map, as
1275/// `crate::ops::health` builds it.
1276pub fn render_check_finding_line(entity: &str, f: &serde_json::Value) -> String {
1277    let code = f["finding"]["code"].as_str().unwrap_or("?");
1278    let section = f["finding"]["section"]
1279        .as_str()
1280        .map(|x| format!(" [{x}]"))
1281        .unwrap_or_default();
1282    let message = f["finding"]["message"].as_str().unwrap_or("");
1283    // Who wrote the sentence, and whether they are this workspace. Without
1284    // the identity a reading agent takes a checker's prose for the report's
1285    // own voice; a third-party row is additionally contained, because this
1286    // line is read by the same agent that reads the entities.
1287    let third_party =
1288        f["origin"].as_str() == Some(crate::render::OriginClass::ThirdParty.as_wire());
1289    let by = f["identity"]
1290        .as_str()
1291        .map(|i| format!(" by `{i}`"))
1292        .unwrap_or_default();
1293    let (mark, message) = if third_party {
1294        (
1295            crate::render::QUOTE_LABEL,
1296            crate::render::quote_inline(message),
1297        )
1298    } else {
1299        ("", message.to_string())
1300    };
1301    format!(
1302        "  - finding on `{entity}` ({} {}){by}{mark}: {code}{section} — {message}",
1303        f["kind"].as_str().unwrap_or("verification"),
1304        f["verdict"].as_str().unwrap_or("?"),
1305    )
1306}
1307
1308#[cfg(test)]
1309mod tests {
1310    use super::render_health_markdown;
1311    use serde_json::json;
1312
1313    fn base_payload() -> serde_json::Value {
1314        json!({
1315            "summary": { "total_entities": 1 },
1316            "total_nodes": 1,
1317        })
1318    }
1319
1320    /// The description advertises `body_observations` on the conformance
1321    /// axis, and a description is not a shipped field: the drift gate
1322    /// compares description tokens against an allowlist, so it stayed green
1323    /// while no server emitted the key at all (grade, 2026-08-27). This
1324    /// pins the text channel end of it; the JSON end is pinned by the
1325    /// handler test in `ops::integrity`.
1326    #[test]
1327    fn body_observations_render_their_code_and_fate_not_just_an_id() {
1328        let mut v = base_payload();
1329        v["body_observations"] = json!([{
1330            "id": "specs--alpha",
1331            "code": "ABSORBED_SECTION",
1332            "fate": "absorbed",
1333            "detail": { "heading": "Rogue", "note": "survives the next write" },
1334        }, {
1335            "id": "specs--beta",
1336            "code": "UNDECLARED_METADATA_KEY",
1337            "fate": "dropped",
1338            "detail": { "key": "reviewer", "note": "the next write drops it" },
1339        }]);
1340        let md = render_health_markdown(&v);
1341        assert!(md.contains("## Body observations (2)"), "{md}");
1342        assert!(
1343            md.contains(
1344                "- specs--alpha [ABSORBED_SECTION] `Rogue`: absorbed (survives the next write)"
1345            ),
1346            "{md}"
1347        );
1348        assert!(
1349            md.contains(
1350                "- specs--beta [UNDECLARED_METADATA_KEY] `reviewer`: dropped \
1351                 (the next write drops it)"
1352            ),
1353            "{md}"
1354        );
1355        // Absent key renders nothing at all.
1356        assert!(!render_health_markdown(&base_payload()).contains("Body observations"));
1357    }
1358
1359    /// 04/06, criteria 2 and 4: the text channel names the condition.
1360    /// This is the surface an agent gets once the JSON exceeds
1361    /// `token_budget`, and it rendered all three dangling conditions as
1362    /// one indistinguishable `from → target` line while every other
1363    /// surface had been migrated — the last place the fused report
1364    /// survived.
1365    #[test]
1366    fn render_health_markdown_names_the_dangling_condition() {
1367        let mut v = base_payload();
1368        v["dangling_links"] = json!([
1369            {
1370                "kind": "DANGLING_LINK_TARGET_MISSING",
1371                "from": "specs--a", "target_id": "specs--gone",
1372                "target_path": "gone", "section": "purpose",
1373            },
1374            {
1375                "kind": "DANGLING_RELATION_TARGET_MISSING",
1376                "from": "specs--b", "target_id": "specs--vanished",
1377                "target_path": "vanished", "section": null,
1378            },
1379        ]);
1380        let md = render_health_markdown(&v);
1381        assert!(
1382            md.contains("[DANGLING_LINK_TARGET_MISSING] specs--a → specs--gone"),
1383            "{md}"
1384        );
1385        assert!(
1386            md.contains("[DANGLING_RELATION_TARGET_MISSING] specs--b → specs--vanished"),
1387            "{md}"
1388        );
1389        // The two conditions do not render as the same line shape.
1390        assert!(
1391            !md.contains("- specs--a → specs--gone"),
1392            "the unprefixed form is what fused them: {md}"
1393        );
1394    }
1395
1396    /// Text-channel parity: the `checks` / `stale_derivations` axes
1397    /// and the quarantine roster render their own sections — content
1398    /// when populated, the explicit zero statement when requested but
1399    /// empty (null is a statement), and NOTHING when the JSON key is
1400    /// absent: a payload without the keys renders byte-identically to
1401    /// itself with sections appended, never mutated.
1402    #[test]
1403    fn render_health_markdown_covers_checks_derivations_and_quarantine() {
1404        // Populated.
1405        let mut v = base_payload();
1406        v["checks"] = json!({
1407            "specs": {
1408                "never_checked": 2, "checked_ok": 1,
1409                "check_failed": 0, "check_stale": 0,
1410                "conformance": {
1411                    "never_checked": 3, "checked_ok": 0,
1412                    "check_failed": 0, "check_stale": 0,
1413                },
1414                "independence": {
1415                    "self_checked": { "count": 0, "items": [] },
1416                    "confirmed_independent": { "count": 0, "items": [] },
1417                    "unconfirmable": { "count": 1, "items": ["specs--a"] },
1418                },
1419            }
1420        });
1421        v["stale_derivations"] = json!({
1422            "specs": [{
1423                "source": "specs--a", "rel_type": "DERIVES_FROM",
1424                "target": "specs--b", "state": "stale",
1425                "baseline": "aaa", "current": "bbb",
1426            }]
1427        });
1428        v["quarantined"] = json!([{
1429            "mem": "broken",
1430            "reason_code": "SCHEMA_NOT_FOUND",
1431            "reason_message": "no schema; repair via memstead mem set-schema",
1432        }]);
1433        let md = render_health_markdown(&v);
1434        assert!(md.contains("## Checks (1 mems)"), "{md}");
1435        assert!(
1436            md.contains(
1437                "- `specs`: never_checked 2, checked_ok 1, check_failed 0, \
1438                 check_stale 0; conformance: never_checked 3, checked_ok 0, \
1439                 check_failed 0, check_stale 0; independence: self_checked 0, \
1440                 confirmed_independent 0, unconfirmable 1"
1441            ),
1442            "{md}"
1443        );
1444        assert!(md.contains("## Stale derivations (1 findings)"), "{md}");
1445        assert!(
1446            md.contains("- `specs`: specs--a -[DERIVES_FROM]-> specs--b (stale)"),
1447            "{md}"
1448        );
1449        assert!(md.contains("## Quarantined mems (1)"), "{md}");
1450        assert!(
1451            md.contains(
1452                "- `broken` [SCHEMA_NOT_FOUND] no schema; repair via memstead mem set-schema"
1453            ),
1454            "{md}"
1455        );
1456
1457        // Requested but empty → the explicit zero statement.
1458        let mut empty = base_payload();
1459        empty["checks"] = json!({});
1460        empty["stale_derivations"] = json!({ "specs": [] });
1461        let md = render_health_markdown(&empty);
1462        assert!(md.contains("## Checks (0 mems)"), "{md}");
1463        assert!(md.contains("## Stale derivations (0 findings)"), "{md}");
1464
1465        // Keys absent (not requested) → byte-unchanged: no section,
1466        // and the populated render is the base render plus appendix.
1467        let base_md = render_health_markdown(&base_payload());
1468        for heading in ["## Checks", "## Stale derivations", "## Quarantined mems"] {
1469            assert!(
1470                !base_md.contains(heading),
1471                "absent key must render nothing: {base_md}"
1472            );
1473        }
1474        let appended = render_health_markdown(&v);
1475        assert!(
1476            appended.starts_with(&base_md),
1477            "sections append; the base output stays byte-identical"
1478        );
1479    }
1480}