Skip to main content

memstead_base/ops/
health.rs

1//! Health checks — missing required fields, staleness, scoring.
2//!
3//! Checks each entity against its schema's requirements:
4//! - Required metadata fields present and non-empty
5//! - Required sections present and non-empty
6//! - Staleness: days since last_modified > schema threshold
7//! - Undeclared relationships — existing entities whose
8//!   `relationships:` include a name that is not in the per-mem
9//!   schema's vocabulary surface as soft warnings rather than hard
10//!   load-time failures. Agents can fix either the entity or the
11//!   schema; undeclared *types* on load are decision-3 hard errors
12//!   and covered elsewhere.
13
14use std::collections::HashMap;
15use std::sync::Arc;
16
17use memstead_schema::{Schema, TypeDefinition, type_by_name};
18
19use super::{
20    DanglingLink, FoldedTag, HealthIssue, HealthReport, HealthSummary, StaleEntity,
21    TagDistribution, TagVariant, UntaggedStats,
22};
23use crate::entity::MetadataValue;
24use crate::graph::query;
25use crate::store::Store;
26
27/// Allowed `include` keys for `memstead_health` — the single source of
28/// truth shared across the MCP server and the
29/// CLI's `health` command. Adding a new include key here lights
30/// it up uniformly; agents see the same `UNKNOWN_INCLUDE_KEY` warning
31/// shape whether they reach health via MCP or CLI.
32pub const HEALTH_INCLUDE_KEYS: &[&str] = &[
33    "orphans",
34    "stubs",
35    "most_connected",
36    "missing_fields",
37    "stale",
38    "dangling_links",
39    "tags",
40    "missing_required_outgoing",
41    "constraints",
42    "signals",
43    "labelling",
44    "conformance",
45    "integrity",
46    "config",
47    "anchors",
48    "friction",
49    "open_questions",
50    "stale_derivations",
51    "checks",
52    "ledger",
53    "vital_signs",
54    "due",
55];
56
57/// Item cap per vital-signs list.
58pub const VITAL_SIGNS_ITEM_CAP: usize = 20;
59
60/// The `include=["vital_signs"]` axis: per mem, the cheap,
61/// engine-countable model-truth signals the `/remodel` skill reads — each
62/// a count plus a capped list with an explicit `more` remainder, never a
63/// verdict, threshold or recommendation (the engine names what is there;
64/// the `/remodel` skill decides). Five signals:
65///
66/// - `type_share_by_community`: per community, how many of its entities
67///   sit on the schema's declared last-resort type (`last_resort: true`
68///   on exactly one type); `not_declared` when the schema declares none,
69///   never a guess from type names.
70/// - `unclaimed_source_files`: files of the mem's bound sources that no
71///   entity's anchor claims, largest first with their sizes (the size
72///   threshold that makes one "large" stays in the skill).
73/// - `contested_unowned_files`: files two or more entities claim through
74///   anchors while none owns them (no `anchored` class anchor).
75/// - `zero_outgoing_entities`: entities with no outgoing edge, folded into
76///   the community of their subject (their own cluster when it has more
77///   members than themselves, else the cluster of an entity that links to
78///   them, else `unplaced`) rather than ranked as singletons.
79/// - `empty_declared_sections`: sections the type declares that an
80///   entity carries empty.
81///
82/// Reuse, never recompute: the community partition, the anchor sidecar
83/// reads and the source enumeration are the ones the other axes use.
84pub fn health_vital_signs_axis(
85    engine: &crate::engine::Engine,
86    mem_filter: Option<&str>,
87) -> serde_json::Value {
88    let cap = VITAL_SIGNS_ITEM_CAP;
89    let capped = |mut items: Vec<serde_json::Value>| -> serde_json::Value {
90        let count = items.len();
91        let more = count.saturating_sub(cap);
92        items.truncate(cap);
93        let mut o = serde_json::Map::new();
94        o.insert("count".into(), serde_json::json!(count));
95        o.insert("items".into(), serde_json::Value::Array(items));
96        if more > 0 {
97            o.insert("more".into(), serde_json::json!(more));
98        }
99        serde_json::Value::Object(o)
100    };
101
102    let mut mems: Vec<String> = engine.mem_names().iter().map(|s| s.to_string()).collect();
103    mems.sort();
104    let communities = engine.communities();
105    let mut out = serde_json::Map::new();
106    for mem in &mems {
107        if let Some(f) = mem_filter
108            && f != mem
109        {
110            continue;
111        }
112        let entities: Vec<&crate::entity::Entity> = engine
113            .store()
114            .all_entities()
115            .filter(|e| !e.stub && e.id.mem() == mem)
116            .collect();
117        let schema = engine.schema_for(mem);
118
119        // --- 1. type share per community ---
120        let last_resort: Option<String> = schema.as_ref().and_then(|s| {
121            s.types
122                .values()
123                .find(|t| t.last_resort)
124                .map(|t| t.name.clone())
125        });
126        let type_share = match &last_resort {
127            None => serde_json::json!({ "status": "not_declared" }),
128            Some(lr) => {
129                let mut per: std::collections::BTreeMap<String, (usize, usize)> =
130                    std::collections::BTreeMap::new();
131                for e in &entities {
132                    let cluster = communities
133                        .entity_cluster_map
134                        .get(&e.id.0)
135                        .cloned()
136                        .unwrap_or_else(|| "unplaced".to_string());
137                    let slot = per.entry(cluster).or_insert((0, 0));
138                    slot.0 += 1;
139                    if e.entity_type == *lr {
140                        slot.1 += 1;
141                    }
142                }
143                let mut rows: Vec<serde_json::Value> = per
144                    .into_iter()
145                    .map(|(community, (total, on_last_resort))| {
146                        serde_json::json!({
147                            "community": community,
148                            "entities": total,
149                            "on_last_resort_type": on_last_resort,
150                        })
151                    })
152                    .collect();
153                // Most concentrated first: the reader sees the flattest
154                // cluster without ranking being a judgement.
155                rows.sort_by(|a, b| {
156                    let share = |v: &serde_json::Value| {
157                        let t = v["entities"].as_u64().unwrap_or(1).max(1) as f64;
158                        v["on_last_resort_type"].as_u64().unwrap_or(0) as f64 / t
159                    };
160                    share(b)
161                        .partial_cmp(&share(a))
162                        .unwrap_or(std::cmp::Ordering::Equal)
163                        .then_with(|| a["community"].as_str().cmp(&b["community"].as_str()))
164                });
165                let mut v = capped(rows);
166                v["status"] = serde_json::json!("declared");
167                v["last_resort_type"] = serde_json::json!(lr);
168                v
169            }
170        };
171
172        // --- 2 and 3. the file-to-entity map of the bound sources ---
173        // artifact -> (claiming entities, owned by an `anchored` anchor)
174        let mut claims: std::collections::BTreeMap<
175            String,
176            (std::collections::BTreeSet<String>, bool),
177        > = std::collections::BTreeMap::new();
178        for e in &entities {
179            for a in engine.entity_anchors(&e.id) {
180                let slot = claims.entry(a.artifact.clone()).or_default();
181                slot.0.insert(e.id.0.clone());
182                if a.class == crate::anchor::AnchorProvenanceClass::Anchored {
183                    slot.1 = true;
184                }
185            }
186        }
187        let roots = engine.anchor_source_roots(mem);
188        let mut unclaimed: Vec<serde_json::Value> = Vec::new();
189        let mut sources_enumerated = 0usize;
190        if let Some(ws) = engine.workspace_root() {
191            let mut seen: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
192            for join in roots.values() {
193                sources_enumerated += 1;
194                for file in crate::source_scope::enumerate_source_artifacts(
195                    engine,
196                    &join.source,
197                    &join.deny_paths,
198                    ws,
199                ) {
200                    if !seen.insert(file.clone()) || claims.contains_key(&file) {
201                        continue;
202                    }
203                    let size = std::fs::metadata(ws.join(&file))
204                        .map(|m| m.len())
205                        .unwrap_or(0);
206                    unclaimed.push(serde_json::json!({ "artifact": file, "bytes": size }));
207                }
208            }
209        }
210        unclaimed.sort_by(|a, b| {
211            b["bytes"]
212                .as_u64()
213                .cmp(&a["bytes"].as_u64())
214                .then_with(|| a["artifact"].as_str().cmp(&b["artifact"].as_str()))
215        });
216        let unclaimed_v = if sources_enumerated == 0 {
217            serde_json::json!({ "status": "no_bound_source" })
218        } else {
219            let mut v = capped(unclaimed);
220            v["status"] = serde_json::json!("enumerated");
221            v
222        };
223        let contested: Vec<serde_json::Value> = claims
224            .iter()
225            .filter(|(_, (who, owned))| who.len() >= 2 && !owned)
226            .map(|(artifact, (who, _))| {
227                serde_json::json!({
228                    "artifact": artifact,
229                    "claimed_by": who.iter().cloned().collect::<Vec<_>>(),
230                })
231            })
232            .collect();
233
234        // --- 4. zero-outgoing entities, folded into their subject ---
235        let cluster_size = |c: &str| -> usize {
236            communities
237                .clusters
238                .get(c)
239                .map(|ci| ci.entities.len())
240                .unwrap_or(0)
241        };
242        let mut by_community: std::collections::BTreeMap<String, Vec<String>> =
243            std::collections::BTreeMap::new();
244        for e in &entities {
245            if !engine.store().outgoing(&e.id).is_empty() {
246                continue;
247            }
248            let own = communities.entity_cluster_map.get(&e.id.0).cloned();
249            let community = match own {
250                Some(c) if cluster_size(&c) > 1 => c,
251                _ => engine
252                    .store()
253                    .incoming(&e.id)
254                    .iter()
255                    .find_map(|edge| communities.entity_cluster_map.get(&edge.from.0).cloned())
256                    .unwrap_or_else(|| "unplaced".to_string()),
257            };
258            by_community
259                .entry(community)
260                .or_default()
261                .push(e.id.0.clone());
262        }
263        let zero_total: usize = by_community.values().map(Vec::len).sum();
264        let zero_rows: Vec<serde_json::Value> = by_community
265            .into_iter()
266            .map(|(community, mut ids)| {
267                ids.sort();
268                let count = ids.len();
269                let more = count.saturating_sub(cap);
270                ids.truncate(cap);
271                let mut o = serde_json::json!({
272                    "community": community,
273                    "count": count,
274                    "items": ids,
275                });
276                if more > 0 {
277                    o["more"] = serde_json::json!(more);
278                }
279                o
280            })
281            .collect();
282        let mut zero_v = capped(zero_rows);
283        zero_v["entities"] = serde_json::json!(zero_total);
284
285        // --- 5. declared sections carried empty ---
286        let mut empty_sections: Vec<serde_json::Value> = Vec::new();
287        if let Some(s) = &schema {
288            for e in &entities {
289                let Some(td) = s.types.get(&e.entity_type) else {
290                    continue;
291                };
292                for sec in &td.sections {
293                    if e.sections
294                        .get(&sec.key)
295                        .is_some_and(|body| body.trim().is_empty())
296                    {
297                        empty_sections.push(serde_json::json!({
298                            "id": e.id.0,
299                            "section": sec.key,
300                        }));
301                    }
302                }
303            }
304        }
305
306        out.insert(
307            mem.clone(),
308            serde_json::json!({
309                "type_share_by_community": type_share,
310                "unclaimed_source_files": unclaimed_v,
311                "contested_unowned_files": capped(contested),
312                "zero_outgoing_entities": zero_v,
313                "empty_declared_sections": capped(empty_sections),
314            }),
315        );
316    }
317    let mut top = serde_json::Map::new();
318    top.insert("_item_cap".into(), serde_json::json!(cap));
319    for (k, v) in out {
320        top.insert(k, v);
321    }
322    serde_json::Value::Object(top)
323}
324
325/// The `include=["anchors"]` axis — per-mem counts of the four
326/// standalone-verification states, computed through the same
327/// per-anchor mechanism `verify-anchors` and the binding verify use.
328/// Shared by the health composer, the CLI health command, and the
329/// MCP server so the axis cannot drift between surfaces.
330/// The check records of one source (the workspace ledger, or one
331/// archive's sealed member), folded the way the checks axis reads them.
332#[derive(Default)]
333struct CheckMaps {
334    /// Newest `verification` record per entity.
335    latest: std::collections::BTreeMap<String, crate::check::CheckRecord>,
336    /// Newest `conformance` record per entity.
337    latest_conformance: std::collections::BTreeMap<String, crate::check::CheckRecord>,
338    /// Foreign `x-<name>` kinds per entity: recorded verbatim, never
339    /// aggregated into a state, listed by count per mem.
340    foreign_by_entity: std::collections::BTreeMap<String, Vec<String>>,
341    /// Newest record of any kind per entity, for the finding it may carry.
342    newest_any: std::collections::BTreeMap<String, crate::check::CheckRecord>,
343    /// Every verification record per entity, in standing order: the per-record
344    /// readings show each check's standing, not only the newest one's.
345    all_verification: std::collections::BTreeMap<String, Vec<crate::check::CheckRecord>>,
346}
347
348impl CheckMaps {
349    fn from_records<'a>(records: impl Iterator<Item = &'a crate::check::CheckRecord>) -> Self {
350        let mut maps = Self::default();
351        for rec in records {
352            maps.newest_any.insert(rec.entity.clone(), rec.clone());
353            match rec.resolved_kind() {
354                Some(crate::check::CheckKind::Verification) => {
355                    maps.all_verification
356                        .entry(rec.entity.clone())
357                        .or_default()
358                        .push(rec.clone());
359                    maps.latest.insert(rec.entity.clone(), rec.clone());
360                }
361                Some(crate::check::CheckKind::Conformance) => {
362                    maps.latest_conformance
363                        .insert(rec.entity.clone(), rec.clone());
364                }
365                None => {
366                    if let Some(k) = rec.foreign_kind() {
367                        maps.foreign_by_entity
368                            .entry(rec.entity.clone())
369                            .or_default()
370                            .push(k.to_string());
371                    }
372                }
373            }
374        }
375        maps
376    }
377}
378
379/// The `include=["checks"]` axis: per mem,
380/// counts of the four derived check states plus the author≠checker
381/// independence gate over ok-checked entities. The gate compares
382/// caller-declared IDENTITIES and nothing else:
383/// the entity's created-by record against its newest ok-check record
384/// — both carry an identity and they are equal → `self_checked`
385/// ("twice-asserted, not verified"); both carry one and they differ →
386/// `confirmed_independent`; either side lacks one → `unconfirmable`,
387/// never a guessed category. Transport is not identity: the recorded
388/// `(actor, client)` pair names the SURFACE a record arrived through
389/// and is recorded as context only — it never participates in the
390/// comparison (a same pair does not establish the same actor, and
391/// different pairs do not establish different actors). An identity is
392/// an honesty device, not authentication: caller-declared, unverified,
393/// tamper-evident in append-only history — a consistent multi-agent
394/// setup gets real independence signals, and a lying setup defeats
395/// only itself. Derivation only: nothing here is stamped, and a
396/// workspace without a check ledger serves all-never-checked.
397/// Identity lists are capped at [`OPEN_QUESTIONS_ITEM_CAP`] with an
398/// explicit `more` count.
399pub fn health_checks_axis(
400    engine: &crate::engine::Engine,
401    mem_filter: Option<&str>,
402) -> serde_json::Value {
403    let cap = OPEN_QUESTIONS_ITEM_CAP;
404    let capped = |mut items: Vec<String>| -> serde_json::Value {
405        items.sort();
406        let count = items.len();
407        let more = count.saturating_sub(cap);
408        items.truncate(cap);
409        let mut o = serde_json::Map::new();
410        o.insert("count".into(), serde_json::json!(count));
411        o.insert("items".into(), serde_json::json!(items));
412        if more > 0 {
413            o.insert("more".into(), serde_json::json!(more));
414        }
415        serde_json::Value::Object(o)
416    };
417
418    // The workspace ledger, folded once for every non-archive mem: the
419    // newest record per (entity, kind), every verification record, the
420    // newest record of any kind (for its finding), the foreign kinds.
421    // State is kind-scoped: a conformance record never supersedes a
422    // verification record, or the reverse.
423    let ledger_records: Vec<crate::check::CheckRecord> = engine
424        .workspace_root()
425        .map(|root| crate::check::CheckLedger::for_workspace(root).in_standing_order())
426        .unwrap_or_default();
427    let from_ledger = CheckMaps::from_records(ledger_records.iter());
428
429    let mut mems: Vec<String> = engine.mem_names().iter().map(|s| s.to_string()).collect();
430    mems.sort();
431    let mut out = serde_json::Map::new();
432    for mem in mems {
433        if let Some(f) = mem_filter
434            && f != mem
435        {
436            continue;
437        }
438        // One source per mount: an archive mount derives from its sealed
439        // check records (`.memstead/checks.json`) and never from the
440        // workspace ledger beside it; every other mount from the ledger.
441        let sealed_maps;
442        let (maps, sealed_note) = if engine.is_archive_mount(&mem) {
443            match engine.archive_checks_for(&mem) {
444                Some(sealed) => {
445                    let records: Vec<crate::check::CheckRecord> = sealed
446                        .entities
447                        .iter()
448                        .flat_map(|(path, kinds)| {
449                            let id = crate::EntityId::new(&mem, path).0;
450                            kinds.iter().map(move |(kind, sc)| sc.to_record(&id, kind))
451                        })
452                        .collect();
453                    sealed_maps = CheckMaps::from_records(records.iter());
454                    (
455                        &sealed_maps,
456                        Some(serde_json::json!({
457                            "carried": true,
458                            "records": records.len(),
459                        })),
460                    )
461                }
462                None => {
463                    sealed_maps = CheckMaps::default();
464                    (
465                        &sealed_maps,
466                        Some(serde_json::json!({
467                            "carried": false,
468                            "reason": "the archive carries no check records; every state reads never_checked",
469                        })),
470                    )
471                }
472            }
473        } else {
474            (&from_ledger, None)
475        };
476        let CheckMaps {
477            latest,
478            latest_conformance,
479            foreign_by_entity,
480            newest_any,
481            all_verification,
482        } = maps;
483        let mut counts = std::collections::BTreeMap::from([
484            ("never_checked", 0usize),
485            ("checked_ok", 0usize),
486            ("check_failed", 0usize),
487            ("check_stale", 0usize),
488        ]);
489        // The `conformance` kind's counts, additively beside the
490        // verification counts. Pin-aware: a schema re-pin stales
491        // every conformance verdict recorded under the old pin. A
492        // workspace with no conformance records serves all
493        // `never_checked` — honestly empty, never absent.
494        let current_pin = engine
495            .mount(&mem)
496            .and_then(|m| m.schema.as_ref())
497            .map(|s| s.as_display());
498        let mut conformance_counts = std::collections::BTreeMap::from([
499            ("never_checked", 0usize),
500            ("checked_ok", 0usize),
501            ("check_failed", 0usize),
502            ("check_stale", 0usize),
503        ]);
504        let mut self_checked: Vec<String> = Vec::new();
505        let mut confirmed_independent: Vec<String> = Vec::new();
506        let mut unconfirmable: Vec<String> = Vec::new();
507        // Which identities each ok-checked criterion was compared against
508        // (engine::independence), rendered so a reader can see who counted
509        // as an executor. One provenance pass per mem.
510        let mut executors = serde_json::Map::new();
511        let mut readings = serde_json::Map::new();
512        let touches = engine.mem_touches(&mem);
513        let mut foreign_kinds: std::collections::BTreeMap<String, usize> =
514            std::collections::BTreeMap::new();
515        let mut findings = serde_json::Map::new();
516        for e in engine.store().all_entities().filter(|e| e.mem == mem) {
517            let id = e.id.0.clone();
518            if let Some(kinds) = foreign_by_entity.get(&id) {
519                for k in kinds {
520                    *foreign_kinds.entry(k.clone()).or_insert(0) += 1;
521                }
522            }
523            if let Some(rec) = newest_any.get(&id)
524                && let Some(f) = &rec.finding
525            {
526                findings.insert(
527                    id.clone(),
528                    serde_json::json!({
529                        "verdict": rec.verdict,
530                        "kind": rec.kind.as_deref().unwrap_or("verification"),
531                        "ts": rec.ts,
532                        "observed_at": rec.observed_at,
533                        "identity": rec.identity,
534                        // The trust class of the prose on this row: the
535                        // message is whatever agent recorded the check
536                        // wrote, which in a workspace that points a foreign
537                        // model or a transcribed outside finding at its
538                        // ledger is not the workspace itself.
539                        "origin": engine.check_row_prose_origin(&mem, &id, rec).as_wire(),
540                        "finding": f,
541                    }),
542                );
543            }
544            let state = crate::check::derive_state(latest.get(&id), &e.content_hash);
545            *counts.entry(state.as_str()).or_insert(0) += 1;
546            if let Some(records) = all_verification.get(&id) {
547                let rows: Vec<serde_json::Value> = records
548                    .iter()
549                    .map(|rec| {
550                        let reading = if rec.verdict == "ok" {
551                            engine.independence_of(e, rec, &touches).0.as_str()
552                        } else {
553                            "failed"
554                        };
555                        // The declared role rides every row, and whether
556                        // it is a checking capacity: a gate closes only
557                        // on a row that is fresh, independent AND
558                        // declared `checker` or `verifier`.
559                        let role_confirms = matches!(
560                            crate::vcs::Role::from_wire(&rec.role).unwrap_or_default(),
561                            crate::vcs::Role::Checker | crate::vcs::Role::Verifier
562                        );
563                        serde_json::json!({
564                            "ts": rec.ts,
565                            "observed_at": rec.observed_at,
566                            "identity": rec.identity,
567                            "verdict": rec.verdict,
568                            "reading": reading,
569                            "role": rec.role,
570                            "role_confirms": role_confirms,
571                        })
572                    })
573                    .collect();
574                readings.insert(id.clone(), serde_json::Value::Array(rows));
575            }
576            let cstate = crate::check::derive_state_pinned(
577                latest_conformance.get(&id),
578                &e.content_hash,
579                current_pin.as_deref(),
580            );
581            *conformance_counts.entry(cstate.as_str()).or_insert(0) += 1;
582            if state != crate::check::CheckState::CheckedOk {
583                continue;
584            }
585            // Identity-only comparison (comparator widened
586            // 2026-09-02): the newest ok-check's identity against every
587            // identity that mutated the verified plan, its criteria or
588            // its session-log notes since this criterion was written
589            // (engine::independence); a non-criterion compares against
590            // every identity that wrote it up to the write the check saw.
591            // The (actor, client) transport pair is
592            // recorded context and never a comparator. Either side
593            // lacking an identity is unconfirmable, never a guessed
594            // category.
595            let check = latest.get(&id).expect("checked_ok implies a record");
596            let (reading, execs) = engine.independence_of(e, check, &touches);
597            if let Some(execs) = execs {
598                executors.insert(id.clone(), serde_json::json!(execs.identities));
599            }
600            match reading {
601                crate::engine::independence::Independence::SelfChecked => self_checked.push(id),
602                crate::engine::independence::Independence::ConfirmedIndependent => {
603                    confirmed_independent.push(id)
604                }
605                crate::engine::independence::Independence::Unconfirmable => unconfirmable.push(id),
606            }
607        }
608        let mut m = serde_json::Map::new();
609        for (k, v) in counts {
610            m.insert(k.to_string(), serde_json::json!(v));
611        }
612        let mut c = serde_json::Map::new();
613        for (k, v) in conformance_counts {
614            c.insert(k.to_string(), serde_json::json!(v));
615        }
616        m.insert("conformance".into(), serde_json::Value::Object(c));
617        // Foreign kinds by count, and the structured finding each
618        // entity's newest record carries — recorded, rendered, never
619        // interpreted.
620        m.insert(
621            "foreign_kinds".into(),
622            serde_json::to_value(&foreign_kinds).unwrap_or(serde_json::json!({})),
623        );
624        m.insert("findings".into(), serde_json::Value::Object(findings));
625        // On an archive mount: whether the archive seals check records at
626        // all, so an all-`never_checked` reading is explained, never bare.
627        if let Some(note) = sealed_note {
628            m.insert("sealed".into(), note);
629        }
630        m.insert(
631            "independence".into(),
632            serde_json::json!({
633                "self_checked": capped(self_checked),
634                "confirmed_independent": capped(confirmed_independent),
635                "unconfirmable": capped(unconfirmable),
636                "comparator": "every identity that mutated the verified plan, its criteria or its session-log notes since the criterion was written; a non-criterion compares against every identity that wrote it up to the write the check saw",
637                "executors": serde_json::Value::Object(executors),
638                "readings": serde_json::Value::Object(readings),
639            }),
640        );
641        out.insert(mem, serde_json::Value::Object(m));
642    }
643    serde_json::Value::Object(out)
644}
645
646/// One derivation-staleness finding: an
647/// explicit edge on a derivation-declared rel-type whose baseline
648/// differs from the target's current hash (`stale`), or that has no
649/// recorded baseline at all (`unbaselined`). Fresh edges are never
650/// reported.
651#[derive(Debug, Clone, serde::Serialize)]
652pub struct DerivationFinding {
653    pub source: crate::entity::EntityId,
654    pub rel_type: String,
655    pub target: crate::entity::EntityId,
656    /// `"stale"` or `"unbaselined"` — never fabricated as fresh.
657    pub state: String,
658    /// The recorded baseline hash (`None` for unbaselined edges).
659    #[serde(skip_serializing_if = "Option::is_none")]
660    pub baseline: Option<String>,
661    /// The target's current content hash ("" for an absent target).
662    pub current: String,
663}
664
665/// The `include=["stale_derivations"]` axis: per-mem findings from
666/// [`crate::engine::Engine::derivation_report`], shared by the CLI
667/// and the MCP server. A mem whose schema declares no derivation
668/// rel-types contributes an empty list — never an error.
669pub fn health_stale_derivations_axis(
670    engine: &crate::engine::Engine,
671    mem_filter: Option<&str>,
672) -> serde_json::Value {
673    let mut mems: Vec<String> = engine.mem_names().iter().map(|s| s.to_string()).collect();
674    mems.sort();
675    let mut out = serde_json::Map::new();
676    for mem in mems {
677        if let Some(f) = mem_filter
678            && f != mem
679        {
680            continue;
681        }
682        let findings = engine.derivation_report(&mem).unwrap_or_default();
683        out.insert(
684            mem,
685            serde_json::to_value(&findings).unwrap_or(serde_json::Value::Array(Vec::new())),
686        );
687    }
688    serde_json::Value::Object(out)
689}
690
691/// Per-kind item cap for the `open_questions` axis — the axis is an
692/// agent worklist, not a dump. Stated in the output (`_item_cap`);
693/// truncation is always explicit via each list's `more` count.
694pub const OPEN_QUESTIONS_ITEM_CAP: usize = 20;
695
696/// The `include=["open_questions"]` axis: per
697/// mem, a composed worklist of what the holding does not know — its
698/// stubs, its never-confirmed (`recheck`) and `unresolvable` anchors,
699/// its unsatisfied constraints, its dangling links, and, when a
700/// paired process mem is resolvable for the destination, that
701/// process mem's open entries. Negative findings ride under the
702/// DISTINCT `already_searched` heading — their operational meaning is
703/// "done, keep off", never todo.
704///
705/// Composition only: every signal is read from the same source its
706/// own axis serves (store stub flags, `verify_mem_anchors`,
707/// `constraint_findings`, `collect_dangling_links`, the pipeline
708/// store), so this axis can never disagree with the per-signal axes.
709/// Best-effort on the process leg: an unreadable pipeline store means
710/// no process sections, never an axis failure.
711pub fn health_open_questions_axis(
712    engine: &crate::engine::Engine,
713    mem_filter: Option<&str>,
714) -> serde_json::Value {
715    let cap = OPEN_QUESTIONS_ITEM_CAP;
716    let capped = |mut items: Vec<serde_json::Value>| -> serde_json::Value {
717        let count = items.len();
718        let more = count.saturating_sub(cap);
719        items.truncate(cap);
720        let mut o = serde_json::Map::new();
721        o.insert("count".into(), serde_json::json!(count));
722        o.insert("items".into(), serde_json::Value::Array(items));
723        if more > 0 {
724            o.insert("more".into(), serde_json::json!(more));
725        }
726        serde_json::Value::Object(o)
727    };
728
729    // Bindings by destination mem. The pairing is not declarative yet;
730    // until it is, the ingest-name convention (process mem
731    // named after the binding) is the resolution mechanism.
732    let bindings: Vec<(String, String)> = engine
733        .workspace_root()
734        .and_then(|root| crate::pipeline_store::load_pipeline_configs(root).ok())
735        .map(|c| {
736            c.bindings
737                .iter()
738                .map(|r| (r.config.destination_mem.clone(), r.name.clone()))
739                .collect()
740        })
741        .unwrap_or_default();
742    let mounted: Vec<String> = engine.mem_names().iter().map(|s| s.to_string()).collect();
743
744    let mut mems: Vec<String> = mounted.clone();
745    mems.sort();
746    let mut out = serde_json::Map::new();
747    for mem in &mems {
748        if let Some(f) = mem_filter
749            && f != mem
750        {
751            continue;
752        }
753
754        // Stubs — same source as the stubs axis (store stub flag).
755        let stubs = capped(
756            engine
757                .store()
758                .all_entities()
759                .filter(|e| e.stub && e.id.mem() == mem)
760                .map(|e| serde_json::json!({ "kind": "stub", "id": e.id.to_string() }))
761                .collect(),
762        );
763
764        // Anchors — same per-anchor mechanism as the anchors axis;
765        // only the never-confirmed and unreachable states are holes.
766        // A dangling sidecar row is a hole too, and
767        // it gets its OWN bucket. `unresolvable` is the wire form of the
768        // orphaned state, whose repair is the opposite one: an orphaned anchor
769        // asks whether its entity should be re-anchored or pruned, a dangling
770        // row asks why the entity went missing. Folding the two together here
771        // would reproduce, on the health axis, exactly the collapse the axis
772        // itself refuses.
773        //
774        // `entity_end_unreconciled` rides along both ways: an empty dangling
775        // bucket means "none found" only when the check could run at all.
776        let (mut recheck, mut unresolvable, mut unobserved, mut dangling_rows) =
777            (Vec::new(), Vec::new(), Vec::new(), Vec::new());
778        // Span rows whose quoted words are gone: the claim's basis moved,
779        // so someone has to re-read the source. Its own bucket, like the
780        // others: it is neither a gone artifact nor an unmeasured row.
781        let mut span_absent = Vec::new();
782        // Rows resting on a recorded observation older than today: open
783        // work too (someone has to look again), stated as its age.
784        let mut aging = Vec::new();
785        let mut entity_end_unreconciled: Option<String> = None;
786        if let Ok(report) = engine.verify_mem_anchors(mem) {
787            entity_end_unreconciled = report.unreconciled.clone();
788            for a in &report.anchors {
789                if let Some(days) = a.unobserved_for_days
790                    && days > 0
791                {
792                    aging.push(serde_json::json!({
793                        "kind": "anchor_aging",
794                        "id": a.entity_id,
795                        "artifact": a.artifact,
796                        "state": a.state,
797                        "observed_at": a.observed_at,
798                        "unobserved_for_days": days,
799                        "note": format!("unobserved for {days} days"),
800                    }));
801                }
802                let item = serde_json::json!({
803                    "kind": format!("anchor_{}", a.state),
804                    "id": a.entity_id,
805                    "artifact": a.artifact,
806                });
807                match a.state.as_str() {
808                    "recheck" => recheck.push(item),
809                    // The enum's wire name for a gone artifact; the bucket
810                    // keeps the axis's count name (`anchors_unresolvable`).
811                    "orphaned" => unresolvable.push(item),
812                    "span_absent" => span_absent.push(item),
813                    "unobserved" => unobserved.push(item),
814                    "dangling" => dangling_rows.push(item),
815                    _ => {}
816                }
817            }
818        }
819
820        // Unsatisfied constraints — same collector as the
821        // constraints axis.
822        let constraints = capped(
823            engine
824                .constraint_findings(Some(mem))
825                .iter()
826                .map(|r| {
827                    serde_json::json!({
828                        "kind": "unsatisfied_constraint",
829                        "id": r.id.to_string(),
830                        "violations": r.violations.len(),
831                    })
832                })
833                .collect(),
834        );
835
836        // Dangling links — same collector as the overview include, and the
837        // SAME three names rather than a parallel vocabulary of its own.
838        // This axis emitted one `dangling_link` kind
839        // over all three conditions, which is the fused code by another
840        // spelling; a second vocabulary is the one that drifts first.
841        let dangling = capped(
842            collect_dangling_links(engine.store(), Some(mem))
843                .iter()
844                .map(|d| {
845                    serde_json::json!({
846                        "kind": d.kind.code(),
847                        "id": d.from.to_string(),
848                        "target": d.target_id.to_string(),
849                        "repair": d.kind.repair(),
850                    })
851                })
852                .collect(),
853        );
854
855        // Paired process mems: open entries are work; negative
856        // findings are the opposite — already searched, keep off.
857        // Pairing runs through the ONE resolution function the brief
858        // renderer uses: a destination's
859        // declaration wins regardless of naming — and pairs even
860        // with no binding at all (the process tier stands without
861        // one); the binding-name convention remains the fallback. A
862        // declaration naming an unmounted mem is a typed finding,
863        // never a silent fallback.
864        let mut process = Vec::new();
865        let mem_bindings: Vec<&String> = bindings
866            .iter()
867            .filter(|(d, _)| d == mem)
868            .map(|(_, b)| b)
869            .collect();
870        let mut resolutions: Vec<(Option<String>, crate::binding_run::ProcessMemResolution)> =
871            Vec::new();
872        if mem_bindings.is_empty() {
873            let r = crate::binding_run::resolve_process_mem(engine, mem, "");
874            if r.declared {
875                resolutions.push((None, r));
876            }
877        } else {
878            for binding in &mem_bindings {
879                // `binding` is the stem; the convention derives from the
880                // canonical id `<mem>/<stem>`, the same input the brief
881                // renderer hands the derivation.
882                let derived =
883                    crate::binding_run::derived_process_mem_name(&format!("{mem}/{binding}"));
884                resolutions.push((
885                    Some((*binding).clone()),
886                    crate::binding_run::resolve_process_mem(engine, mem, &derived),
887                ));
888            }
889        }
890        for (binding, r) in resolutions {
891            if r.mounted {
892                let mut open = Vec::new();
893                let mut searched = Vec::new();
894                for e in engine
895                    .store()
896                    .all_entities()
897                    .filter(|e| !e.stub && e.id.mem() == r.mem.as_str())
898                {
899                    let item = serde_json::json!({
900                        "kind": e.entity_type,
901                        "id": e.id.to_string(),
902                        "title": e.title,
903                    });
904                    if e.entity_type == "negative_finding" {
905                        searched.push(item);
906                    } else {
907                        open.push(item);
908                    }
909                }
910                // The store iterates in hash order; a byte-parity gate over
911                // this axis (the CLI-versus-MCP pin, a fixture diff between
912                // two builds) needs the same bytes every run, so both lists
913                // are ordered by id before the cap takes the head.
914                let by_id = |a: &serde_json::Value, b: &serde_json::Value| {
915                    a["id"].as_str().cmp(&b["id"].as_str())
916                };
917                open.sort_by(by_id);
918                searched.sort_by(by_id);
919                process.push(serde_json::json!({
920                    "binding": binding,
921                    "process_mem": r.mem,
922                    "declared": r.declared,
923                    "resolvable": true,
924                    "open_entries": capped(open),
925                    "already_searched": capped(searched),
926                }));
927            } else if r.declared {
928                process.push(serde_json::json!({
929                    "binding": binding,
930                    "process_mem": r.mem,
931                    "declared": true,
932                    "resolvable": false,
933                    "finding": "DECLARED_PROCESS_MEM_MISSING",
934                }));
935            } else {
936                process.push(serde_json::json!({
937                    "binding": binding,
938                    "resolvable": false,
939                }));
940            }
941        }
942
943        // The resolution readings: for every type of this mem
944        // that declares `resolution`, the open entities with no condition
945        // written, and the open entities whose condition nobody has
946        // checked under the declared kind. The ledger is read as it is;
947        // an `x-` kind counts by name, an engine kind by derived state.
948        let (mut missing, mut unchecked) = (Vec::new(), Vec::new());
949        if let Some(schema) = engine.schema_for(mem) {
950            for entity in engine
951                .store()
952                .all_entities()
953                .filter(|e| !e.stub && e.id.mem() == mem)
954            {
955                let Some(td) = schema.types.get(&entity.entity_type) else {
956                    continue;
957                };
958                let Some(res) = &td.resolution else { continue };
959                if let Some(field) = &res.status_field {
960                    let open = match entity.metadata.get(field) {
961                        Some(crate::entity::MetadataValue::String(s)) => {
962                            res.open_values.contains(s)
963                        }
964                        _ => false,
965                    };
966                    if !open {
967                        continue;
968                    }
969                }
970                let has_condition = entity
971                    .sections
972                    .get(&res.condition_section)
973                    .is_some_and(|body| !body.trim().is_empty());
974                if !has_condition {
975                    missing.push(serde_json::json!({
976                        "kind": "resolution_missing",
977                        "id": entity.id.to_string(),
978                        "section": res.condition_section,
979                    }));
980                    continue;
981                }
982                let kind = res.check_kind.as_deref().unwrap_or("verification");
983                // The newest record of the declared kind, from the mount's
984                // one source (sealed member or workspace ledger), read the
985                // way the entity read derives its state.
986                let checked = crate::check::RecordKind::from_wire(kind).is_some()
987                    && engine
988                        .latest_check_record(mem, &entity.id.0, kind)
989                        .is_some_and(|r| r.verdict == "ok" && r.entity_hash == entity.content_hash);
990                if !checked {
991                    unchecked.push(serde_json::json!({
992                        "kind": "resolution_unchecked",
993                        "id": entity.id.to_string(),
994                        "section": res.condition_section,
995                        "check_kind": kind,
996                    }));
997                }
998            }
999        }
1000        let resolution_missing = capped(missing);
1001        let resolution_unchecked = capped(unchecked);
1002
1003        let total_open = stubs["count"].as_u64().unwrap_or(0)
1004            + resolution_missing["count"].as_u64().unwrap_or(0)
1005            + resolution_unchecked["count"].as_u64().unwrap_or(0)
1006            + recheck.len() as u64
1007            + unresolvable.len() as u64
1008            + span_absent.len() as u64
1009            + unobserved.len() as u64
1010            + dangling_rows.len() as u64
1011            + aging.len() as u64
1012            + constraints["count"].as_u64().unwrap_or(0)
1013            + dangling["count"].as_u64().unwrap_or(0)
1014            + process
1015                .iter()
1016                .filter_map(|p| p["open_entries"]["count"].as_u64())
1017                .sum::<u64>();
1018
1019        let mut entry = serde_json::Map::new();
1020        entry.insert("stubs".into(), stubs);
1021        entry.insert("anchors_recheck".into(), capped(recheck));
1022        entry.insert("anchors_unresolvable".into(), capped(unresolvable));
1023        entry.insert("anchors_span_absent".into(), capped(span_absent));
1024        // Its own bucket here too. The comment above argues that folding two
1025        // anchor conditions together reproduces the collapse the axis refuses,
1026        // and a first version then did exactly that eight lines further down.
1027        entry.insert("anchors_unobserved".into(), capped(unobserved));
1028        entry.insert("anchors_dangling".into(), capped(dangling_rows));
1029        entry.insert("anchors_aging".into(), capped(aging));
1030        if let Some(why) = entity_end_unreconciled {
1031            entry.insert("entity_end_unreconciled".into(), serde_json::json!(why));
1032        }
1033        entry.insert("unsatisfied_constraints".into(), constraints);
1034        entry.insert("dangling_links".into(), dangling);
1035        entry.insert("resolution_missing".into(), resolution_missing);
1036        entry.insert("resolution_unchecked".into(), resolution_unchecked);
1037        if !process.is_empty() {
1038            entry.insert("process".into(), serde_json::Value::Array(process));
1039        } else {
1040            // No binding targets this mem: the absence of a process
1041            // section is stated, never silent.
1042            entry.insert("process_mem_resolvable".into(), serde_json::json!(false));
1043        }
1044        entry.insert("total_open".into(), serde_json::json!(total_open));
1045        out.insert(mem.clone(), serde_json::Value::Object(entry));
1046    }
1047    let mut top = serde_json::Map::new();
1048    top.insert("_item_cap".into(), serde_json::json!(cap));
1049    for (k, v) in out {
1050        top.insert(k, v);
1051    }
1052    serde_json::Value::Object(top)
1053}
1054
1055pub fn health_anchors_axis(
1056    engine: &crate::engine::Engine,
1057    mem_filter: Option<&str>,
1058) -> serde_json::Value {
1059    let mut mems: Vec<String> = engine.mem_names().iter().map(|s| s.to_string()).collect();
1060    mems.retain(|m| mem_filter.is_none_or(|v| m == v));
1061    mems.sort();
1062    let mut out = serde_json::Map::new();
1063    for mem in mems {
1064        let Ok(report) = engine.verify_mem_anchors(&mem) else {
1065            continue;
1066        };
1067        let condition = report.sidecar_error.as_ref().map(|why| {
1068            serde_json::json!({
1069                "code": "ANCHORS_SIDECAR_UNREADABLE",
1070                "mem": mem,
1071                "reason": why,
1072            })
1073        });
1074        // The figure travels as its type's own three fields (`resolves`,
1075        // `population`, `fully_adjudicated`), merged into the row.
1076        let mut row = serde_json::json!({
1077                // The one condition that replaces the counts: an unreadable
1078                // sidecar. Absent when the sidecar read cleanly.
1079                "condition": condition,
1080                "drifted": report.drifted,
1081                "recheck": report.recheck,
1082                // Split from `unresolvable`: the artifact
1083                // being gone is a measurement, the pass not reaching it is the
1084                // absence of one, and this is the surface a reader arrives at
1085                // without a binding in hand.
1086                "unresolvable": report.unresolvable,
1087                // Span rows whose quoted words are gone from a document
1088                // that is still there.
1089                "span_absent": report.span_absent,
1090                "unobserved": report.unobserved,
1091                // The entity end (03/02). Carried here too, both ways: four
1092                // counts over a mem whose sidecar has outlived its entities
1093                // read as a healthy axis, and so does a zero over a mem whose
1094                // entity end was never reconciled.
1095                "dangling": report.dangling,
1096                "entity_end_unreconciled": report.unreconciled,
1097                // Rows whose state rests on a recorded observation (url
1098                // rows), each with how long it has gone unobserved. A state
1099                // observed months ago is not today's state, and the axis
1100                // says so beside the count it contributed to.
1101                "aging": report
1102                    .anchors
1103                    .iter()
1104                    .filter(|a| a.observed_at.is_some())
1105                    .map(|a| {
1106                        let days = a.unobserved_for_days.unwrap_or(0);
1107                        serde_json::json!({
1108                            "id": a.entity_id,
1109                            "artifact": a.artifact,
1110                            "state": a.state,
1111                            "observed_at": a.observed_at,
1112                            "unobserved_for_days": days,
1113                            "note": format!("unobserved for {days} days"),
1114                        })
1115                    })
1116                    .collect::<Vec<_>>(),
1117        });
1118        if let (Some(o), Ok(serde_json::Value::Object(f))) =
1119            (row.as_object_mut(), serde_json::to_value(&report.figure))
1120        {
1121            o.extend(f);
1122        }
1123        out.insert(mem, row);
1124    }
1125    serde_json::Value::Object(out)
1126}
1127
1128/// Compute health reports for all entities in the store.
1129///
1130/// `mem_schemas` maps mem name → `Arc<Schema>`. Entities whose mem
1131/// is missing from this map fall back to the builtin `default` schema
1132/// relationship vocabulary (keeps legacy fixtures green; real production
1133/// paths always register a mem schema).
1134///
1135/// `mem_filter` scopes the per-entity scans and the structural counts
1136/// (orphans, stubs, leaf population) to one mem; `None` is the classic
1137/// engine-wide sweep. Validating that the name exists is the caller's
1138/// job ([`crate::Engine::health_scoped`] refuses `UNKNOWN_MEM` before
1139/// reaching here) — an unknown name at this level just scans nothing.
1140pub fn compute_health(
1141    store: &Store,
1142    default_schema: &TypeDefinition,
1143    mem_schemas: &HashMap<String, Arc<Schema>>,
1144    mem_filter: Option<&str>,
1145) -> HealthSummary {
1146    let mut missing_fields = Vec::new();
1147    let mut stale_entities = Vec::new();
1148
1149    let today_days = days_since_epoch();
1150
1151    let in_scope = |mem: &str| mem_filter.is_none_or(|v| mem == v);
1152
1153    for entity in store.all_entities() {
1154        if entity.stub || !in_scope(&entity.mem) {
1155            continue;
1156        }
1157
1158        // Resolve the entity's `TypeDefinition` against the entity's
1159        // own mem's schema first. `type_by_name` only knows the
1160        // builtin `default` schema; falling through to it on a mem
1161        // pinned to a non-default schema (e.g. `planning@0.1.0`) would
1162        // silently use `default_schema` (effectively `spec`) for every
1163        // entity and report `spec`'s `health_required_fields` —
1164        // `[identity, purpose]` — even on entities of types like
1165        // `goal` / `option` / `decision`.
1166        let resolved = mem_schemas
1167            .get(entity.mem.as_str())
1168            .and_then(|s| s.types.get(entity.entity_type.as_str()).cloned())
1169            .or_else(|| type_by_name(&entity.entity_type));
1170        let schema: &TypeDefinition = resolved.as_deref().unwrap_or(default_schema);
1171        let mut issues = Vec::new();
1172
1173        // Check health_required_fields
1174        for field in &schema.health_required_fields {
1175            // Check if it's a section or metadata field
1176            if schema.section(field).is_some() {
1177                // It's a section. When the content is present in the
1178                // file but sits under a non-deriving heading, report
1179                // the distinct mismatch finding instead of "missing" —
1180                // the two conditions must never collapse.
1181                let content = entity.sections.get(field.as_str());
1182                if content.is_none_or(|c| c.trim().is_empty()) {
1183                    if let Some(issue) = section_heading_mismatch_issue(entity, schema, field) {
1184                        issues.push(issue);
1185                    } else {
1186                        issues.push(HealthIssue {
1187                            field: field.clone(),
1188                            code: super::HealthIssueCode::Missing,
1189                            message: format!("required section '{field}' is empty"),
1190                        });
1191                    }
1192                }
1193            } else {
1194                // It's a metadata field. Treat missing AND empty /
1195                // whitespace-only values as gaps so the scan matches
1196                // the section branch's `trim().is_empty()` semantics
1197                // — an empty `MetadataValue::String("")` is just as
1198                // unhelpful to an agent as an absent key.
1199                let value = entity.metadata.get(field.as_str());
1200                let is_empty = match value {
1201                    None => true,
1202                    Some(v) => v.to_frontmatter_string().trim().is_empty(),
1203                };
1204                if is_empty {
1205                    issues.push(HealthIssue {
1206                        field: field.clone(),
1207                        code: super::HealthIssueCode::Missing,
1208                        message: format!("required field '{field}' is missing"),
1209                    });
1210                }
1211            }
1212        }
1213
1214        // The heading-mismatch condition is drift worth surfacing on
1215        // every declared section, not only the health-required ones.
1216        for s in schema.sections.iter().filter(|s| !s.catch_all) {
1217            if schema.health_required_fields.contains(&s.key) {
1218                continue; // already handled above
1219            }
1220            let content = entity.sections.get(s.key.as_str());
1221            if content.is_none_or(|c| c.trim().is_empty())
1222                && let Some(issue) = section_heading_mismatch_issue(entity, schema, &s.key)
1223            {
1224                issues.push(issue);
1225            }
1226        }
1227
1228        // Undeclared-relationship warning. Scan the entity's
1229        // relationship list against the mem's schema vocabulary; every
1230        // unknown name becomes a soft HealthIssue (same severity as a
1231        // missing section) so agents running a health sweep after a
1232        // schema version bump see drift without a crashed load.
1233        //
1234        // Shape-violation scan: when the mem's schema declares
1235        // `source_types` / `target_types` on a relationship and an
1236        // existing edge violates the shape, surface as a soft
1237        // HealthIssue. The relate-add path enforces shape going
1238        // forward; this scan catches edges authored before the
1239        // constraint landed (or via inline `relations:` on
1240        // memstead_create, which does not yet shape-check). The
1241        // remove-path on `memstead_relate` skips shape validation so the
1242        // cleanup is always reachable.
1243        if let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) {
1244            let mut seen_unknown = std::collections::HashSet::new();
1245            for rel in &entity.relationships {
1246                if !mem_schema.relationship_known(&rel.rel_type) {
1247                    if seen_unknown.insert(rel.rel_type.clone()) {
1248                        let suggestion = mem_schema
1249                            .suggest_relationship(&rel.rel_type)
1250                            .map(|s| format!(" Did you mean '{s}'?"))
1251                            .unwrap_or_default();
1252                        let (schema_name, schema_version) = mem_schema.id();
1253                        issues.push(HealthIssue {
1254                            field: "relationships".to_string(),
1255                            code: super::HealthIssueCode::UndeclaredRelationship,
1256                            message: format!(
1257                                "relationship '{}' is not declared in schema \
1258                                 '{schema_name}@{schema_version}'.{suggestion}",
1259                                rel.rel_type
1260                            ),
1261                        });
1262                    }
1263                    continue;
1264                }
1265
1266                let target_type = store
1267                    .get(&rel.target)
1268                    .map(|t| t.entity_type.clone())
1269                    .filter(|t| !t.is_empty());
1270                if let Err(crate::runtime_validator::ValidationError::InvalidRelationshipShape {
1271                    rel_type,
1272                    from_type,
1273                    to_type,
1274                    allowed_source_types,
1275                    allowed_target_types,
1276                    ..
1277                }) = crate::runtime_validator::validate_rel_shape(
1278                    &rel.rel_type,
1279                    entity.entity_type.as_str(),
1280                    target_type.as_deref(),
1281                    mem_schema.as_ref(),
1282                ) {
1283                    let allowed_src = if allowed_source_types.is_empty() {
1284                        "<any>".to_string()
1285                    } else {
1286                        allowed_source_types.join(", ")
1287                    };
1288                    let allowed_tgt = if allowed_target_types.is_empty() {
1289                        "<any>".to_string()
1290                    } else {
1291                        allowed_target_types.join(", ")
1292                    };
1293                    issues.push(HealthIssue {
1294                        field: "relationships".to_string(),
1295                        code: super::HealthIssueCode::InvalidRelShape,
1296                        message: format!(
1297                            "INVALID_REL_SHAPE: edge '{rel_type}' from \
1298                             '{from_type}' to '{to_type}' (target {target}) \
1299                             violates declared shape — allowed_source_types: \
1300                             [{allowed_src}], allowed_target_types: \
1301                             [{allowed_tgt}]. Remove via \
1302                             `memstead_relate from={from_id} to={target} \
1303                             type={rel_type} remove=true`.",
1304                            target = rel.target,
1305                            from_id = entity.id,
1306                        ),
1307                    });
1308                }
1309            }
1310        }
1311
1312        // Staleness check
1313        let auto_ts_field = schema.metadata_fields.iter().find(|f| f.auto_timestamp);
1314
1315        if let Some(ts_field) = auto_ts_field
1316            && let Some(val) = entity.metadata.get(ts_field.key.as_str())
1317        {
1318            let date_str = val.to_frontmatter_string();
1319            if let Some(modified_days) = parse_iso_to_days(&date_str) {
1320                let days_since = today_days.saturating_sub(modified_days);
1321                if days_since > schema.staleness_threshold_days as u64 {
1322                    stale_entities.push(StaleEntity {
1323                        id: entity.id.clone(),
1324                        title: entity.title.clone(),
1325                        days_since_modified: days_since,
1326                        anchor_state: None,
1327                    });
1328                }
1329            }
1330        }
1331
1332        if !issues.is_empty() {
1333            // Compute a simple health score: (total_fields - issues) / total_fields.
1334            // `issues.len()` can exceed `total_fields` once the
1335            // relationship-vocabulary issues are added on top, so saturate
1336            // the subtraction rather than underflow. A score of 0.0 is the
1337            // natural floor — agents treat it as "maximally broken".
1338            let total = schema.health_required_fields.len();
1339            let score = if total > 0 {
1340                (total.saturating_sub(issues.len()) as f32) / (total as f32)
1341            } else {
1342                1.0
1343            };
1344
1345            missing_fields.push(HealthReport {
1346                id: entity.id.clone(),
1347                title: entity.title.clone(),
1348                score,
1349                issues,
1350            });
1351        }
1352    }
1353
1354    // Sort stale entities by days_since_modified descending
1355    stale_entities.sort_by_key(|e| std::cmp::Reverse(e.days_since_modified));
1356
1357    // Structural counts — scoped by the same filter as the entity scans
1358    // above so a `mem`-scoped summary is internally consistent.
1359    let orphan_count = query::find_orphans_with_schemas(store, mem_schemas)
1360        .into_iter()
1361        .filter(|id| store.get(id).is_some_and(|e| in_scope(&e.mem)))
1362        .count();
1363    let leaf_entities_by_type = match mem_filter {
1364        None => query::leaf_population(store, mem_schemas),
1365        Some(v) => {
1366            let scoped: HashMap<String, Arc<Schema>> = mem_schemas
1367                .iter()
1368                .filter(|(mem, _)| mem.as_str() == v)
1369                .map(|(mem, s)| (mem.clone(), s.clone()))
1370                .collect();
1371            query::leaf_population(store, &scoped)
1372        }
1373    };
1374    let stub_count = query::find_stubs(store)
1375        .iter()
1376        .filter(|(id, _)| store.get(id).is_some_and(|e| in_scope(&e.mem)))
1377        .count();
1378
1379    // The store iterates a hash map: order the per-entity lists by id so
1380    // two processes (the CLI and the MCP server) render the same bytes.
1381    stale_entities.sort_by(|a, b| a.id.0.cmp(&b.id.0));
1382    missing_fields.sort_by(|a, b| a.id.0.cmp(&b.id.0));
1383
1384    HealthSummary {
1385        stale_entities,
1386        anchor_fresh: Vec::new(),
1387        missing_fields,
1388        orphan_count,
1389        stub_count,
1390        warnings: Vec::new(),
1391        quarantined: Vec::new(),
1392        load_errors: Vec::new(),
1393        boot_diagnosis: None,
1394        leaf_entities_by_type,
1395        dangling_links: None,
1396        findings: None,
1397        tag_distribution: None,
1398        tag_distribution_folded: None,
1399        untagged_entities: None,
1400    }
1401}
1402
1403/// Scan every non-stub entity's `tags` metadata and aggregate (tag → count,
1404/// per-entity-type breakdown) plus untagged coverage. Comma-separated parser
1405/// with per-segment trim; empty segments drop. Comparison is case-sensitive
1406/// on the primary surface — case drift is surfaced separately via
1407/// [`TagDistribution`] siblings folded by the caller if desired.
1408///
1409/// `mem_filter` narrows both aggregation passes to entities in that mem;
1410/// `limit` caps the returned `tag_distribution` array after sorting by count
1411/// descending (tie-break by tag ascending for deterministic output).
1412///
1413/// Also returns `FoldedTag` entries for any canonical (lowercase) tag where
1414/// two or more authored casings appear — drift-flag only; empty when no
1415/// collisions exist.
1416pub fn collect_tag_distribution(
1417    store: &Store,
1418    mem_filter: Option<&str>,
1419    limit: usize,
1420) -> (Vec<TagDistribution>, Vec<FoldedTag>, UntaggedStats) {
1421    // tag → (count, per_type_count)
1422    let mut counts: HashMap<String, (usize, HashMap<String, usize>)> = HashMap::new();
1423    let mut untagged = UntaggedStats {
1424        total: 0,
1425        by_entity_type: HashMap::new(),
1426    };
1427
1428    for entity in store.all_entities() {
1429        if entity.stub {
1430            continue;
1431        }
1432        if let Some(v) = mem_filter
1433            && entity.mem != v
1434        {
1435            continue;
1436        }
1437
1438        let tags_raw = entity
1439            .metadata
1440            .get("tags")
1441            .and_then(|v| match v {
1442                MetadataValue::String(s) => Some(s.as_str()),
1443                _ => None,
1444            })
1445            .unwrap_or("");
1446
1447        let mut any_tag = false;
1448        for tag in tags_raw.split(',').map(str::trim).filter(|s| !s.is_empty()) {
1449            any_tag = true;
1450            let entry = counts
1451                .entry(tag.to_string())
1452                .or_insert_with(|| (0, HashMap::new()));
1453            entry.0 += 1;
1454            *entry.1.entry(entity.entity_type.clone()).or_insert(0) += 1;
1455        }
1456        if !any_tag {
1457            untagged.total += 1;
1458            *untagged
1459                .by_entity_type
1460                .entry(entity.entity_type.clone())
1461                .or_insert(0) += 1;
1462        }
1463    }
1464
1465    // Primary distribution — case-sensitive.
1466    let mut entries: Vec<TagDistribution> = counts
1467        .iter()
1468        .map(|(tag, (count, by_type))| TagDistribution {
1469            tag: tag.clone(),
1470            count: *count,
1471            by_entity_type: by_type.clone(),
1472        })
1473        .collect();
1474    entries.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.tag.cmp(&b.tag)));
1475    entries.truncate(limit);
1476
1477    // Case-drift sidecar: group by lowercase canonical; surface only entries
1478    // with ≥2 distinct authored casings. Operates on the full counts map, not
1479    // the truncated primary surface, so drift hidden below `limit` still
1480    // surfaces.
1481    let mut by_canonical: HashMap<String, Vec<(String, usize)>> = HashMap::new();
1482    for (tag, (count, _)) in counts.iter() {
1483        by_canonical
1484            .entry(tag.to_lowercase())
1485            .or_default()
1486            .push((tag.clone(), *count));
1487    }
1488    let mut folded: Vec<FoldedTag> = by_canonical
1489        .into_iter()
1490        .filter(|(_, v)| v.len() > 1)
1491        .map(|(canonical, mut variants)| {
1492            variants.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
1493            let total = variants.iter().map(|(_, c)| *c).sum();
1494            FoldedTag {
1495                canonical,
1496                total,
1497                variants: variants
1498                    .into_iter()
1499                    .map(|(tag, count)| TagVariant { tag, count })
1500                    .collect(),
1501            }
1502        })
1503        .collect();
1504    folded.sort_by(|a, b| {
1505        b.total
1506            .cmp(&a.total)
1507            .then_with(|| a.canonical.cmp(&b.canonical))
1508    });
1509
1510    (entries, folded, untagged)
1511}
1512
1513/// Collect the three separately-repaired conditions the diagnostic
1514/// covers, each tagged with its own [`DanglingLinkKind`]:
1515///
1516/// - `LinkTargetMissing` — a body wiki-link whose target has no markdown
1517///   file: either absent from the store entirely, or present only as a
1518///   stub. Repair: write the entity, or drop the link.
1519/// - `LinkNotRelated` — a body wiki-link to a fully written entity that
1520///   the referrer's relationships list omits (an alias orphan under the
1521///   alias model). The target is fine; the row is missing. Repair: a
1522///   write of the referrer re-synthesises the row.
1523/// - `RelationTargetMissing` — a `## Relationships` row naming an entity
1524///   absent from the store entirely, not even as a stub. Auto-stubbing
1525///   means this only arises from out-of-band file edits or historical
1526///   cross-mem corruption (an earlier mem-delete path). Repair: restore
1527///   the target or remove the edge.
1528///
1529/// The three used to share one code, and only the first was identifiable
1530/// from the payload; the other two were told apart, if at all, by
1531/// whether `section` happened to be null. `section` still marks the
1532/// source axis (`None` for the relationship table), but the condition is
1533/// named, not inferred.
1534///
1535/// `mem_filter` narrows *scanning* to entities in that mem; resolution
1536/// stays global so cross-mem links whose target is a real entity
1537/// elsewhere are not flagged as missing.
1538pub fn collect_dangling_links(store: &Store, mem_filter: Option<&str>) -> Vec<DanglingLink> {
1539    use crate::entity::parser::extract_inline_links_lenient;
1540    use std::collections::HashSet;
1541
1542    let mut out = Vec::new();
1543    for entity in store.all_entities() {
1544        if entity.stub {
1545            continue;
1546        }
1547        if let Some(v) = mem_filter
1548            && entity.mem != v
1549        {
1550            continue;
1551        }
1552        let explicit_targets: HashSet<_> = entity
1553            .relationships
1554            .iter()
1555            .map(|r| r.target.clone())
1556            .collect();
1557        for (section_key, section_body) in &entity.sections {
1558            for target_id in extract_inline_links_lenient(section_body, &entity.mem) {
1559                let target_missing = store.get(&target_id).map(|e| e.stub).unwrap_or(true);
1560                let alias_orphan = !target_missing && !explicit_targets.contains(&target_id);
1561                // The one place the three conditions are distinguished, so the
1562                // one place the discriminator is set. Consumers read `kind`;
1563                // none re-derives it against the store (04/06).
1564                let kind = if target_missing {
1565                    crate::ops::DanglingLinkKind::LinkTargetMissing
1566                } else {
1567                    crate::ops::DanglingLinkKind::LinkNotRelated
1568                };
1569                if target_missing || alias_orphan {
1570                    out.push(DanglingLink {
1571                        kind,
1572                        from: entity.id.clone(),
1573                        target_id: target_id.clone(),
1574                        target_path: target_id.path().to_string(),
1575                        section: Some(section_key.clone()),
1576                    });
1577                }
1578            }
1579        }
1580        // Relationship-table dangler scan. The `## Relationships`
1581        // section is structurally distinct from body sections — its
1582        // rows materialise from `entity.relationships` rather than a
1583        // free-text body — so `section: None` marks the source axis.
1584        //
1585        // Discrimination differs from the body scan: a relationship
1586        // target that resolves to a stub is a legitimate forward
1587        // reference (the alias machinery auto-stubs absent targets
1588        // by design), not corruption. Only a target that's *fully
1589        // absent* from the store — neither stub nor real — flags as
1590        // dangling. In practice this only fires for out-of-band file
1591        // edits or historical cross-mem-delete corruption that
1592        // dropped the stub along with the deleted mem.
1593        //
1594        // Dedup against the body-scan output so a target that
1595        // surfaces from both axes doesn't double-emit.
1596        for rel in &entity.relationships {
1597            if store.get(&rel.target).is_some() {
1598                continue;
1599            }
1600            let already_reported = out
1601                .iter()
1602                .any(|d| d.from == entity.id && d.target_id == rel.target);
1603            if already_reported {
1604                continue;
1605            }
1606            out.push(DanglingLink {
1607                kind: crate::ops::DanglingLinkKind::RelationTargetMissing,
1608                from: entity.id.clone(),
1609                target_id: rel.target.clone(),
1610                target_path: rel.target.path().to_string(),
1611                section: None,
1612            });
1613        }
1614    }
1615    // Deterministic output — the store iterates a HashMap, so without a
1616    // sort two identical runs can serve the same findings in different
1617    // orders. Sort by (from, target, section) so successive sweeps diff
1618    // cleanly.
1619    out.sort_by(|a, b| {
1620        (&a.from.0, &a.target_id.0, &a.section).cmp(&(&b.from.0, &b.target_id.0, &b.section))
1621    });
1622    out
1623}
1624
1625/// Collect every non-stub entity whose type declares `required_outgoing`
1626/// blocks that the entity's current outgoing edges leave unsatisfied.
1627/// Results are deterministic — sorted
1628/// by `(mem, id)` — so the agent can diff successive sweeps without
1629/// the underlying HashMap iteration order leaking through.
1630///
1631/// `mem_filter` narrows scanning to entities in that mem when set;
1632/// `mem_schemas` resolves the entity's type definition against the
1633/// mem's pinned schema. Entities whose mem has no schema in the
1634/// map are skipped (no schema → no `required_outgoing` to evaluate).
1635pub fn collect_missing_required_outgoing(
1636    store: &Store,
1637    mem_filter: Option<&str>,
1638    mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
1639) -> Vec<MissingRequiredOutgoingReport> {
1640    let mut out = Vec::new();
1641    for entity in store.all_entities() {
1642        if entity.stub {
1643            continue;
1644        }
1645        if let Some(v) = mem_filter
1646            && entity.mem != v
1647        {
1648            continue;
1649        }
1650        let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
1651            continue;
1652        };
1653        let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
1654            continue;
1655        };
1656        if td.required_outgoing.is_empty() {
1657            continue;
1658        }
1659        let unsatisfied = unsatisfied_required_outgoing(entity, td);
1660        if unsatisfied.is_empty() {
1661            continue;
1662        }
1663        out.push(MissingRequiredOutgoingReport {
1664            id: entity.id.clone(),
1665            title: entity.title.clone(),
1666            entity_type: entity.entity_type.clone(),
1667            mem: entity.mem.clone(),
1668            missing: unsatisfied,
1669        });
1670    }
1671    out.sort_by(|a, b| a.mem.cmp(&b.mem).then_with(|| a.id.0.cmp(&b.id.0)));
1672    out
1673}
1674
1675/// Evaluate one entity's declared `required_outgoing` blocks against
1676/// its current outgoing edges, returning the unsatisfied blocks in
1677/// declaration order. THE single evaluation — shared by the health
1678/// sweep ([`collect_missing_required_outgoing`]) and the per-mutation
1679/// `MISSING_REQUIRED_OUTGOING` warning on create/update. A second
1680/// implementation of the block check is a defect: the two surfaces
1681/// must never disagree about what counts as unsatisfied.
1682pub fn unsatisfied_required_outgoing(
1683    entity: &crate::entity::Entity,
1684    td: &TypeDefinition,
1685) -> Vec<super::MissingRequiredOutgoingBlock> {
1686    td.required_outgoing
1687        .iter()
1688        .filter(|block| {
1689            // A conditional block applies only while `when_field`
1690            // holds `when_value` (same comparison the `requires_when`
1691            // constraint uses). Unset field or any other value = the
1692            // block is unarmed and never unsatisfied.
1693            if let (Some(when_field), Some(when_value)) = (&block.when_field, &block.when_value) {
1694                let armed = entity
1695                    .metadata
1696                    .get(when_field.as_str())
1697                    .is_some_and(|v| v.to_frontmatter_string() == *when_value);
1698                if !armed {
1699                    return false;
1700                }
1701            }
1702            let count = entity
1703                .relationships
1704                .iter()
1705                .filter(|rel| block.relationships.iter().any(|name| name == &rel.rel_type))
1706                .count();
1707            !block.admits(count)
1708        })
1709        .map(|block| super::MissingRequiredOutgoingBlock {
1710            relationships: block.relationships.clone(),
1711            cardinality: block.cardinality.to_string(),
1712            severity: block.severity,
1713            when_field: block.when_field.clone(),
1714            when_value: block.when_value.clone(),
1715        })
1716        .collect()
1717}
1718
1719/// One violated declared constraint on one entity — the wire entry
1720/// shared by the write-path surface (the `CONSTRAINT_UNSATISFIED`
1721/// warning or refusal, tier decided by the declared severity) and the
1722/// health `constraints` include. The serde `kind` tag names the form;
1723/// the remaining fields restate the declaration (plus the observed
1724/// offense — the colliding entity, the unbacked value, the tainting
1725/// ancestor) so a consumer can repair without re-fetching the schema.
1726#[derive(Debug, Clone, serde::Serialize)]
1727#[serde(tag = "kind", rename_all = "snake_case")]
1728pub enum UnsatisfiedConstraint {
1729    RequiresWhen {
1730        field: String,
1731        when_field: String,
1732        when_value: String,
1733        severity: memstead_schema::ConstraintSeverity,
1734    },
1735    Unique {
1736        fields: Vec<String>,
1737        /// The entity's values for `fields`, in declaration order.
1738        values: Vec<String>,
1739        /// The other entity holding the same tuple (lexically smallest
1740        /// when several collide).
1741        colliding: String,
1742        severity: memstead_schema::ConstraintSeverity,
1743    },
1744    EnumFromNeighbour {
1745        field: String,
1746        /// The set value no reached neighbour's section backs.
1747        value: String,
1748        relationships: Vec<String>,
1749        section: String,
1750        severity: memstead_schema::ConstraintSeverity,
1751    },
1752    StatusPropagation {
1753        field: String,
1754        /// The terminal value the ancestor holds.
1755        value: String,
1756        /// The relation set the taint travels along.
1757        relationships: Vec<String>,
1758        /// The tainting ancestor — the entity holding the terminal
1759        /// value that this entity (transitively) reaches.
1760        tainted_by: String,
1761        /// The chain of ids the taint travelled, from `tainted_by` first
1762        /// to this entity last, one shortest path (a stub on the way is
1763        /// named: it carried the edge). A reader of a finding on an
1764        /// entity with several parents can say through which parent the
1765        /// fall arrived instead of guessing; with several fallen sources
1766        /// each finding carries its own path.
1767        path: Vec<String>,
1768        severity: memstead_schema::ConstraintSeverity,
1769    },
1770    /// Form 6 — the entity holds the gated `to_value` while related
1771    /// entities lack a fresh confirming check record.
1772    TransitionRequiresChecks {
1773        field: String,
1774        to_value: String,
1775        relationships: Vec<String>,
1776        direction: memstead_schema::ReachDirection,
1777        /// Every related entity NOT at derived state `checked_ok`,
1778        /// each with the state it derived, sorted by id.
1779        unchecked: Vec<UncheckedRelated>,
1780        /// How many related entities the declared edges reach.
1781        related: usize,
1782        /// The declared floor; a violation with `related < min_related`
1783        /// is the vacuous case the floor exists to refuse.
1784        min_related: usize,
1785        severity: memstead_schema::ConstraintSeverity,
1786    },
1787    /// Form 7 — the entity holds the gated `to_value` while it carries
1788    /// no fresh, independent, confirming check record of `check_kind`.
1789    TransitionRequiresSelfCheck {
1790        field: String,
1791        to_value: String,
1792        check_kind: String,
1793        /// The standing the entity's own record derived instead of an
1794        /// independent `checked_ok` (`never_checked`, `check_stale`,
1795        /// `check_failed`, `self_checked`, `unconfirmable`).
1796        state: String,
1797        /// On a refused transition write: what the write changed beside
1798        /// the gated field and the engine-stamped timestamps
1799        /// (`section:<key>`, `metadata:<key>`, `title`, `type`,
1800        /// `relationships`). A self-check transition write may change
1801        /// nothing else, because the record it rests on checked the
1802        /// content as stored. Empty on the health axis.
1803        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1804        changed: Vec<String>,
1805        severity: memstead_schema::ConstraintSeverity,
1806    },
1807    /// The entity reaches no non-stub entity of a terminal type along
1808    /// the declared relation set — the declaration is echoed whole so
1809    /// the reader sees which obligation went unmet without re-fetching
1810    /// the schema. Health-sweep only, always warn-tier.
1811    MustReach {
1812        relationships: Vec<String>,
1813        direction: memstead_schema::ReachDirection,
1814        terminal_types: Vec<String>,
1815        #[serde(skip_serializing_if = "Option::is_none")]
1816        max_depth: Option<u32>,
1817        severity: memstead_schema::ConstraintSeverity,
1818    },
1819}
1820
1821impl UnsatisfiedConstraint {
1822    pub fn severity(&self) -> memstead_schema::ConstraintSeverity {
1823        match self {
1824            Self::RequiresWhen { severity, .. }
1825            | Self::Unique { severity, .. }
1826            | Self::EnumFromNeighbour { severity, .. }
1827            | Self::StatusPropagation { severity, .. }
1828            | Self::MustReach { severity, .. }
1829            | Self::TransitionRequiresChecks { severity, .. }
1830            | Self::TransitionRequiresSelfCheck { severity, .. } => *severity,
1831        }
1832    }
1833
1834    /// One-line human rendering for warning/refusal message text.
1835    pub fn describe(&self) -> String {
1836        match self {
1837            Self::RequiresWhen {
1838                field,
1839                when_field,
1840                when_value,
1841                ..
1842            } => format!(
1843                "requires_when: '{field}' is required when {when_field}={when_value} and is unset"
1844            ),
1845            Self::Unique {
1846                fields, colliding, ..
1847            } => format!(
1848                "unique: tuple ({}) collides with '{colliding}'",
1849                fields.join(", ")
1850            ),
1851            Self::EnumFromNeighbour {
1852                field,
1853                value,
1854                relationships,
1855                section,
1856                ..
1857            } => format!(
1858                "enum_from_neighbour: '{field}' value '{value}' has no backing entry in any \
1859                 `{section}` section reached via {}",
1860                relationships.join(", ")
1861            ),
1862            Self::StatusPropagation {
1863                field,
1864                value,
1865                tainted_by,
1866                path,
1867                ..
1868            } => {
1869                format!(
1870                    "status_propagation: tainted by '{tainted_by}' ({field}={value}) via {}",
1871                    path.join(" → ")
1872                )
1873            }
1874            Self::MustReach {
1875                relationships,
1876                direction,
1877                terminal_types,
1878                max_depth,
1879                ..
1880            } => {
1881                let depth = match max_depth {
1882                    Some(d) => format!(" within {d} hop(s)"),
1883                    None => String::new(),
1884                };
1885                format!(
1886                    "must_reach: no path via [{}] ({direction}) reaches a [{}] entity{depth}",
1887                    relationships.join(", "),
1888                    terminal_types.join(", ")
1889                )
1890            }
1891            Self::TransitionRequiresChecks {
1892                field,
1893                to_value,
1894                relationships,
1895                unchecked,
1896                related,
1897                min_related,
1898                ..
1899            } => {
1900                if related < min_related {
1901                    return format!(
1902                        "transition_requires_checks: {field}={to_value} requires at least \
1903                         {min_related} related entit{} via [{}] — found {related}",
1904                        if *min_related == 1 { "y" } else { "ies" },
1905                        relationships.join(", ")
1906                    );
1907                }
1908                let listed: Vec<String> = unchecked
1909                    .iter()
1910                    .map(|u| format!("'{}' ({})", u.id, u.state))
1911                    .collect();
1912                format!(
1913                    "transition_requires_checks: {field}={to_value} requires a fresh confirming \
1914                     check record on every entity related via [{}] — unconfirmed: {}",
1915                    relationships.join(", "),
1916                    listed.join(", ")
1917                )
1918            }
1919            Self::TransitionRequiresSelfCheck {
1920                field,
1921                to_value,
1922                check_kind,
1923                state,
1924                changed,
1925                ..
1926            } => {
1927                let mut m = format!(
1928                    "transition_requires_self_check: {field}={to_value} requires a fresh confirming \
1929                     `{check_kind}` check record on this entity under an identity other than its \
1930                     author — derived: {state}"
1931                );
1932                if !changed.is_empty() {
1933                    m.push_str(&format!(
1934                        "; the write also changes {}, and a self-check transition write may \
1935                         change nothing but `{field}`: write those changes first, check the \
1936                         result, then set `{field}`",
1937                        changed.join(", ")
1938                    ));
1939                }
1940                m
1941            }
1942        }
1943    }
1944}
1945
1946/// One related entity blocking a `transition_requires_checks` gate:
1947/// its id and the derived verification state it reads instead of the
1948/// required `checked_ok`.
1949#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
1950pub struct UncheckedRelated {
1951    pub id: String,
1952    pub state: String,
1953}
1954
1955/// The gated-transition evaluators' window into the check ledger:
1956/// the derived standing of one entity's newest check record of one
1957/// wire kind (`verification`, `conformance`, or a foreign `x-<name>`).
1958/// Callers with an engine build it from the workspace check ledger;
1959/// `None` (no ledger access — a workspace-less engine, or a call path
1960/// that cannot reach one) derives every entity as `never_checked`, so
1961/// a declared gate refuses honestly rather than passing unverified.
1962pub type CheckStateProvider<'a> =
1963    &'a dyn Fn(&crate::entity::Entity, &str) -> crate::engine::independence::CheckStanding;
1964
1965/// Evaluate one entity's declared per-entity `constraints` against its
1966/// current state (and, for the store-aware forms, against the rest of
1967/// its mem), returning the violated ones in declaration order. THE
1968/// single evaluation — shared by the health sweep
1969/// ([`collect_constraint_findings`]) and the per-mutation
1970/// `CONSTRAINT_UNSATISFIED` surface on create/update/relate; a second
1971/// implementation of any form is a defect.
1972///
1973/// Form semantics:
1974/// - `requires_when` triggers when `when_field`'s frontmatter value
1975///   equals `when_value` exactly; a triggered constraint is satisfied
1976///   when `field` — a metadata field or a section key — is present
1977///   with non-blank content.
1978/// - `unique`: the entity's tuple of `fields` values (skipped when any
1979///   field is unset/blank) must not equal another non-stub entity's
1980///   tuple within the same mem and type. `exclude` names the entity's
1981///   own id so an update does not collide with its stored self.
1982/// - `enum_from_neighbour`: a set `field` value must appear as a
1983///   bullet entry (`- value` / `* value` line) in the `section` body
1984///   of at least one entity reached via an outgoing edge of one of `relationships`.
1985/// - `status_propagation` is a reachability property of the graph,
1986///   not of one write — it is evaluated only by the health sweep
1987///   ([`collect_constraint_findings`]), never here.
1988pub fn unsatisfied_constraints(
1989    store: &Store,
1990    entity: &crate::entity::Entity,
1991    td: &TypeDefinition,
1992    exclude: Option<&crate::entity::EntityId>,
1993    checks: Option<CheckStateProvider<'_>>,
1994) -> Vec<UnsatisfiedConstraint> {
1995    use memstead_schema::ConstraintDef;
1996    td.constraints
1997        .iter()
1998        .filter_map(|c| match c {
1999            ConstraintDef::RequiresWhen {
2000                field,
2001                when_field,
2002                when_value,
2003                severity,
2004            } => {
2005                let triggered = entity
2006                    .metadata
2007                    .get(when_field.as_str())
2008                    .is_some_and(|v| v.to_frontmatter_string() == *when_value);
2009                if !triggered {
2010                    return None;
2011                }
2012                let satisfied = entity
2013                    .metadata
2014                    .get(field.as_str())
2015                    .is_some_and(|v| !v.to_frontmatter_string().trim().is_empty())
2016                    || entity
2017                        .sections
2018                        .get(field.as_str())
2019                        .is_some_and(|body| !body.trim().is_empty());
2020                if satisfied {
2021                    return None;
2022                }
2023                Some(UnsatisfiedConstraint::RequiresWhen {
2024                    field: field.clone(),
2025                    when_field: when_field.clone(),
2026                    when_value: when_value.clone(),
2027                    severity: *severity,
2028                })
2029            }
2030            ConstraintDef::Unique { fields, severity } => {
2031                let tuple = tuple_of(entity, fields)?;
2032                let mut colliding: Vec<&str> = store
2033                    .all_entities()
2034                    .filter(|other| {
2035                        !other.stub
2036                            && other.mem == entity.mem
2037                            && other.entity_type == entity.entity_type
2038                            && Some(&other.id) != exclude
2039                            && other.id != entity.id
2040                            && tuple_of(other, fields).as_ref() == Some(&tuple)
2041                    })
2042                    .map(|other| other.id.0.as_str())
2043                    .collect();
2044                colliding.sort_unstable();
2045                let first = colliding.first()?;
2046                Some(UnsatisfiedConstraint::Unique {
2047                    fields: fields.clone(),
2048                    values: tuple,
2049                    colliding: first.to_string(),
2050                    severity: *severity,
2051                })
2052            }
2053            ConstraintDef::EnumFromNeighbour {
2054                field,
2055                relationships,
2056                section,
2057                severity,
2058            } => {
2059                let value = entity
2060                    .metadata
2061                    .get(field.as_str())
2062                    .map(|v| v.to_frontmatter_string())
2063                    .filter(|v| !v.trim().is_empty())?;
2064                let backed = entity
2065                    .relationships
2066                    .iter()
2067                    .filter(|rel| relationships.contains(&rel.rel_type))
2068                    .filter_map(|rel| store.get(&rel.target))
2069                    .filter_map(|neighbour| neighbour.sections.get(section.as_str()))
2070                    .any(|body| bullet_entries(body).contains(&value));
2071                if backed {
2072                    return None;
2073                }
2074                Some(UnsatisfiedConstraint::EnumFromNeighbour {
2075                    field: field.clone(),
2076                    value,
2077                    relationships: relationships.clone(),
2078                    section: section.clone(),
2079                    severity: *severity,
2080                })
2081            }
2082            ConstraintDef::StatusPropagation { .. } => None,
2083            ConstraintDef::TransitionRequiresChecks {
2084                field,
2085                to_value,
2086                relationships,
2087                direction,
2088                min_related,
2089                severity,
2090            } => {
2091                let triggered = entity
2092                    .metadata
2093                    .get(field.as_str())
2094                    .is_some_and(|v| v.to_frontmatter_string() == *to_value);
2095                if !triggered {
2096                    return None;
2097                }
2098                let (related, unchecked) = transition_gate_standing(
2099                    store,
2100                    entity,
2101                    relationships,
2102                    *direction,
2103                    exclude,
2104                    checks,
2105                );
2106                if unchecked.is_empty() && related >= *min_related {
2107                    return None;
2108                }
2109                Some(UnsatisfiedConstraint::TransitionRequiresChecks {
2110                    field: field.clone(),
2111                    to_value: to_value.clone(),
2112                    relationships: relationships.clone(),
2113                    direction: *direction,
2114                    unchecked,
2115                    related,
2116                    min_related: *min_related,
2117                    severity: *severity,
2118                })
2119            }
2120            ConstraintDef::TransitionRequiresSelfCheck {
2121                field,
2122                to_value,
2123                check_kind,
2124                severity,
2125            } => {
2126                let triggered = entity
2127                    .metadata
2128                    .get(field.as_str())
2129                    .is_some_and(|v| v.to_frontmatter_string() == *to_value);
2130                if !triggered {
2131                    return None;
2132                }
2133                // The entity's own record of the declared kind, read
2134                // through the same provider form 6 reads related
2135                // entities with: no ledger derives never_checked, the
2136                // author's own ok reads self_checked, neither confirms.
2137                let standing = match checks {
2138                    Some(provider) => provider(entity, check_kind),
2139                    None => crate::engine::independence::CheckStanding {
2140                        state: crate::check::CheckState::NeverChecked,
2141                        independence: None,
2142                        role: crate::vcs::Role::Unspecified,
2143                    },
2144                };
2145                if standing.confirms() {
2146                    return None;
2147                }
2148                Some(UnsatisfiedConstraint::TransitionRequiresSelfCheck {
2149                    field: field.clone(),
2150                    to_value: to_value.clone(),
2151                    check_kind: check_kind.clone(),
2152                    state: standing.label().to_string(),
2153                    changed: Vec::new(),
2154                    severity: *severity,
2155                })
2156            }
2157        })
2158        .collect()
2159}
2160
2161/// The standing of one gated-transition constraint's related set
2162/// against one entity, independent of whether the entity currently
2163/// holds the gated value: `(total related, those lacking a fresh
2164/// confirming check record)`, the unconfirmed sorted by id. THE single
2165/// related-set enumeration — shared by the write-time evaluator arm
2166/// above and the gates-brief renderer, so the brief can never disagree
2167/// with the refusal. Outgoing reads the entity's own edges (its
2168/// written state); incoming scans the store for edge sources pointing
2169/// at it, excluding the entity's own stored copy (`exclude`) so an
2170/// update never gates on its pre-write self.
2171pub fn transition_gate_standing(
2172    store: &Store,
2173    entity: &crate::entity::Entity,
2174    relationships: &[String],
2175    direction: memstead_schema::ReachDirection,
2176    exclude: Option<&crate::entity::EntityId>,
2177    checks: Option<CheckStateProvider<'_>>,
2178) -> (usize, Vec<UncheckedRelated>) {
2179    let related: Vec<&crate::entity::Entity> = match direction {
2180        memstead_schema::ReachDirection::Out => entity
2181            .relationships
2182            .iter()
2183            .filter(|rel| relationships.contains(&rel.rel_type))
2184            .filter_map(|rel| store.get(&rel.target))
2185            .collect(),
2186        memstead_schema::ReachDirection::In => store
2187            .all_entities()
2188            .filter(|other| {
2189                other.id != entity.id
2190                    && Some(&other.id) != exclude
2191                    && other
2192                        .relationships
2193                        .iter()
2194                        .any(|rel| rel.target == entity.id && relationships.contains(&rel.rel_type))
2195            })
2196            .collect(),
2197    };
2198    let total = related.len();
2199    let mut unchecked: Vec<UncheckedRelated> = related
2200        .into_iter()
2201        .filter_map(|rel_entity| {
2202            // An ok check confirms only when it is independent of the
2203            // executors (engine::independence): the executor's own ok
2204            // reads `self_checked` here and does not close the gate.
2205            let standing = match checks {
2206                Some(provider) => {
2207                    provider(rel_entity, crate::check::CheckKind::Verification.as_str())
2208                }
2209                None => crate::engine::independence::CheckStanding {
2210                    state: crate::check::CheckState::NeverChecked,
2211                    independence: None,
2212                    role: crate::vcs::Role::Unspecified,
2213                },
2214            };
2215            if standing.confirms() {
2216                None
2217            } else {
2218                Some(UncheckedRelated {
2219                    id: rel_entity.id.0.clone(),
2220                    state: standing.label().to_string(),
2221                })
2222            }
2223        })
2224        .collect();
2225    unchecked.sort_by(|a, b| a.id.cmp(&b.id));
2226    (total, unchecked)
2227}
2228
2229/// The entity's tuple of frontmatter values for `fields`, in
2230/// declaration order — `None` when any field is unset or blank (no
2231/// tuple, nothing to compare).
2232fn tuple_of(entity: &crate::entity::Entity, fields: &[String]) -> Option<Vec<String>> {
2233    fields
2234        .iter()
2235        .map(|f| {
2236            entity
2237                .metadata
2238                .get(f.as_str())
2239                .map(|v| v.to_frontmatter_string())
2240                .filter(|v| !v.trim().is_empty())
2241        })
2242        .collect()
2243}
2244
2245/// The bullet entries of a section body — trimmed text of `- item` /
2246/// `* item` lines. The legal-value shape `enum_from_neighbour` reads.
2247fn bullet_entries(body: &str) -> Vec<String> {
2248    // A bullet inside a code block is an example of the list, not a
2249    // member of it — the same referee every other content reader uses
2250    // ([`crate::markdown`]). Masking preserves byte offsets and line
2251    // count, so each masked line pairs with its original.
2252    let masked = crate::markdown::mask_code_blocks_and_spans(body);
2253    body.lines()
2254        .zip(masked.lines())
2255        .filter_map(|(line, masked_line)| {
2256            let m = masked_line.trim_start();
2257            if m.starts_with("- ") || m.starts_with("* ") {
2258                let t = line.trim_start();
2259                t.strip_prefix("- ")
2260                    .or_else(|| t.strip_prefix("* "))
2261                    .map(|e| e.trim().to_string())
2262            } else {
2263                None
2264            }
2265        })
2266        .collect()
2267}
2268
2269/// One entity's violated declared constraints, surfaced from the
2270/// health-time scan (`include=["constraints"]`). Mirrors
2271/// [`MissingRequiredOutgoingReport`]'s envelope shape — the two
2272/// includes read the same way.
2273#[derive(Debug, Clone, serde::Serialize)]
2274pub struct ConstraintFindingReport {
2275    pub id: crate::entity::EntityId,
2276    pub title: String,
2277    pub entity_type: String,
2278    pub mem: String,
2279    pub violations: Vec<UnsatisfiedConstraint>,
2280    /// Standing violations of the entity's declared section formats
2281    /// (additive: consumers of the pre-format shape see an
2282    /// absent key, never an empty list.
2283    #[serde(skip_serializing_if = "Vec::is_empty")]
2284    pub format_violations: Vec<crate::section_format::SectionFormatViolation>,
2285}
2286
2287/// Collect every non-stub entity whose declared `constraints` its
2288/// current state violates. Two passes: the per-entity forms
2289/// (`requires_when`, `unique`, `enum_from_neighbour`) through the
2290/// shared [`unsatisfied_constraints`] evaluation, then the
2291/// `status_propagation` graph sweep — for each entity holding a
2292/// declared terminal value, every entity reaching it (transitively)
2293/// via the declared rel-type and direction gains a finding naming that
2294/// tainting ancestor. Deterministic — reports sorted by `(mem, id)`,
2295/// violations in declaration order then by tainting ancestor.
2296pub fn collect_constraint_findings(
2297    store: &Store,
2298    mem_filter: Option<&str>,
2299    mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
2300    checks: Option<CheckStateProvider<'_>>,
2301) -> Vec<ConstraintFindingReport> {
2302    use memstead_schema::ConstraintDef;
2303    type Bucket = (
2304        Vec<UnsatisfiedConstraint>,
2305        Vec<crate::section_format::SectionFormatViolation>,
2306    );
2307    let mut by_entity: std::collections::BTreeMap<String, Bucket> = Default::default();
2308
2309    // Reverse adjacency for `must_reach` incoming walks — built once
2310    // per sweep, and only when some pinned schema declares one (a
2311    // workspace without the form pays nothing).
2312    let needs_reverse = mem_schemas.values().any(|s| {
2313        s.types.values().any(|t| {
2314            t.must_reach
2315                .iter()
2316                .any(|ob| ob.direction == memstead_schema::ReachDirection::In)
2317        })
2318    });
2319    let reverse: ReverseIndex = if needs_reverse {
2320        build_reverse_index(store)
2321    } else {
2322        ReverseIndex::default()
2323    };
2324
2325    for entity in store.all_entities() {
2326        if entity.stub {
2327            continue;
2328        }
2329        if let Some(v) = mem_filter
2330            && entity.mem != v
2331        {
2332            continue;
2333        }
2334        let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
2335            continue;
2336        };
2337        let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
2338            continue;
2339        };
2340
2341        // Section-format sweep — standing violations of a
2342        // declared markdown shape, every severity (block-tier
2343        // pre-existing violations are health findings too; the next
2344        // write of the section is the sanctioned repair point).
2345        for def in &td.sections {
2346            if def.compiled_content.is_none() {
2347                continue;
2348            }
2349            let Some(body) = entity.sections.get(def.key.as_str()) else {
2350                continue;
2351            };
2352            let violations = crate::section_format::check_section_format(def, body);
2353            if !violations.is_empty() {
2354                by_entity
2355                    .entry(entity.id.0.clone())
2356                    .or_default()
2357                    .1
2358                    .extend(violations);
2359            }
2360        }
2361
2362        // Reachability obligations — health-sweep only by design (no
2363        // single write completes a transitive absence, so the write
2364        // path never evaluates these). The finding echoes the whole
2365        // declaration.
2366        for ob in &td.must_reach {
2367            if !reaches_terminal(store, &reverse, &entity.id, ob) {
2368                by_entity.entry(entity.id.0.clone()).or_default().0.push(
2369                    UnsatisfiedConstraint::MustReach {
2370                        relationships: ob.relationships.clone(),
2371                        direction: ob.direction,
2372                        terminal_types: ob.terminal_types.clone(),
2373                        max_depth: ob.max_depth,
2374                        severity: ob.severity,
2375                    },
2376                );
2377            }
2378        }
2379
2380        if td.constraints.is_empty() {
2381            continue;
2382        }
2383
2384        // Pass 1 — per-entity forms.
2385        let violations = unsatisfied_constraints(store, entity, td, None, checks);
2386        if !violations.is_empty() {
2387            by_entity
2388                .entry(entity.id.0.clone())
2389                .or_default()
2390                .0
2391                .extend(violations);
2392        }
2393    }
2394
2395    // Pass 2 — every entity as a taint source, whatever mem it lives
2396    // in: it holds a declared terminal value, so sweep its dependents.
2397    // The taint walks the declared relation set's union subgraph (a
2398    // single `rel_type` is a one-element set) and crosses mem
2399    // boundaries like any walk here; the mem filter narrows which
2400    // TAINTED entities are reported, never which sources are swept.
2401    // Folded into the per-entity loop above, the filter skipped a
2402    // source in another mem before its dependents in the filtered mem
2403    // were ever computed, so a mem resting on a fallen card elsewhere
2404    // read clean under `--mem` and tainted without it. Sources are
2405    // swept in id order, so an entity tainted by several ancestors
2406    // carries its findings in the same order on every run.
2407    let mut sources: Vec<&crate::entity::Entity> =
2408        store.all_entities().filter(|e| !e.stub).collect();
2409    sources.sort_by(|a, b| a.id.0.cmp(&b.id.0));
2410    for entity in sources {
2411        let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
2412            continue;
2413        };
2414        let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
2415            continue;
2416        };
2417        for c in &td.constraints {
2418            let ConstraintDef::StatusPropagation {
2419                field,
2420                value,
2421                relationships,
2422                direction,
2423                severity,
2424            } = c
2425            else {
2426                continue;
2427            };
2428            let terminal = entity
2429                .metadata
2430                .get(field.as_str())
2431                .is_some_and(|v| v.to_frontmatter_string() == *value);
2432            if !terminal {
2433                continue;
2434            }
2435            for (tainted, path) in reach_transitively(store, &entity.id, relationships, *direction)
2436            {
2437                if let Some(v) = mem_filter
2438                    && tainted.mem() != v
2439                {
2440                    continue;
2441                }
2442                by_entity.entry(tainted.0.clone()).or_default().0.push(
2443                    UnsatisfiedConstraint::StatusPropagation {
2444                        field: field.clone(),
2445                        value: value.clone(),
2446                        relationships: relationships.clone(),
2447                        tainted_by: entity.id.to_string(),
2448                        path: path.iter().map(ToString::to_string).collect(),
2449                        severity: *severity,
2450                    },
2451                );
2452            }
2453        }
2454    }
2455
2456    let mut out: Vec<ConstraintFindingReport> = by_entity
2457        .into_iter()
2458        .filter_map(|(id, (violations, format_violations))| {
2459            let id = crate::entity::EntityId(id);
2460            let entity = store.get(&id)?;
2461            Some(ConstraintFindingReport {
2462                id,
2463                title: entity.title.clone(),
2464                entity_type: entity.entity_type.clone(),
2465                mem: entity.mem.clone(),
2466                violations,
2467                format_violations,
2468            })
2469        })
2470        .collect();
2471    out.sort_by(|a, b| a.mem.cmp(&b.mem).then_with(|| a.id.0.cmp(&b.id.0)));
2472    out
2473}
2474
2475/// Transitive reachability along one rel-type from `start`, excluding
2476/// `start` itself, each reached entity with the path the walk took to
2477/// it (`start` first, the entity last). `In` walks against edge
2478/// direction (the entities whose `rel_type` edges point at the frontier
2479/// — "what stands on this"); `Out` follows the frontier's own
2480/// edges. Breadth first with neighbours in id order, so the path is one
2481/// shortest path and the same one on every run. Stubs are traversed (an
2482/// edge through a stub still transmits the taint) and named on the
2483/// paths that cross them, but stubs themselves are not returned.
2484fn reach_transitively(
2485    store: &Store,
2486    start: &crate::entity::EntityId,
2487    rel_types: &[String],
2488    direction: memstead_schema::ReachDirection,
2489) -> Vec<(crate::entity::EntityId, Vec<crate::entity::EntityId>)> {
2490    use memstead_schema::ReachDirection;
2491    let mut parent: std::collections::HashMap<crate::entity::EntityId, crate::entity::EntityId> =
2492        Default::default();
2493    let mut seen: std::collections::HashSet<crate::entity::EntityId> =
2494        std::iter::once(start.clone()).collect();
2495    let mut frontier = std::collections::VecDeque::from([start.clone()]);
2496    let mut reached = Vec::new();
2497    while let Some(current) = frontier.pop_front() {
2498        let mut next: Vec<crate::entity::EntityId> = match direction {
2499            ReachDirection::In => store
2500                .all_entities()
2501                .filter(|e| {
2502                    e.relationships
2503                        .iter()
2504                        .any(|r| rel_types.iter().any(|n| n == &r.rel_type) && r.target == current)
2505                })
2506                .map(|e| e.id.clone())
2507                .collect(),
2508            ReachDirection::Out => store
2509                .get(&current)
2510                .map(|e| {
2511                    e.relationships
2512                        .iter()
2513                        .filter(|r| rel_types.iter().any(|n| n == &r.rel_type))
2514                        .map(|r| r.target.clone())
2515                        .collect()
2516                })
2517                .unwrap_or_default(),
2518        };
2519        next.sort_by(|a, b| a.0.cmp(&b.0));
2520        for id in next {
2521            if seen.insert(id.clone()) {
2522                parent.insert(id.clone(), current.clone());
2523                if store.get(&id).is_some_and(|e| !e.stub) {
2524                    let mut path = vec![id.clone()];
2525                    let mut at = id.clone();
2526                    while let Some(p) = parent.get(&at) {
2527                        path.push(p.clone());
2528                        at = p.clone();
2529                    }
2530                    path.reverse();
2531                    reached.push((id.clone(), path));
2532                }
2533                frontier.push_back(id);
2534            }
2535        }
2536    }
2537    reached
2538}
2539
2540/// Reverse adjacency for `must_reach` incoming walks: target id →
2541/// `(rel_type, source id)` pairs. Built once per sweep so the
2542/// incoming direction stays O(edges) instead of re-scanning the store
2543/// per frontier node.
2544type ReverseIndex =
2545    std::collections::HashMap<crate::entity::EntityId, Vec<(String, crate::entity::EntityId)>>;
2546
2547fn build_reverse_index(store: &Store) -> ReverseIndex {
2548    let mut idx = ReverseIndex::default();
2549    for entity in store.all_entities() {
2550        for rel in &entity.relationships {
2551            idx.entry(rel.target.clone())
2552                .or_default()
2553                .push((rel.rel_type.clone(), entity.id.clone()));
2554        }
2555    }
2556    idx
2557}
2558
2559/// Whether `start` reaches at least one non-stub entity of a terminal
2560/// type along the obligation's relation set, direction, and depth
2561/// bound. Breadth-first with visited-set discipline (cycles along the
2562/// walked set terminate); stubs terminate no obligation — they carry
2563/// no outgoing edges and never count as reached terminals. Cross-mem
2564/// edges are followed like any edge, matching the propagation walk
2565/// and the cycle check (the engine's established traversal posture);
2566/// the start entity itself never satisfies its own obligation.
2567fn reaches_terminal(
2568    store: &Store,
2569    reverse: &ReverseIndex,
2570    start: &crate::entity::EntityId,
2571    ob: &memstead_schema::MustReach,
2572) -> bool {
2573    use memstead_schema::ReachDirection;
2574    let mut seen: std::collections::HashSet<crate::entity::EntityId> =
2575        std::iter::once(start.clone()).collect();
2576    let mut frontier = vec![start.clone()];
2577    let mut depth: u32 = 0;
2578    while !frontier.is_empty() {
2579        if let Some(max) = ob.max_depth
2580            && depth >= max
2581        {
2582            return false;
2583        }
2584        depth += 1;
2585        let mut next_frontier = Vec::new();
2586        for current in frontier {
2587            let next: Vec<crate::entity::EntityId> = match ob.direction {
2588                ReachDirection::Out => store
2589                    .get(&current)
2590                    .map(|e| {
2591                        e.relationships
2592                            .iter()
2593                            .filter(|r| ob.relationships.iter().any(|n| n == &r.rel_type))
2594                            .map(|r| r.target.clone())
2595                            .collect()
2596                    })
2597                    .unwrap_or_default(),
2598                ReachDirection::In => reverse
2599                    .get(&current)
2600                    .map(|sources| {
2601                        sources
2602                            .iter()
2603                            .filter(|(rel, _)| ob.relationships.iter().any(|n| n == rel))
2604                            .map(|(_, src)| src.clone())
2605                            .collect()
2606                    })
2607                    .unwrap_or_default(),
2608            };
2609            for id in next {
2610                if seen.insert(id.clone()) {
2611                    if store.get(&id).is_some_and(|e| {
2612                        !e.stub && ob.terminal_types.iter().any(|t| t == &e.entity_type)
2613                    }) {
2614                        return true;
2615                    }
2616                    next_frontier.push(id);
2617                }
2618            }
2619        }
2620        frontier = next_frontier;
2621    }
2622    false
2623}
2624
2625/// One entity's above-`none` signals, surfaced from the include-gated
2626/// `signals` health axis. Mirrors [`ConstraintFindingReport`]'s
2627/// envelope shape; the `signals` entries carry value, level, and
2628/// contributors (the evidence ships with the number, always).
2629#[derive(Debug, Clone, serde::Serialize)]
2630pub struct SignalReport {
2631    pub id: crate::entity::EntityId,
2632    pub title: String,
2633    pub entity_type: String,
2634    pub mem: String,
2635    /// Only signals whose level is not `none`, in declaration order.
2636    pub signals: Vec<super::signals::ComputedSignal>,
2637}
2638
2639impl SignalReport {
2640    /// Whether any entry is `warn`-level — the `--strict`
2641    /// participation test (a `notice` never participates; that is the
2642    /// whole difference between the two levels).
2643    pub fn has_warn(&self) -> bool {
2644        self.signals
2645            .iter()
2646            .any(|s| s.level == Some(memstead_schema::SignalLevel::Warn))
2647    }
2648}
2649
2650/// Collect every non-stub entity carrying at least one declared
2651/// signal above `none`. Deterministic — sorted by `(mem, id)`;
2652/// signals in declaration order, contributors sorted.
2653pub fn collect_signal_reports(
2654    store: &Store,
2655    mem_filter: Option<&str>,
2656    mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
2657) -> Vec<SignalReport> {
2658    let mut out = Vec::new();
2659    for entity in store.all_entities() {
2660        if entity.stub {
2661            continue;
2662        }
2663        if let Some(v) = mem_filter
2664            && entity.mem != v
2665        {
2666            continue;
2667        }
2668        let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
2669            continue;
2670        };
2671        let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
2672            continue;
2673        };
2674        if td.signals.is_empty() {
2675            continue;
2676        }
2677        let above: Vec<super::signals::ComputedSignal> =
2678            super::signals::compute_signals(store, td, &entity.id)
2679                .into_iter()
2680                .filter(|s| s.level.is_some())
2681                .collect();
2682        if above.is_empty() {
2683            continue;
2684        }
2685        out.push(SignalReport {
2686            id: entity.id.clone(),
2687            title: entity.title.clone(),
2688            entity_type: entity.entity_type.clone(),
2689            mem: entity.mem.clone(),
2690            signals: above,
2691        });
2692    }
2693    out.sort_by(|a, b| a.mem.cmp(&b.mem).then_with(|| a.id.0.cmp(&b.id.0)));
2694    out
2695}
2696
2697/// A defective section-format declaration a loaded schema carries
2698/// (recorded by the lenient boot path; install would have refused).
2699/// Surfaced under the health `constraints` include so a sealed schema
2700/// with a bad declaration is visible without bricking boot.
2701#[derive(Debug, Clone, serde::Serialize)]
2702pub struct SchemaFormatDefect {
2703    pub schema: String,
2704    pub type_name: String,
2705    pub section: String,
2706    pub problems: Vec<String>,
2707}
2708
2709/// Collect the defective section-format declarations across the
2710/// mounted mems' pinned schemas, deduplicated per schema ref,
2711/// deterministic order.
2712pub fn collect_schema_format_defects(
2713    mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
2714) -> Vec<SchemaFormatDefect> {
2715    let mut seen: std::collections::BTreeSet<String> = Default::default();
2716    let mut out = Vec::new();
2717    let mut schemas: Vec<&Arc<memstead_schema::Schema>> = mem_schemas.values().collect();
2718    schemas.sort_by_key(|s| (s.manifest.name.clone(), s.version.clone()));
2719    for schema in schemas {
2720        let schema_ref = format!("{}@{}", schema.manifest.name, schema.version);
2721        if !seen.insert(schema_ref.clone()) {
2722            continue;
2723        }
2724        for td in schema.types.values() {
2725            for section in &td.sections {
2726                if !section.format_problems.is_empty() {
2727                    out.push(SchemaFormatDefect {
2728                        schema: schema_ref.clone(),
2729                        type_name: td.name.clone(),
2730                        section: section.key.clone(),
2731                        problems: section.format_problems.clone(),
2732                    });
2733                }
2734            }
2735        }
2736    }
2737    out.sort_by(|a, b| {
2738        (&a.schema, &a.type_name, &a.section).cmp(&(&b.schema, &b.type_name, &b.section))
2739    });
2740    out
2741}
2742
2743/// One entity's unsatisfied `required_outgoing` blocks, surfaced from
2744/// the health-time scan. `missing` reuses the per-write warning's wire
2745/// block type — one struct, one serialized shape (`{ relationships,
2746/// cardinality }`) on both surfaces — and adds the `mem` name (the
2747/// warning's `entity_id` already encodes it via the mem prefix, but
2748/// health is multi-mem by default and an explicit field is cheaper for
2749/// downstream filters).
2750#[derive(Debug, Clone, serde::Serialize)]
2751pub struct MissingRequiredOutgoingReport {
2752    pub id: crate::entity::EntityId,
2753    pub title: String,
2754    pub entity_type: String,
2755    pub mem: String,
2756    pub missing: Vec<super::MissingRequiredOutgoingBlock>,
2757}
2758
2759/// Render the workspace-config projection the health surface serves —
2760/// per-writable-mem detail (`origin`, storage/durability, `vcs`
2761/// `gitdir`/`worktree`/`head`, title/subject, `write_guidance`,
2762/// `extra`) plus the `mutations` and `plugin` policy values. One
2763/// implementation, every surface: the MCP composer reaches it through
2764/// `include_config: true` OR the `config` include key; the CLI through
2765/// `--include config`. `mutations` / `plugin` are passed prebuilt so a
2766/// server that owns its own copies inserts them verbatim; callers
2767/// without server state derive them from `Engine::settings()` (see
2768/// [`config_projection_from_settings`]). Returns the three top-level
2769/// entries (`mems`, `mutations`, `plugin`) for the caller to merge —
2770/// callers gate on their own opt-in flag and must render at most once.
2771pub fn config_projection(
2772    engine: &crate::Engine,
2773    writable_mems: &[String],
2774    mutations: serde_json::Value,
2775    plugin: serde_json::Value,
2776) -> serde_json::Map<String, serde_json::Value> {
2777    // Per-mem storage backend → durability marker, derived from the
2778    // mount's `MountStorage` kind. Lives alongside `vcs` so an agent
2779    // reading per-mem config learns whether a `write_id` this mem
2780    // returns is durable-on-disk or volatile-in-RAM.
2781    let backend_by_mem: std::collections::HashMap<&str, (&'static str, bool)> = engine
2782        .mounts()
2783        .iter()
2784        .map(|m| {
2785            (
2786                m.mem.as_str(),
2787                (m.storage.backend_id(), m.storage.is_durable()),
2788            )
2789        })
2790        .collect();
2791    let mems_detail: Vec<serde_json::Value> = writable_mems
2792        .iter()
2793        .map(|name| {
2794            let origin = engine
2795                .mem_router()
2796                .origin_for_mem(name)
2797                .map(|o| o.kind())
2798                .unwrap_or("explicit");
2799            let mut entry = serde_json::Map::new();
2800            entry.insert("name".into(), serde_json::json!(name));
2801            entry.insert("origin".into(), serde_json::json!(origin));
2802            if let Some((storage, durable)) = backend_by_mem.get(name.as_str()).copied() {
2803                entry.insert("storage".into(), serde_json::json!(storage));
2804                entry.insert("durable".into(), serde_json::json!(durable));
2805            }
2806            let mut vcs_obj = serde_json::Map::new();
2807            if let Ok(gitdir) = engine.gitdir_for(name) {
2808                vcs_obj.insert("gitdir".into(), serde_json::json!(gitdir));
2809            }
2810            if let Ok(worktree) = engine.worktree_for(name) {
2811                vcs_obj.insert("worktree".into(), serde_json::json!(worktree));
2812            }
2813            if let Some(sha) = engine.mem_head_sha(name).ok().flatten() {
2814                vcs_obj.insert("head".into(), serde_json::json!(sha));
2815            }
2816            if !vcs_obj.is_empty() {
2817                entry.insert("vcs".into(), serde_json::Value::Object(vcs_obj));
2818            }
2819            if let Some(cfg) = engine.mem_config_for(name) {
2820                // Display title + subject block, when set — the
2821                // config projection prefers the title wherever a
2822                // mem is printed; the name stays the identity.
2823                if let Some(title) = &cfg.title {
2824                    entry.insert("title".into(), serde_json::json!(title));
2825                }
2826                if let Some(subject) = &cfg.subject {
2827                    entry.insert("subject".into(), serde_json::json!(subject));
2828                }
2829                let guidance = serde_json::Map::from_iter(
2830                    cfg.write_guidance
2831                        .iter()
2832                        .map(|(k, v)| (k.clone(), v.clone())),
2833                );
2834                entry.insert("write_guidance".into(), serde_json::Value::Object(guidance));
2835                let extra = serde_json::Map::from_iter(
2836                    cfg.extra.iter().map(|(k, v)| (k.clone(), v.clone())),
2837                );
2838                entry.insert("extra".into(), serde_json::Value::Object(extra));
2839            }
2840            serde_json::Value::Object(entry)
2841        })
2842        .collect();
2843
2844    let mut out = serde_json::Map::new();
2845    out.insert("mems".into(), serde_json::json!(mems_detail));
2846    out.insert("mutations".into(), mutations);
2847    out.insert("plugin".into(), plugin);
2848    out
2849}
2850
2851/// The `(mutations, plugin)` pair for [`config_projection`], derived
2852/// from the engine's own [`crate::workspace::WorkspaceSettings`] — for
2853/// callers (the CLI) that carry no server-owned config copies. Produces
2854/// the same bytes the MCP server passes when both were loaded from the
2855/// same `workspace.toml`.
2856pub fn config_projection_from_settings(
2857    settings: &crate::workspace::WorkspaceSettings,
2858) -> (serde_json::Value, serde_json::Value) {
2859    let mutations = serde_json::json!({ "require_notes": settings.mutations.require_notes });
2860    let plugin_map: serde_json::Map<String, serde_json::Value> = settings
2861        .plugin
2862        .iter()
2863        .map(|(k, v)| {
2864            (
2865                k.clone(),
2866                serde_json::to_value(v).unwrap_or(serde_json::Value::Null),
2867            )
2868        })
2869        .collect();
2870    (mutations, serde_json::Value::Object(plugin_map))
2871}
2872
2873/// Detect the section-fork condition for one declared section: the
2874/// parsed content under `key` is empty, the schema's declared heading
2875/// for the key does not derive back to it
2876/// (`derive_section_key(heading) != key`), and the file carries that
2877/// declared heading — so the content is present in the file but
2878/// unreachable under the key: absorbed into the catch-all when the
2879/// type declares one, dropped from the parsed sections otherwise.
2880///
2881/// Returns the distinct `SECTION_HEADING_MISMATCH` issue naming both
2882/// the found heading and what a deriving heading would look like. The
2883/// caller must NOT also report the section as missing — collapsing the
2884/// two conditions into the missing-section report is exactly the
2885/// misdirection this finding exists to prevent (the operator goes
2886/// hunting for absent content that is in fact present).
2887pub(crate) fn section_heading_mismatch_issue(
2888    entity: &crate::entity::Entity,
2889    schema: &TypeDefinition,
2890    key: &str,
2891) -> Option<HealthIssue> {
2892    let def = schema.section(key)?;
2893    let derived = memstead_schema::derive_section_key(&def.heading);
2894    if derived == key {
2895        return None;
2896    }
2897    if !entity
2898        .raw_section_headings
2899        .iter()
2900        .any(|h| h == &def.heading)
2901    {
2902        return None;
2903    }
2904    let landing = match schema.catch_all_section() {
2905        Some(c) => format!(
2906            "the content was absorbed into catch-all section '{}'",
2907            c.key
2908        ),
2909        None => "the content is unreachable under any declared key".to_string(),
2910    };
2911    Some(HealthIssue {
2912        field: key.to_string(),
2913        code: super::HealthIssueCode::SectionHeadingMismatch,
2914        message: format!(
2915            "SECTION_HEADING_MISMATCH: section '{key}' is not missing — its content sits \
2916             under heading '{found}', which derives to '{derived}', not '{key}'; {landing}. \
2917             The schema's declared heading cannot round-trip to its key (expected a heading \
2918             that derives to '{key}'); fix the schema's heading/key pair — new installs of \
2919             such a schema are refused",
2920            found = def.heading,
2921        ),
2922    })
2923}
2924
2925/// Get a single entity's health report.
2926pub fn entity_health(entity: &crate::entity::Entity, schema: &TypeDefinition) -> HealthReport {
2927    let mut issues = Vec::new();
2928
2929    for field in &schema.health_required_fields {
2930        if schema.section(field).is_some() {
2931            let content = entity.sections.get(field.as_str());
2932            if content.is_none_or(|c| c.trim().is_empty()) {
2933                if let Some(issue) = section_heading_mismatch_issue(entity, schema, field) {
2934                    issues.push(issue);
2935                } else {
2936                    issues.push(HealthIssue {
2937                        field: field.clone(),
2938                        code: super::HealthIssueCode::Missing,
2939                        message: format!("required section '{field}' is empty"),
2940                    });
2941                }
2942            }
2943        } else {
2944            let value = entity.metadata.get(field.as_str());
2945            if value.is_none() {
2946                issues.push(HealthIssue {
2947                    field: field.clone(),
2948                    code: super::HealthIssueCode::Missing,
2949                    message: format!("required field '{field}' is missing"),
2950                });
2951            }
2952        }
2953    }
2954
2955    // The mismatch condition is drift worth surfacing on every declared
2956    // section, not only the health-required ones — an optional section
2957    // whose content forked away is just as invisible to readers.
2958    for s in schema.sections.iter().filter(|s| !s.catch_all) {
2959        if schema.health_required_fields.contains(&s.key) {
2960            continue; // already handled above
2961        }
2962        let content = entity.sections.get(s.key.as_str());
2963        if content.is_none_or(|c| c.trim().is_empty())
2964            && let Some(issue) = section_heading_mismatch_issue(entity, schema, &s.key)
2965        {
2966            issues.push(issue);
2967        }
2968    }
2969
2970    let total = schema.health_required_fields.len();
2971    let score = if total > 0 {
2972        (total.saturating_sub(issues.len()) as f32) / (total as f32)
2973    } else {
2974        1.0
2975    };
2976
2977    HealthReport {
2978        id: entity.id.clone(),
2979        title: entity.title.clone(),
2980        score,
2981        issues,
2982    }
2983}
2984
2985// ---------------------------------------------------------------------------
2986// Date helpers
2987// ---------------------------------------------------------------------------
2988
2989/// Get current days since Unix epoch.
2990///
2991/// `SystemTime::now()` is unimplemented on `wasm32-unknown-unknown` —
2992/// it traps with `RuntimeError: unreachable` and poisons the wasm
2993/// instance — so the wasm build reads the JS-backed
2994/// clock instead. Same value, same summary shape on every target.
2995/// The `MEMSTEAD_TODAY=YYYY-MM-DD` clock pin, when set to a civil date:
2996/// the one pin every date-dependent reading takes (the due brief, the
2997/// health due axis, the staleness clock, the anchors overlay).
2998pub fn pinned_today() -> Option<String> {
2999    let raw = std::env::var("MEMSTEAD_TODAY").ok()?;
3000    crate::engine::due::pinned_days_since_epoch(&raw)?;
3001    Some(raw)
3002}
3003
3004/// Today as whole days since the Unix epoch, the clock every day-threshold
3005/// reading in health uses. `MEMSTEAD_TODAY=YYYY-MM-DD` pins it (the
3006/// injection a fixture needs to age entities without waiting), honoured
3007/// by every binary alike so the CLI and the MCP server read the same day.
3008pub fn days_since_epoch() -> u64 {
3009    if let Some(pinned) = std::env::var("MEMSTEAD_TODAY")
3010        .ok()
3011        .and_then(|s| crate::engine::due::pinned_days_since_epoch(&s))
3012    {
3013        return pinned;
3014    }
3015    #[cfg(target_arch = "wasm32")]
3016    {
3017        (js_sys::Date::now() / 1000.0) as u64 / 86400
3018    }
3019    #[cfg(not(target_arch = "wasm32"))]
3020    {
3021        std::time::SystemTime::now()
3022            .duration_since(std::time::UNIX_EPOCH)
3023            .unwrap_or_default()
3024            .as_secs()
3025            / 86400
3026    }
3027}
3028
3029/// Parse an ISO 8601 date string to days since epoch.
3030/// Supports `YYYY-MM-DD` and `YYYY-MM-DDTHH:MM:SSZ`.
3031pub fn parse_iso_to_days(date: &str) -> Option<u64> {
3032    let date_part = date.split('T').next()?;
3033    let parts: Vec<&str> = date_part.split('-').collect();
3034    if parts.len() != 3 {
3035        return None;
3036    }
3037    let year: u64 = parts[0].parse().ok()?;
3038    let month: u64 = parts[1].parse().ok()?;
3039    let day: u64 = parts[2].parse().ok()?;
3040    Some(ymd_to_days(year, month, day))
3041}
3042
3043/// Convert (year, month, day) to days since Unix epoch.
3044/// Inverse of the algorithm in generator.rs.
3045fn ymd_to_days(year: u64, month: u64, day: u64) -> u64 {
3046    // Algorithm from http://howardhinnant.github.io/date_algorithms.html
3047    let y = if month <= 2 { year - 1 } else { year };
3048    let m = if month <= 2 { month + 9 } else { month - 3 };
3049    let era = y / 400;
3050    let yoe = y - era * 400;
3051    let doy = (153 * m + 2) / 5 + day - 1;
3052    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
3053    let days = era * 146097 + doe;
3054    days - 719468
3055}
3056
3057#[cfg(test)]
3058mod tests;