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 (A6, 2026-09-02): per mem, the
61/// cheap, engine-countable model-truth signals the remodel campaign
62/// specified — each a count plus a capped list with an explicit `more`
63/// remainder, never a verdict, threshold or recommendation (the engine
64/// names what is there; 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::ingest::cursor::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 `include=["checks"]` axis: per mem,
331/// counts of the four derived check states plus the author≠checker
332/// independence gate over ok-checked entities. The gate compares
333/// caller-declared IDENTITIES and nothing else:
334/// the entity's created-by record against its newest ok-check record
335/// — both carry an identity and they are equal → `self_checked`
336/// ("twice-asserted, not verified"); both carry one and they differ →
337/// `confirmed_independent`; either side lacks one → `unconfirmable`,
338/// never a guessed category. Transport is not identity: the recorded
339/// `(actor, client)` pair names the SURFACE a record arrived through
340/// and is recorded as context only — it never participates in the
341/// comparison (a same pair does not establish the same actor, and
342/// different pairs do not establish different actors). An identity is
343/// an honesty device, not authentication: caller-declared, unverified,
344/// tamper-evident in append-only history — a consistent multi-agent
345/// setup gets real independence signals, and a lying setup defeats
346/// only itself. Derivation only: nothing here is stamped, and a
347/// workspace without a check ledger serves all-never-checked.
348/// Identity lists are capped at [`OPEN_QUESTIONS_ITEM_CAP`] with an
349/// explicit `more` count.
350pub fn health_checks_axis(
351    engine: &crate::engine::Engine,
352    mem_filter: Option<&str>,
353) -> serde_json::Value {
354    let cap = OPEN_QUESTIONS_ITEM_CAP;
355    let capped = |mut items: Vec<String>| -> serde_json::Value {
356        items.sort();
357        let count = items.len();
358        let more = count.saturating_sub(cap);
359        items.truncate(cap);
360        let mut o = serde_json::Map::new();
361        o.insert("count".into(), serde_json::json!(count));
362        o.insert("items".into(), serde_json::json!(items));
363        if more > 0 {
364            o.insert("more".into(), serde_json::json!(more));
365        }
366        serde_json::Value::Object(o)
367    };
368
369    let ledger = engine
370        .workspace_root()
371        .map(crate::check::CheckLedger::for_workspace);
372    // Newest record per (entity, kind), one ledger read for the whole
373    // axis. State is kind-scoped: a conformance record never
374    // supersedes a verification record, or the reverse.
375    let mut latest: std::collections::BTreeMap<String, crate::check::CheckRecord> =
376        std::collections::BTreeMap::new();
377    let mut latest_conformance: std::collections::BTreeMap<String, crate::check::CheckRecord> =
378        std::collections::BTreeMap::new();
379    // Foreign `x-<name>` kinds: recorded verbatim, never aggregated into
380    // a state — listed by count per mem so a reader sees that another
381    // checker has been here. Keyed by entity for the per-mem tally.
382    let mut foreign_by_entity: std::collections::BTreeMap<String, Vec<String>> =
383        std::collections::BTreeMap::new();
384    // The newest record of ANY kind per entity, for the finding it may
385    // carry: a finding is served under the entity's latest verdict.
386    let mut newest_any: std::collections::BTreeMap<String, crate::check::CheckRecord> =
387        std::collections::BTreeMap::new();
388    // Every verification record per entity, oldest first: the per-record
389    // readings (engine::independence) show each check's standing, not
390    // only the newest one's — a superseded self-check stays visible.
391    let mut all_verification: std::collections::BTreeMap<String, Vec<crate::check::CheckRecord>> =
392        std::collections::BTreeMap::new();
393    if let Some(l) = &ledger {
394        for rec in l.all() {
395            newest_any.insert(rec.entity.clone(), rec.clone());
396            match rec.resolved_kind() {
397                Some(crate::check::CheckKind::Verification) => {
398                    all_verification
399                        .entry(rec.entity.clone())
400                        .or_default()
401                        .push(rec.clone());
402                    latest.insert(rec.entity.clone(), rec);
403                }
404                Some(crate::check::CheckKind::Conformance) => {
405                    latest_conformance.insert(rec.entity.clone(), rec);
406                }
407                None => {
408                    if let Some(k) = rec.foreign_kind() {
409                        foreign_by_entity
410                            .entry(rec.entity.clone())
411                            .or_default()
412                            .push(k.to_string());
413                    }
414                }
415            }
416        }
417    }
418
419    let mut mems: Vec<String> = engine.mem_names().iter().map(|s| s.to_string()).collect();
420    mems.sort();
421    let mut out = serde_json::Map::new();
422    for mem in mems {
423        if let Some(f) = mem_filter
424            && f != mem
425        {
426            continue;
427        }
428        let mut counts = std::collections::BTreeMap::from([
429            ("never_checked", 0usize),
430            ("checked_ok", 0usize),
431            ("check_failed", 0usize),
432            ("check_stale", 0usize),
433        ]);
434        // The `conformance` kind's counts, additively beside the
435        // verification counts. Pin-aware: a schema re-pin stales
436        // every conformance verdict recorded under the old pin. A
437        // workspace with no conformance records serves all
438        // `never_checked` — honestly empty, never absent.
439        let current_pin = engine
440            .mount(&mem)
441            .and_then(|m| m.schema.as_ref())
442            .map(|s| s.as_display());
443        let mut conformance_counts = std::collections::BTreeMap::from([
444            ("never_checked", 0usize),
445            ("checked_ok", 0usize),
446            ("check_failed", 0usize),
447            ("check_stale", 0usize),
448        ]);
449        let mut self_checked: Vec<String> = Vec::new();
450        let mut confirmed_independent: Vec<String> = Vec::new();
451        let mut unconfirmable: Vec<String> = Vec::new();
452        // Which identities each ok-checked criterion was compared against
453        // (engine::independence), rendered so a reader can see who counted
454        // as an executor. One provenance pass per mem.
455        let mut executors = serde_json::Map::new();
456        let mut readings = serde_json::Map::new();
457        let touches = engine.mem_touches(&mem);
458        let mut foreign_kinds: std::collections::BTreeMap<String, usize> =
459            std::collections::BTreeMap::new();
460        let mut findings = serde_json::Map::new();
461        for e in engine.store().all_entities().filter(|e| e.mem == mem) {
462            let id = e.id.0.clone();
463            if let Some(kinds) = foreign_by_entity.get(&id) {
464                for k in kinds {
465                    *foreign_kinds.entry(k.clone()).or_insert(0) += 1;
466                }
467            }
468            if let Some(rec) = newest_any.get(&id)
469                && let Some(f) = &rec.finding
470            {
471                findings.insert(
472                    id.clone(),
473                    serde_json::json!({
474                        "verdict": rec.verdict,
475                        "kind": rec.kind.as_deref().unwrap_or("verification"),
476                        "ts": rec.ts,
477                        "identity": rec.identity,
478                        "finding": f,
479                    }),
480                );
481            }
482            let state = crate::check::derive_state(latest.get(&id), &e.content_hash);
483            *counts.entry(state.as_str()).or_insert(0) += 1;
484            if let Some(records) = all_verification.get(&id) {
485                let rows: Vec<serde_json::Value> = records
486                    .iter()
487                    .map(|rec| {
488                        let reading = if rec.verdict == "ok" {
489                            engine.independence_of(e, rec, &touches).0.as_str()
490                        } else {
491                            "failed"
492                        };
493                        serde_json::json!({
494                            "ts": rec.ts,
495                            "identity": rec.identity,
496                            "verdict": rec.verdict,
497                            "reading": reading,
498                        })
499                    })
500                    .collect();
501                readings.insert(id.clone(), serde_json::Value::Array(rows));
502            }
503            let cstate = crate::check::derive_state_pinned(
504                latest_conformance.get(&id),
505                &e.content_hash,
506                current_pin.as_deref(),
507            );
508            *conformance_counts.entry(cstate.as_str()).or_insert(0) += 1;
509            if state != crate::check::CheckState::CheckedOk {
510                continue;
511            }
512            // Identity-only comparison (plan 15, comparator widened
513            // 2026-09-02): the newest ok-check's identity against every
514            // identity that mutated the verified plan, its criteria or
515            // its session-log notes since this criterion was written
516            // (engine::independence); a non-criterion compares against
517            // its own author. The (actor, client) transport pair is
518            // recorded context and never a comparator. Either side
519            // lacking an identity is unconfirmable, never a guessed
520            // category.
521            let check = latest.get(&id).expect("checked_ok implies a record");
522            let (reading, execs) = engine.independence_of(e, check, &touches);
523            if let Some(execs) = execs {
524                executors.insert(id.clone(), serde_json::json!(execs.identities));
525            }
526            match reading {
527                crate::engine::independence::Independence::SelfChecked => self_checked.push(id),
528                crate::engine::independence::Independence::ConfirmedIndependent => {
529                    confirmed_independent.push(id)
530                }
531                crate::engine::independence::Independence::Unconfirmable => unconfirmable.push(id),
532            }
533        }
534        let mut m = serde_json::Map::new();
535        for (k, v) in counts {
536            m.insert(k.to_string(), serde_json::json!(v));
537        }
538        let mut c = serde_json::Map::new();
539        for (k, v) in conformance_counts {
540            c.insert(k.to_string(), serde_json::json!(v));
541        }
542        m.insert("conformance".into(), serde_json::Value::Object(c));
543        // Foreign kinds by count, and the structured finding each
544        // entity's newest record carries — recorded, rendered, never
545        // interpreted.
546        m.insert(
547            "foreign_kinds".into(),
548            serde_json::to_value(&foreign_kinds).unwrap_or(serde_json::json!({})),
549        );
550        m.insert("findings".into(), serde_json::Value::Object(findings));
551        m.insert(
552            "independence".into(),
553            serde_json::json!({
554                "self_checked": capped(self_checked),
555                "confirmed_independent": capped(confirmed_independent),
556                "unconfirmable": capped(unconfirmable),
557                "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 its own author",
558                "executors": serde_json::Value::Object(executors),
559                "readings": serde_json::Value::Object(readings),
560            }),
561        );
562        out.insert(mem, serde_json::Value::Object(m));
563    }
564    serde_json::Value::Object(out)
565}
566
567/// One derivation-staleness finding: an
568/// explicit edge on a derivation-declared rel-type whose baseline
569/// differs from the target's current hash (`stale`), or that has no
570/// recorded baseline at all (`unbaselined`). Fresh edges are never
571/// reported.
572#[derive(Debug, Clone, serde::Serialize)]
573pub struct DerivationFinding {
574    pub source: crate::entity::EntityId,
575    pub rel_type: String,
576    pub target: crate::entity::EntityId,
577    /// `"stale"` or `"unbaselined"` — never fabricated as fresh.
578    pub state: String,
579    /// The recorded baseline hash (`None` for unbaselined edges).
580    #[serde(skip_serializing_if = "Option::is_none")]
581    pub baseline: Option<String>,
582    /// The target's current content hash ("" for an absent target).
583    pub current: String,
584}
585
586/// The `include=["stale_derivations"]` axis: per-mem findings from
587/// [`crate::engine::Engine::derivation_report`], shared by the CLI
588/// and the MCP server. A mem whose schema declares no derivation
589/// rel-types contributes an empty list — never an error.
590pub fn health_stale_derivations_axis(
591    engine: &crate::engine::Engine,
592    mem_filter: Option<&str>,
593) -> serde_json::Value {
594    let mut mems: Vec<String> = engine.mem_names().iter().map(|s| s.to_string()).collect();
595    mems.sort();
596    let mut out = serde_json::Map::new();
597    for mem in mems {
598        if let Some(f) = mem_filter
599            && f != mem
600        {
601            continue;
602        }
603        let findings = engine.derivation_report(&mem).unwrap_or_default();
604        out.insert(
605            mem,
606            serde_json::to_value(&findings).unwrap_or(serde_json::Value::Array(Vec::new())),
607        );
608    }
609    serde_json::Value::Object(out)
610}
611
612/// Per-kind item cap for the `open_questions` axis — the axis is an
613/// agent worklist, not a dump. Stated in the output (`_item_cap`);
614/// truncation is always explicit via each list's `more` count.
615pub const OPEN_QUESTIONS_ITEM_CAP: usize = 20;
616
617/// The `include=["open_questions"]` axis: per
618/// mem, a composed worklist of what the holding does not know — its
619/// stubs, its never-confirmed (`recheck`) and `unresolvable` anchors,
620/// its unsatisfied constraints, its dangling links, and, when a
621/// paired process mem is resolvable for the destination, that
622/// process mem's open entries. Negative findings ride under the
623/// DISTINCT `already_searched` heading — their operational meaning is
624/// "done, keep off", never todo.
625///
626/// Composition only: every signal is read from the same source its
627/// own axis serves (store stub flags, `verify_mem_anchors`,
628/// `constraint_findings`, `collect_dangling_links`, the pipeline
629/// store), so this axis can never disagree with the per-signal axes.
630/// Best-effort on the process leg: an unreadable pipeline store means
631/// no process sections, never an axis failure.
632pub fn health_open_questions_axis(
633    engine: &crate::engine::Engine,
634    mem_filter: Option<&str>,
635) -> serde_json::Value {
636    let cap = OPEN_QUESTIONS_ITEM_CAP;
637    let capped = |mut items: Vec<serde_json::Value>| -> serde_json::Value {
638        let count = items.len();
639        let more = count.saturating_sub(cap);
640        items.truncate(cap);
641        let mut o = serde_json::Map::new();
642        o.insert("count".into(), serde_json::json!(count));
643        o.insert("items".into(), serde_json::Value::Array(items));
644        if more > 0 {
645            o.insert("more".into(), serde_json::json!(more));
646        }
647        serde_json::Value::Object(o)
648    };
649
650    // Bindings by destination mem — the pairing plan 14 will make
651    // declarative; until then the ingest-name convention (process mem
652    // named after the binding) is the resolution mechanism.
653    let bindings: Vec<(String, String)> = engine
654        .workspace_root()
655        .and_then(|root| crate::pipeline_store::load_pipeline_configs(root).ok())
656        .map(|c| {
657            c.bindings
658                .iter()
659                .map(|r| (r.config.destination_mem.clone(), r.name.clone()))
660                .collect()
661        })
662        .unwrap_or_default();
663    let mounted: Vec<String> = engine.mem_names().iter().map(|s| s.to_string()).collect();
664
665    let mut mems: Vec<String> = mounted.clone();
666    mems.sort();
667    let mut out = serde_json::Map::new();
668    for mem in &mems {
669        if let Some(f) = mem_filter
670            && f != mem
671        {
672            continue;
673        }
674
675        // Stubs — same source as the stubs axis (store stub flag).
676        let stubs = capped(
677            engine
678                .store()
679                .all_entities()
680                .filter(|e| e.stub && e.id.mem() == mem)
681                .map(|e| serde_json::json!({ "kind": "stub", "id": e.id.to_string() }))
682                .collect(),
683        );
684
685        // Anchors — same per-anchor mechanism as the anchors axis;
686        // only the never-confirmed and unreachable states are holes.
687        // A dangling sidecar row is a hole too (consistency-sweep 03/02), and
688        // it gets its OWN bucket. `unresolvable` is the wire form of the
689        // orphaned state, whose repair is the opposite one: an orphaned anchor
690        // asks whether its entity should be re-anchored or pruned, a dangling
691        // row asks why the entity went missing. Folding the two together here
692        // would reproduce, on the health axis, exactly the collapse the axis
693        // itself refuses.
694        //
695        // `entity_end_unreconciled` rides along both ways: an empty dangling
696        // bucket means "none found" only when the check could run at all.
697        let (mut recheck, mut unresolvable, mut unobserved, mut dangling_rows) =
698            (Vec::new(), Vec::new(), Vec::new(), Vec::new());
699        // Rows resting on a recorded observation older than today: open
700        // work too (someone has to look again), stated as its age.
701        let mut aging = Vec::new();
702        let mut entity_end_unreconciled: Option<String> = None;
703        if let Ok(report) = engine.verify_mem_anchors(mem) {
704            entity_end_unreconciled = report.unreconciled.clone();
705            for a in &report.anchors {
706                if let Some(days) = a.unobserved_for_days
707                    && days > 0
708                {
709                    aging.push(serde_json::json!({
710                        "kind": "anchor_aging",
711                        "id": a.entity_id,
712                        "artifact": a.artifact,
713                        "state": a.state,
714                        "observed_at": a.observed_at,
715                        "unobserved_for_days": days,
716                        "note": format!("unobserved for {days} days"),
717                    }));
718                }
719                let item = serde_json::json!({
720                    "kind": format!("anchor_{}", a.state),
721                    "id": a.entity_id,
722                    "artifact": a.artifact,
723                });
724                match a.state.as_str() {
725                    "recheck" => recheck.push(item),
726                    // The enum's wire name for a gone artifact; the bucket
727                    // keeps the axis's count name (`anchors_unresolvable`).
728                    "orphaned" => unresolvable.push(item),
729                    "unobserved" => unobserved.push(item),
730                    "dangling" => dangling_rows.push(item),
731                    _ => {}
732                }
733            }
734        }
735
736        // Unsatisfied constraints — same collector as the
737        // constraints axis.
738        let constraints = capped(
739            engine
740                .constraint_findings(Some(mem))
741                .iter()
742                .map(|r| {
743                    serde_json::json!({
744                        "kind": "unsatisfied_constraint",
745                        "id": r.id.to_string(),
746                        "violations": r.violations.len(),
747                    })
748                })
749                .collect(),
750        );
751
752        // Dangling links — same collector as the overview include, and the
753        // SAME three names rather than a parallel vocabulary of its own.
754        // This axis emitted one `dangling_link` kind
755        // over all three conditions, which is the fused code by another
756        // spelling; a second vocabulary is the one that drifts first.
757        let dangling = capped(
758            collect_dangling_links(engine.store(), Some(mem))
759                .iter()
760                .map(|d| {
761                    serde_json::json!({
762                        "kind": d.kind.code(),
763                        "id": d.from.to_string(),
764                        "target": d.target_id.to_string(),
765                        "repair": d.kind.repair(),
766                    })
767                })
768                .collect(),
769        );
770
771        // Paired process mems: open entries are work; negative
772        // findings are the opposite — already searched, keep off.
773        // Pairing runs through the ONE resolution function the brief
774        // renderer uses: a destination's
775        // declaration wins regardless of naming — and pairs even
776        // with no binding at all (the process tier stands without
777        // one); the binding-name convention remains the fallback. A
778        // declaration naming an unmounted mem is a typed finding,
779        // never a silent fallback.
780        let mut process = Vec::new();
781        let mem_bindings: Vec<&String> = bindings
782            .iter()
783            .filter(|(d, _)| d == mem)
784            .map(|(_, b)| b)
785            .collect();
786        let mut resolutions: Vec<(Option<String>, crate::ingest::resolve::ProcessMemResolution)> =
787            Vec::new();
788        if mem_bindings.is_empty() {
789            let r = crate::ingest::resolve::resolve_process_mem(engine, mem, "");
790            if r.declared {
791                resolutions.push((None, r));
792            }
793        } else {
794            for binding in &mem_bindings {
795                resolutions.push((
796                    Some((*binding).clone()),
797                    crate::ingest::resolve::resolve_process_mem(engine, mem, binding),
798                ));
799            }
800        }
801        for (binding, r) in resolutions {
802            if r.mounted {
803                let mut open = Vec::new();
804                let mut searched = Vec::new();
805                for e in engine
806                    .store()
807                    .all_entities()
808                    .filter(|e| !e.stub && e.id.mem() == r.mem.as_str())
809                {
810                    let item = serde_json::json!({
811                        "kind": e.entity_type,
812                        "id": e.id.to_string(),
813                        "title": e.title,
814                    });
815                    if e.entity_type == "negative_finding" {
816                        searched.push(item);
817                    } else {
818                        open.push(item);
819                    }
820                }
821                process.push(serde_json::json!({
822                    "binding": binding,
823                    "process_mem": r.mem,
824                    "declared": r.declared,
825                    "resolvable": true,
826                    "open_entries": capped(open),
827                    "already_searched": capped(searched),
828                }));
829            } else if r.declared {
830                process.push(serde_json::json!({
831                    "binding": binding,
832                    "process_mem": r.mem,
833                    "declared": true,
834                    "resolvable": false,
835                    "finding": "DECLARED_PROCESS_MEM_MISSING",
836                }));
837            } else {
838                process.push(serde_json::json!({
839                    "binding": binding,
840                    "resolvable": false,
841                }));
842            }
843        }
844
845        // The resolution readings (plan B5): for every type of this mem
846        // that declares `resolution`, the open entities with no condition
847        // written, and the open entities whose condition nobody has
848        // checked under the declared kind. The ledger is read as it is;
849        // an `x-` kind counts by name, an engine kind by derived state.
850        let (mut missing, mut unchecked) = (Vec::new(), Vec::new());
851        if let Some(schema) = engine.schema_for(mem) {
852            let ledger = engine
853                .workspace_root()
854                .map(crate::check::CheckLedger::for_workspace);
855            for entity in engine
856                .store()
857                .all_entities()
858                .filter(|e| !e.stub && e.id.mem() == mem)
859            {
860                let Some(td) = schema.types.get(&entity.entity_type) else {
861                    continue;
862                };
863                let Some(res) = &td.resolution else { continue };
864                if let Some(field) = &res.status_field {
865                    let open = match entity.metadata.get(field) {
866                        Some(crate::entity::MetadataValue::String(s)) => {
867                            res.open_values.contains(s)
868                        }
869                        _ => false,
870                    };
871                    if !open {
872                        continue;
873                    }
874                }
875                let has_condition = entity
876                    .sections
877                    .get(&res.condition_section)
878                    .is_some_and(|body| !body.trim().is_empty());
879                if !has_condition {
880                    missing.push(serde_json::json!({
881                        "kind": "resolution_missing",
882                        "id": entity.id.to_string(),
883                        "section": res.condition_section,
884                    }));
885                    continue;
886                }
887                let kind = res.check_kind.as_deref().unwrap_or("verification");
888                let checked = ledger.as_ref().is_some_and(|l| {
889                    l.all().into_iter().rev().any(|r| {
890                        r.entity == entity.id.to_string()
891                            && r.verdict == "ok"
892                            && r.entity_hash == entity.content_hash
893                            && match crate::check::RecordKind::from_wire(kind) {
894                                Some(crate::check::RecordKind::Engine(k)) => {
895                                    r.resolved_kind() == Some(k)
896                                }
897                                Some(crate::check::RecordKind::Foreign(name)) => {
898                                    r.kind.as_deref() == Some(name.as_str())
899                                }
900                                None => false,
901                            }
902                    })
903                });
904                if !checked {
905                    unchecked.push(serde_json::json!({
906                        "kind": "resolution_unchecked",
907                        "id": entity.id.to_string(),
908                        "section": res.condition_section,
909                        "check_kind": kind,
910                    }));
911                }
912            }
913        }
914        let resolution_missing = capped(missing);
915        let resolution_unchecked = capped(unchecked);
916
917        let total_open = stubs["count"].as_u64().unwrap_or(0)
918            + resolution_missing["count"].as_u64().unwrap_or(0)
919            + resolution_unchecked["count"].as_u64().unwrap_or(0)
920            + recheck.len() as u64
921            + unresolvable.len() as u64
922            + unobserved.len() as u64
923            + dangling_rows.len() as u64
924            + aging.len() as u64
925            + constraints["count"].as_u64().unwrap_or(0)
926            + dangling["count"].as_u64().unwrap_or(0)
927            + process
928                .iter()
929                .filter_map(|p| p["open_entries"]["count"].as_u64())
930                .sum::<u64>();
931
932        let mut entry = serde_json::Map::new();
933        entry.insert("stubs".into(), stubs);
934        entry.insert("anchors_recheck".into(), capped(recheck));
935        entry.insert("anchors_unresolvable".into(), capped(unresolvable));
936        // Its own bucket here too. The comment above argues that folding two
937        // anchor conditions together reproduces the collapse the axis refuses,
938        // and a first version then did exactly that eight lines further down.
939        entry.insert("anchors_unobserved".into(), capped(unobserved));
940        entry.insert("anchors_dangling".into(), capped(dangling_rows));
941        entry.insert("anchors_aging".into(), capped(aging));
942        if let Some(why) = entity_end_unreconciled {
943            entry.insert("entity_end_unreconciled".into(), serde_json::json!(why));
944        }
945        entry.insert("unsatisfied_constraints".into(), constraints);
946        entry.insert("dangling_links".into(), dangling);
947        entry.insert("resolution_missing".into(), resolution_missing);
948        entry.insert("resolution_unchecked".into(), resolution_unchecked);
949        if !process.is_empty() {
950            entry.insert("process".into(), serde_json::Value::Array(process));
951        } else {
952            // No binding targets this mem: the absence of a process
953            // section is stated, never silent.
954            entry.insert("process_mem_resolvable".into(), serde_json::json!(false));
955        }
956        entry.insert("total_open".into(), serde_json::json!(total_open));
957        out.insert(mem.clone(), serde_json::Value::Object(entry));
958    }
959    let mut top = serde_json::Map::new();
960    top.insert("_item_cap".into(), serde_json::json!(cap));
961    for (k, v) in out {
962        top.insert(k, v);
963    }
964    serde_json::Value::Object(top)
965}
966
967pub fn health_anchors_axis(
968    engine: &crate::engine::Engine,
969    mem_filter: Option<&str>,
970) -> serde_json::Value {
971    let mut mems: Vec<String> = engine.mem_names().iter().map(|s| s.to_string()).collect();
972    mems.retain(|m| mem_filter.is_none_or(|v| m == v));
973    mems.sort();
974    let mut out = serde_json::Map::new();
975    for mem in mems {
976        let Ok(report) = engine.verify_mem_anchors(&mem) else {
977            continue;
978        };
979        let condition = report.sidecar_error.as_ref().map(|why| {
980            serde_json::json!({
981                "code": "ANCHORS_SIDECAR_UNREADABLE",
982                "mem": mem,
983                "reason": why,
984            })
985        });
986        // The figure travels as its type's own three fields (`resolves`,
987        // `population`, `fully_adjudicated`), merged into the row.
988        let mut row = serde_json::json!({
989                // The one condition that replaces the counts: an unreadable
990                // sidecar. Absent when the sidecar read cleanly.
991                "condition": condition,
992                "drifted": report.drifted,
993                "recheck": report.recheck,
994                // Split from `unresolvable`: the artifact
995                // being gone is a measurement, the pass not reaching it is the
996                // absence of one, and this is the surface a reader arrives at
997                // without a binding in hand.
998                "unresolvable": report.unresolvable,
999                "unobserved": report.unobserved,
1000                // The entity end (03/02). Carried here too, both ways: four
1001                // counts over a mem whose sidecar has outlived its entities
1002                // read as a healthy axis, and so does a zero over a mem whose
1003                // entity end was never reconciled.
1004                "dangling": report.dangling,
1005                "entity_end_unreconciled": report.unreconciled,
1006                // Rows whose state rests on a recorded observation (url
1007                // rows), each with how long it has gone unobserved. A state
1008                // observed months ago is not today's state, and the axis
1009                // says so beside the count it contributed to.
1010                "aging": report
1011                    .anchors
1012                    .iter()
1013                    .filter(|a| a.observed_at.is_some())
1014                    .map(|a| {
1015                        let days = a.unobserved_for_days.unwrap_or(0);
1016                        serde_json::json!({
1017                            "id": a.entity_id,
1018                            "artifact": a.artifact,
1019                            "state": a.state,
1020                            "observed_at": a.observed_at,
1021                            "unobserved_for_days": days,
1022                            "note": format!("unobserved for {days} days"),
1023                        })
1024                    })
1025                    .collect::<Vec<_>>(),
1026        });
1027        if let (Some(o), Ok(serde_json::Value::Object(f))) =
1028            (row.as_object_mut(), serde_json::to_value(&report.figure))
1029        {
1030            o.extend(f);
1031        }
1032        out.insert(mem, row);
1033    }
1034    serde_json::Value::Object(out)
1035}
1036
1037/// Compute health reports for all entities in the store.
1038///
1039/// `mem_schemas` maps mem name → `Arc<Schema>`. Entities whose mem
1040/// is missing from this map fall back to the builtin `default` schema
1041/// relationship vocabulary (keeps legacy fixtures green; real production
1042/// paths always register a mem schema).
1043///
1044/// `mem_filter` scopes the per-entity scans and the structural counts
1045/// (orphans, stubs, leaf population) to one mem; `None` is the classic
1046/// engine-wide sweep. Validating that the name exists is the caller's
1047/// job ([`crate::Engine::health_scoped`] refuses `UNKNOWN_MEM` before
1048/// reaching here) — an unknown name at this level just scans nothing.
1049pub fn compute_health(
1050    store: &Store,
1051    default_schema: &TypeDefinition,
1052    mem_schemas: &HashMap<String, Arc<Schema>>,
1053    mem_filter: Option<&str>,
1054) -> HealthSummary {
1055    let mut missing_fields = Vec::new();
1056    let mut stale_entities = Vec::new();
1057
1058    let today_days = days_since_epoch();
1059
1060    let in_scope = |mem: &str| mem_filter.is_none_or(|v| mem == v);
1061
1062    for entity in store.all_entities() {
1063        if entity.stub || !in_scope(&entity.mem) {
1064            continue;
1065        }
1066
1067        // Resolve the entity's `TypeDefinition` against the entity's
1068        // own mem's schema first. `type_by_name` only knows the
1069        // builtin `default` schema; falling through to it on a mem
1070        // pinned to a non-default schema (e.g. `planning@0.1.0`) would
1071        // silently use `default_schema` (effectively `spec`) for every
1072        // entity and report `spec`'s `health_required_fields` —
1073        // `[identity, purpose]` — even on entities of types like
1074        // `goal` / `option` / `decision`.
1075        let resolved = mem_schemas
1076            .get(entity.mem.as_str())
1077            .and_then(|s| s.types.get(entity.entity_type.as_str()).cloned())
1078            .or_else(|| type_by_name(&entity.entity_type));
1079        let schema: &TypeDefinition = resolved.as_deref().unwrap_or(default_schema);
1080        let mut issues = Vec::new();
1081
1082        // Check health_required_fields
1083        for field in &schema.health_required_fields {
1084            // Check if it's a section or metadata field
1085            if schema.section(field).is_some() {
1086                // It's a section. When the content is present in the
1087                // file but sits under a non-deriving heading, report
1088                // the distinct mismatch finding instead of "missing" —
1089                // the two conditions must never collapse.
1090                let content = entity.sections.get(field.as_str());
1091                if content.is_none_or(|c| c.trim().is_empty()) {
1092                    if let Some(issue) = section_heading_mismatch_issue(entity, schema, field) {
1093                        issues.push(issue);
1094                    } else {
1095                        issues.push(HealthIssue {
1096                            field: field.clone(),
1097                            code: super::HealthIssueCode::Missing,
1098                            message: format!("required section '{field}' is empty"),
1099                        });
1100                    }
1101                }
1102            } else {
1103                // It's a metadata field. Treat missing AND empty /
1104                // whitespace-only values as gaps so the scan matches
1105                // the section branch's `trim().is_empty()` semantics
1106                // — an empty `MetadataValue::String("")` is just as
1107                // unhelpful to an agent as an absent key.
1108                let value = entity.metadata.get(field.as_str());
1109                let is_empty = match value {
1110                    None => true,
1111                    Some(v) => v.to_frontmatter_string().trim().is_empty(),
1112                };
1113                if is_empty {
1114                    issues.push(HealthIssue {
1115                        field: field.clone(),
1116                        code: super::HealthIssueCode::Missing,
1117                        message: format!("required field '{field}' is missing"),
1118                    });
1119                }
1120            }
1121        }
1122
1123        // The heading-mismatch condition is drift worth surfacing on
1124        // every declared section, not only the health-required ones.
1125        for s in schema.sections.iter().filter(|s| !s.catch_all) {
1126            if schema.health_required_fields.contains(&s.key) {
1127                continue; // already handled above
1128            }
1129            let content = entity.sections.get(s.key.as_str());
1130            if content.is_none_or(|c| c.trim().is_empty())
1131                && let Some(issue) = section_heading_mismatch_issue(entity, schema, &s.key)
1132            {
1133                issues.push(issue);
1134            }
1135        }
1136
1137        // Undeclared-relationship warning. Scan the entity's
1138        // relationship list against the mem's schema vocabulary; every
1139        // unknown name becomes a soft HealthIssue (same severity as a
1140        // missing section) so agents running a health sweep after a
1141        // schema version bump see drift without a crashed load.
1142        //
1143        // Shape-violation scan: when the mem's schema declares
1144        // `source_types` / `target_types` on a relationship and an
1145        // existing edge violates the shape, surface as a soft
1146        // HealthIssue. The relate-add path enforces shape going
1147        // forward; this scan catches edges authored before the
1148        // constraint landed (or via inline `relations:` on
1149        // memstead_create, which does not yet shape-check). The
1150        // remove-path on `memstead_relate` skips shape validation so the
1151        // cleanup is always reachable.
1152        if let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) {
1153            let mut seen_unknown = std::collections::HashSet::new();
1154            for rel in &entity.relationships {
1155                if !mem_schema.relationship_known(&rel.rel_type) {
1156                    if seen_unknown.insert(rel.rel_type.clone()) {
1157                        let suggestion = mem_schema
1158                            .suggest_relationship(&rel.rel_type)
1159                            .map(|s| format!(" Did you mean '{s}'?"))
1160                            .unwrap_or_default();
1161                        let (schema_name, schema_version) = mem_schema.id();
1162                        issues.push(HealthIssue {
1163                            field: "relationships".to_string(),
1164                            code: super::HealthIssueCode::UndeclaredRelationship,
1165                            message: format!(
1166                                "relationship '{}' is not declared in schema \
1167                                 '{schema_name}@{schema_version}'.{suggestion}",
1168                                rel.rel_type
1169                            ),
1170                        });
1171                    }
1172                    continue;
1173                }
1174
1175                let target_type = store
1176                    .get(&rel.target)
1177                    .map(|t| t.entity_type.clone())
1178                    .filter(|t| !t.is_empty());
1179                if let Err(crate::runtime_validator::ValidationError::InvalidRelationshipShape {
1180                    rel_type,
1181                    from_type,
1182                    to_type,
1183                    allowed_source_types,
1184                    allowed_target_types,
1185                    ..
1186                }) = crate::runtime_validator::validate_rel_shape(
1187                    &rel.rel_type,
1188                    entity.entity_type.as_str(),
1189                    target_type.as_deref(),
1190                    mem_schema.as_ref(),
1191                ) {
1192                    let allowed_src = if allowed_source_types.is_empty() {
1193                        "<any>".to_string()
1194                    } else {
1195                        allowed_source_types.join(", ")
1196                    };
1197                    let allowed_tgt = if allowed_target_types.is_empty() {
1198                        "<any>".to_string()
1199                    } else {
1200                        allowed_target_types.join(", ")
1201                    };
1202                    issues.push(HealthIssue {
1203                        field: "relationships".to_string(),
1204                        code: super::HealthIssueCode::InvalidRelShape,
1205                        message: format!(
1206                            "INVALID_REL_SHAPE: edge '{rel_type}' from \
1207                             '{from_type}' to '{to_type}' (target {target}) \
1208                             violates declared shape — allowed_source_types: \
1209                             [{allowed_src}], allowed_target_types: \
1210                             [{allowed_tgt}]. Remove via \
1211                             `memstead_relate from={from_id} to={target} \
1212                             type={rel_type} remove=true`.",
1213                            target = rel.target,
1214                            from_id = entity.id,
1215                        ),
1216                    });
1217                }
1218            }
1219        }
1220
1221        // Staleness check
1222        let auto_ts_field = schema.metadata_fields.iter().find(|f| f.auto_timestamp);
1223
1224        if let Some(ts_field) = auto_ts_field
1225            && let Some(val) = entity.metadata.get(ts_field.key.as_str())
1226        {
1227            let date_str = val.to_frontmatter_string();
1228            if let Some(modified_days) = parse_iso_to_days(&date_str) {
1229                let days_since = today_days.saturating_sub(modified_days);
1230                if days_since > schema.staleness_threshold_days as u64 {
1231                    stale_entities.push(StaleEntity {
1232                        id: entity.id.clone(),
1233                        title: entity.title.clone(),
1234                        days_since_modified: days_since,
1235                        anchor_state: None,
1236                    });
1237                }
1238            }
1239        }
1240
1241        if !issues.is_empty() {
1242            // Compute a simple health score: (total_fields - issues) / total_fields.
1243            // `issues.len()` can exceed `total_fields` once the
1244            // relationship-vocabulary issues are added on top, so saturate
1245            // the subtraction rather than underflow. A score of 0.0 is the
1246            // natural floor — agents treat it as "maximally broken".
1247            let total = schema.health_required_fields.len();
1248            let score = if total > 0 {
1249                (total.saturating_sub(issues.len()) as f32) / (total as f32)
1250            } else {
1251                1.0
1252            };
1253
1254            missing_fields.push(HealthReport {
1255                id: entity.id.clone(),
1256                title: entity.title.clone(),
1257                score,
1258                issues,
1259            });
1260        }
1261    }
1262
1263    // Sort stale entities by days_since_modified descending
1264    stale_entities.sort_by_key(|e| std::cmp::Reverse(e.days_since_modified));
1265
1266    // Structural counts — scoped by the same filter as the entity scans
1267    // above so a `mem`-scoped summary is internally consistent.
1268    let orphan_count = query::find_orphans_with_schemas(store, mem_schemas)
1269        .into_iter()
1270        .filter(|id| store.get(id).is_some_and(|e| in_scope(&e.mem)))
1271        .count();
1272    let leaf_entities_by_type = match mem_filter {
1273        None => query::leaf_population(store, mem_schemas),
1274        Some(v) => {
1275            let scoped: HashMap<String, Arc<Schema>> = mem_schemas
1276                .iter()
1277                .filter(|(mem, _)| mem.as_str() == v)
1278                .map(|(mem, s)| (mem.clone(), s.clone()))
1279                .collect();
1280            query::leaf_population(store, &scoped)
1281        }
1282    };
1283    let stub_count = query::find_stubs(store)
1284        .iter()
1285        .filter(|(id, _)| store.get(id).is_some_and(|e| in_scope(&e.mem)))
1286        .count();
1287
1288    // The store iterates a hash map: order the per-entity lists by id so
1289    // two processes (the CLI and the MCP server) render the same bytes.
1290    stale_entities.sort_by(|a, b| a.id.0.cmp(&b.id.0));
1291    missing_fields.sort_by(|a, b| a.id.0.cmp(&b.id.0));
1292
1293    HealthSummary {
1294        stale_entities,
1295        anchor_fresh: Vec::new(),
1296        missing_fields,
1297        orphan_count,
1298        stub_count,
1299        warnings: Vec::new(),
1300        quarantined: Vec::new(),
1301        load_errors: Vec::new(),
1302        boot_diagnosis: None,
1303        leaf_entities_by_type,
1304        dangling_links: None,
1305        findings: None,
1306        tag_distribution: None,
1307        tag_distribution_folded: None,
1308        untagged_entities: None,
1309    }
1310}
1311
1312/// Scan every non-stub entity's `tags` metadata and aggregate (tag → count,
1313/// per-entity-type breakdown) plus untagged coverage. Comma-separated parser
1314/// with per-segment trim; empty segments drop. Comparison is case-sensitive
1315/// on the primary surface — case drift is surfaced separately via
1316/// [`TagDistribution`] siblings folded by the caller if desired.
1317///
1318/// `mem_filter` narrows both aggregation passes to entities in that mem;
1319/// `limit` caps the returned `tag_distribution` array after sorting by count
1320/// descending (tie-break by tag ascending for deterministic output).
1321///
1322/// Also returns `FoldedTag` entries for any canonical (lowercase) tag where
1323/// two or more authored casings appear — drift-flag only; empty when no
1324/// collisions exist.
1325pub fn collect_tag_distribution(
1326    store: &Store,
1327    mem_filter: Option<&str>,
1328    limit: usize,
1329) -> (Vec<TagDistribution>, Vec<FoldedTag>, UntaggedStats) {
1330    // tag → (count, per_type_count)
1331    let mut counts: HashMap<String, (usize, HashMap<String, usize>)> = HashMap::new();
1332    let mut untagged = UntaggedStats {
1333        total: 0,
1334        by_entity_type: HashMap::new(),
1335    };
1336
1337    for entity in store.all_entities() {
1338        if entity.stub {
1339            continue;
1340        }
1341        if let Some(v) = mem_filter
1342            && entity.mem != v
1343        {
1344            continue;
1345        }
1346
1347        let tags_raw = entity
1348            .metadata
1349            .get("tags")
1350            .and_then(|v| match v {
1351                MetadataValue::String(s) => Some(s.as_str()),
1352                _ => None,
1353            })
1354            .unwrap_or("");
1355
1356        let mut any_tag = false;
1357        for tag in tags_raw.split(',').map(str::trim).filter(|s| !s.is_empty()) {
1358            any_tag = true;
1359            let entry = counts
1360                .entry(tag.to_string())
1361                .or_insert_with(|| (0, HashMap::new()));
1362            entry.0 += 1;
1363            *entry.1.entry(entity.entity_type.clone()).or_insert(0) += 1;
1364        }
1365        if !any_tag {
1366            untagged.total += 1;
1367            *untagged
1368                .by_entity_type
1369                .entry(entity.entity_type.clone())
1370                .or_insert(0) += 1;
1371        }
1372    }
1373
1374    // Primary distribution — case-sensitive.
1375    let mut entries: Vec<TagDistribution> = counts
1376        .iter()
1377        .map(|(tag, (count, by_type))| TagDistribution {
1378            tag: tag.clone(),
1379            count: *count,
1380            by_entity_type: by_type.clone(),
1381        })
1382        .collect();
1383    entries.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.tag.cmp(&b.tag)));
1384    entries.truncate(limit);
1385
1386    // Case-drift sidecar: group by lowercase canonical; surface only entries
1387    // with ≥2 distinct authored casings. Operates on the full counts map, not
1388    // the truncated primary surface, so drift hidden below `limit` still
1389    // surfaces.
1390    let mut by_canonical: HashMap<String, Vec<(String, usize)>> = HashMap::new();
1391    for (tag, (count, _)) in counts.iter() {
1392        by_canonical
1393            .entry(tag.to_lowercase())
1394            .or_default()
1395            .push((tag.clone(), *count));
1396    }
1397    let mut folded: Vec<FoldedTag> = by_canonical
1398        .into_iter()
1399        .filter(|(_, v)| v.len() > 1)
1400        .map(|(canonical, mut variants)| {
1401            variants.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
1402            let total = variants.iter().map(|(_, c)| *c).sum();
1403            FoldedTag {
1404                canonical,
1405                total,
1406                variants: variants
1407                    .into_iter()
1408                    .map(|(tag, count)| TagVariant { tag, count })
1409                    .collect(),
1410            }
1411        })
1412        .collect();
1413    folded.sort_by(|a, b| {
1414        b.total
1415            .cmp(&a.total)
1416            .then_with(|| a.canonical.cmp(&b.canonical))
1417    });
1418
1419    (entries, folded, untagged)
1420}
1421
1422/// Collect the three separately-repaired conditions the diagnostic
1423/// covers, each tagged with its own [`DanglingLinkKind`]:
1424///
1425/// - `LinkTargetMissing` — a body wiki-link whose target has no markdown
1426///   file: either absent from the store entirely, or present only as a
1427///   stub. Repair: write the entity, or drop the link.
1428/// - `LinkNotRelated` — a body wiki-link to a fully written entity that
1429///   the referrer's relationships list omits (an alias orphan under the
1430///   alias model). The target is fine; the row is missing. Repair: a
1431///   write of the referrer re-synthesises the row.
1432/// - `RelationTargetMissing` — a `## Relationships` row naming an entity
1433///   absent from the store entirely, not even as a stub. Auto-stubbing
1434///   means this only arises from out-of-band file edits or historical
1435///   cross-mem corruption (the pre-F15 mem-delete path). Repair: restore
1436///   the target or remove the edge.
1437///
1438/// The three used to share one code, and only the first was identifiable
1439/// from the payload; the other two were told apart, if at all, by
1440/// whether `section` happened to be null. `section` still marks the
1441/// source axis (`None` for the relationship table), but the condition is
1442/// named, not inferred.
1443///
1444/// `mem_filter` narrows *scanning* to entities in that mem; resolution
1445/// stays global so cross-mem links whose target is a real entity
1446/// elsewhere are not flagged as missing.
1447pub fn collect_dangling_links(store: &Store, mem_filter: Option<&str>) -> Vec<DanglingLink> {
1448    use crate::entity::parser::extract_inline_links_lenient;
1449    use std::collections::HashSet;
1450
1451    let mut out = Vec::new();
1452    for entity in store.all_entities() {
1453        if entity.stub {
1454            continue;
1455        }
1456        if let Some(v) = mem_filter
1457            && entity.mem != v
1458        {
1459            continue;
1460        }
1461        let explicit_targets: HashSet<_> = entity
1462            .relationships
1463            .iter()
1464            .map(|r| r.target.clone())
1465            .collect();
1466        for (section_key, section_body) in &entity.sections {
1467            for target_id in extract_inline_links_lenient(section_body, &entity.mem) {
1468                let target_missing = store.get(&target_id).map(|e| e.stub).unwrap_or(true);
1469                let alias_orphan = !target_missing && !explicit_targets.contains(&target_id);
1470                // The one place the three conditions are distinguished, so the
1471                // one place the discriminator is set. Consumers read `kind`;
1472                // none re-derives it against the store (04/06).
1473                let kind = if target_missing {
1474                    crate::ops::DanglingLinkKind::LinkTargetMissing
1475                } else {
1476                    crate::ops::DanglingLinkKind::LinkNotRelated
1477                };
1478                if target_missing || alias_orphan {
1479                    out.push(DanglingLink {
1480                        kind,
1481                        from: entity.id.clone(),
1482                        target_id: target_id.clone(),
1483                        target_path: target_id.path().to_string(),
1484                        section: Some(section_key.clone()),
1485                    });
1486                }
1487            }
1488        }
1489        // Relationship-table dangler scan. The `## Relationships`
1490        // section is structurally distinct from body sections — its
1491        // rows materialise from `entity.relationships` rather than a
1492        // free-text body — so `section: None` marks the source axis.
1493        //
1494        // Discrimination differs from the body scan: a relationship
1495        // target that resolves to a stub is a legitimate forward
1496        // reference (the alias machinery auto-stubs absent targets
1497        // by design), not corruption. Only a target that's *fully
1498        // absent* from the store — neither stub nor real — flags as
1499        // dangling. In practice this only fires for out-of-band file
1500        // edits or historical cross-mem-delete corruption that
1501        // dropped the stub along with the deleted mem.
1502        //
1503        // Dedup against the body-scan output so a target that
1504        // surfaces from both axes doesn't double-emit.
1505        for rel in &entity.relationships {
1506            if store.get(&rel.target).is_some() {
1507                continue;
1508            }
1509            let already_reported = out
1510                .iter()
1511                .any(|d| d.from == entity.id && d.target_id == rel.target);
1512            if already_reported {
1513                continue;
1514            }
1515            out.push(DanglingLink {
1516                kind: crate::ops::DanglingLinkKind::RelationTargetMissing,
1517                from: entity.id.clone(),
1518                target_id: rel.target.clone(),
1519                target_path: rel.target.path().to_string(),
1520                section: None,
1521            });
1522        }
1523    }
1524    // Deterministic output — the store iterates a HashMap, so without a
1525    // sort two identical runs can serve the same findings in different
1526    // orders. Sort by (from, target, section) so successive sweeps diff
1527    // cleanly.
1528    out.sort_by(|a, b| {
1529        (&a.from.0, &a.target_id.0, &a.section).cmp(&(&b.from.0, &b.target_id.0, &b.section))
1530    });
1531    out
1532}
1533
1534/// Collect every non-stub entity whose type declares `required_outgoing`
1535/// blocks that the entity's current outgoing edges leave unsatisfied.
1536/// Results are deterministic — sorted
1537/// by `(mem, id)` — so the agent can diff successive sweeps without
1538/// the underlying HashMap iteration order leaking through.
1539///
1540/// `mem_filter` narrows scanning to entities in that mem when set;
1541/// `mem_schemas` resolves the entity's type definition against the
1542/// mem's pinned schema. Entities whose mem has no schema in the
1543/// map are skipped (no schema → no `required_outgoing` to evaluate).
1544pub fn collect_missing_required_outgoing(
1545    store: &Store,
1546    mem_filter: Option<&str>,
1547    mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
1548) -> Vec<MissingRequiredOutgoingReport> {
1549    let mut out = Vec::new();
1550    for entity in store.all_entities() {
1551        if entity.stub {
1552            continue;
1553        }
1554        if let Some(v) = mem_filter
1555            && entity.mem != v
1556        {
1557            continue;
1558        }
1559        let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
1560            continue;
1561        };
1562        let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
1563            continue;
1564        };
1565        if td.required_outgoing.is_empty() {
1566            continue;
1567        }
1568        let unsatisfied = unsatisfied_required_outgoing(entity, td);
1569        if unsatisfied.is_empty() {
1570            continue;
1571        }
1572        out.push(MissingRequiredOutgoingReport {
1573            id: entity.id.clone(),
1574            title: entity.title.clone(),
1575            entity_type: entity.entity_type.clone(),
1576            mem: entity.mem.clone(),
1577            missing: unsatisfied,
1578        });
1579    }
1580    out.sort_by(|a, b| a.mem.cmp(&b.mem).then_with(|| a.id.0.cmp(&b.id.0)));
1581    out
1582}
1583
1584/// Evaluate one entity's declared `required_outgoing` blocks against
1585/// its current outgoing edges, returning the unsatisfied blocks in
1586/// declaration order. THE single evaluation — shared by the health
1587/// sweep ([`collect_missing_required_outgoing`]) and the per-mutation
1588/// `MISSING_REQUIRED_OUTGOING` warning on create/update. A second
1589/// implementation of the block check is a defect: the two surfaces
1590/// must never disagree about what counts as unsatisfied.
1591pub fn unsatisfied_required_outgoing(
1592    entity: &crate::entity::Entity,
1593    td: &TypeDefinition,
1594) -> Vec<super::MissingRequiredOutgoingBlock> {
1595    td.required_outgoing
1596        .iter()
1597        .filter(|block| {
1598            // A conditional block applies only while `when_field`
1599            // holds `when_value` (same comparison the `requires_when`
1600            // constraint uses). Unset field or any other value = the
1601            // block is unarmed and never unsatisfied.
1602            if let (Some(when_field), Some(when_value)) = (&block.when_field, &block.when_value) {
1603                let armed = entity
1604                    .metadata
1605                    .get(when_field.as_str())
1606                    .is_some_and(|v| v.to_frontmatter_string() == *when_value);
1607                if !armed {
1608                    return false;
1609                }
1610            }
1611            let count = entity
1612                .relationships
1613                .iter()
1614                .filter(|rel| block.relationships.iter().any(|name| name == &rel.rel_type))
1615                .count();
1616            !block.admits(count)
1617        })
1618        .map(|block| super::MissingRequiredOutgoingBlock {
1619            relationships: block.relationships.clone(),
1620            cardinality: block.cardinality.to_string(),
1621            severity: block.severity,
1622            when_field: block.when_field.clone(),
1623            when_value: block.when_value.clone(),
1624        })
1625        .collect()
1626}
1627
1628/// One violated declared constraint on one entity — the wire entry
1629/// shared by the write-path surface (the `CONSTRAINT_UNSATISFIED`
1630/// warning or refusal, tier decided by the declared severity) and the
1631/// health `constraints` include. The serde `kind` tag names the form;
1632/// the remaining fields restate the declaration (plus the observed
1633/// offense — the colliding entity, the unbacked value, the tainting
1634/// ancestor) so a consumer can repair without re-fetching the schema.
1635#[derive(Debug, Clone, serde::Serialize)]
1636#[serde(tag = "kind", rename_all = "snake_case")]
1637pub enum UnsatisfiedConstraint {
1638    RequiresWhen {
1639        field: String,
1640        when_field: String,
1641        when_value: String,
1642        severity: memstead_schema::ConstraintSeverity,
1643    },
1644    Unique {
1645        fields: Vec<String>,
1646        /// The entity's values for `fields`, in declaration order.
1647        values: Vec<String>,
1648        /// The other entity holding the same tuple (lexically smallest
1649        /// when several collide).
1650        colliding: String,
1651        severity: memstead_schema::ConstraintSeverity,
1652    },
1653    EnumFromNeighbour {
1654        field: String,
1655        /// The set value no reached neighbour's section backs.
1656        value: String,
1657        rel_type: String,
1658        section: String,
1659        severity: memstead_schema::ConstraintSeverity,
1660    },
1661    StatusPropagation {
1662        field: String,
1663        /// The terminal value the ancestor holds.
1664        value: String,
1665        /// Echo of a single-rel-type declaration — present exactly
1666        /// when the schema declared `rel_type`, keeping the
1667        /// long-standing payload byte-identical.
1668        #[serde(skip_serializing_if = "Option::is_none")]
1669        rel_type: Option<String>,
1670        /// Echo of a relation-set declaration (`rel_types`).
1671        #[serde(skip_serializing_if = "Option::is_none")]
1672        rel_types: Option<Vec<String>>,
1673        /// The tainting ancestor — the entity holding the terminal
1674        /// value that this entity (transitively) reaches.
1675        tainted_by: String,
1676        severity: memstead_schema::ConstraintSeverity,
1677    },
1678    /// Form 6 — the entity holds the gated `to_value` while related
1679    /// entities lack a fresh confirming check record.
1680    TransitionRequiresChecks {
1681        field: String,
1682        to_value: String,
1683        relationships: Vec<String>,
1684        direction: memstead_schema::PropagationDirection,
1685        /// Every related entity NOT at derived state `checked_ok`,
1686        /// each with the state it derived, sorted by id.
1687        unchecked: Vec<UncheckedRelated>,
1688        severity: memstead_schema::ConstraintSeverity,
1689    },
1690    /// The entity reaches no non-stub entity of a terminal type along
1691    /// the declared relation set — the declaration is echoed whole so
1692    /// the reader sees which obligation went unmet without re-fetching
1693    /// the schema. Health-sweep only, always warn-tier.
1694    MustReach {
1695        relationships: Vec<String>,
1696        direction: memstead_schema::ReachDirection,
1697        terminal_types: Vec<String>,
1698        #[serde(skip_serializing_if = "Option::is_none")]
1699        max_depth: Option<u32>,
1700        severity: memstead_schema::ConstraintSeverity,
1701    },
1702}
1703
1704impl UnsatisfiedConstraint {
1705    pub fn severity(&self) -> memstead_schema::ConstraintSeverity {
1706        match self {
1707            Self::RequiresWhen { severity, .. }
1708            | Self::Unique { severity, .. }
1709            | Self::EnumFromNeighbour { severity, .. }
1710            | Self::StatusPropagation { severity, .. }
1711            | Self::MustReach { severity, .. }
1712            | Self::TransitionRequiresChecks { severity, .. } => *severity,
1713        }
1714    }
1715
1716    /// One-line human rendering for warning/refusal message text.
1717    pub fn describe(&self) -> String {
1718        match self {
1719            Self::RequiresWhen {
1720                field,
1721                when_field,
1722                when_value,
1723                ..
1724            } => format!(
1725                "requires_when: '{field}' is required when {when_field}={when_value} and is unset"
1726            ),
1727            Self::Unique {
1728                fields, colliding, ..
1729            } => format!(
1730                "unique: tuple ({}) collides with '{colliding}'",
1731                fields.join(", ")
1732            ),
1733            Self::EnumFromNeighbour {
1734                field,
1735                value,
1736                rel_type,
1737                section,
1738                ..
1739            } => format!(
1740                "enum_from_neighbour: '{field}' value '{value}' has no backing entry in any \
1741                 `{section}` section reached via {rel_type}"
1742            ),
1743            Self::StatusPropagation {
1744                field,
1745                value,
1746                tainted_by,
1747                ..
1748            } => {
1749                format!("status_propagation: tainted by '{tainted_by}' ({field}={value})")
1750            }
1751            Self::MustReach {
1752                relationships,
1753                direction,
1754                terminal_types,
1755                max_depth,
1756                ..
1757            } => {
1758                let depth = match max_depth {
1759                    Some(d) => format!(" within {d} hop(s)"),
1760                    None => String::new(),
1761                };
1762                format!(
1763                    "must_reach: no path via [{}] ({direction}) reaches a [{}] entity{depth}",
1764                    relationships.join(", "),
1765                    terminal_types.join(", ")
1766                )
1767            }
1768            Self::TransitionRequiresChecks {
1769                field,
1770                to_value,
1771                relationships,
1772                unchecked,
1773                ..
1774            } => {
1775                let listed: Vec<String> = unchecked
1776                    .iter()
1777                    .map(|u| format!("'{}' ({})", u.id, u.state))
1778                    .collect();
1779                format!(
1780                    "transition_requires_checks: {field}={to_value} requires a fresh confirming \
1781                     check record on every entity related via [{}] — unconfirmed: {}",
1782                    relationships.join(", "),
1783                    listed.join(", ")
1784                )
1785            }
1786        }
1787    }
1788}
1789
1790/// One related entity blocking a `transition_requires_checks` gate:
1791/// its id and the derived verification state it reads instead of the
1792/// required `checked_ok`.
1793#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
1794pub struct UncheckedRelated {
1795    pub id: String,
1796    pub state: String,
1797}
1798
1799/// The `transition_requires_checks` evaluator's window into the check
1800/// ledger: derived verification state for one entity. Callers with an
1801/// engine build it from the workspace check ledger; `None` (no ledger
1802/// access — a workspace-less engine, or a call path that cannot reach
1803/// one) derives every related entity as `never_checked`, so a
1804/// declared gate refuses honestly rather than passing unverified.
1805pub type CheckStateProvider<'a> =
1806    &'a dyn Fn(&crate::entity::Entity) -> crate::engine::independence::CheckStanding;
1807
1808/// Evaluate one entity's declared per-entity `constraints` against its
1809/// current state (and, for the store-aware forms, against the rest of
1810/// its mem), returning the violated ones in declaration order. THE
1811/// single evaluation — shared by the health sweep
1812/// ([`collect_constraint_findings`]) and the per-mutation
1813/// `CONSTRAINT_UNSATISFIED` surface on create/update/relate; a second
1814/// implementation of any form is a defect.
1815///
1816/// Form semantics:
1817/// - `requires_when` triggers when `when_field`'s frontmatter value
1818///   equals `when_value` exactly; a triggered constraint is satisfied
1819///   when `field` — a metadata field or a section key — is present
1820///   with non-blank content.
1821/// - `unique`: the entity's tuple of `fields` values (skipped when any
1822///   field is unset/blank) must not equal another non-stub entity's
1823///   tuple within the same mem and type. `exclude` names the entity's
1824///   own id so an update does not collide with its stored self.
1825/// - `enum_from_neighbour`: a set `field` value must appear as a
1826///   bullet entry (`- value` / `* value` line) in the `section` body
1827///   of at least one entity reached via an outgoing `rel_type` edge.
1828/// - `status_propagation` is a reachability property of the graph,
1829///   not of one write — it is evaluated only by the health sweep
1830///   ([`collect_constraint_findings`]), never here.
1831pub fn unsatisfied_constraints(
1832    store: &Store,
1833    entity: &crate::entity::Entity,
1834    td: &TypeDefinition,
1835    exclude: Option<&crate::entity::EntityId>,
1836    checks: Option<CheckStateProvider<'_>>,
1837) -> Vec<UnsatisfiedConstraint> {
1838    use memstead_schema::ConstraintDef;
1839    td.constraints
1840        .iter()
1841        .filter_map(|c| match c {
1842            ConstraintDef::RequiresWhen {
1843                field,
1844                when_field,
1845                when_value,
1846                severity,
1847            } => {
1848                let triggered = entity
1849                    .metadata
1850                    .get(when_field.as_str())
1851                    .is_some_and(|v| v.to_frontmatter_string() == *when_value);
1852                if !triggered {
1853                    return None;
1854                }
1855                let satisfied = entity
1856                    .metadata
1857                    .get(field.as_str())
1858                    .is_some_and(|v| !v.to_frontmatter_string().trim().is_empty())
1859                    || entity
1860                        .sections
1861                        .get(field.as_str())
1862                        .is_some_and(|body| !body.trim().is_empty());
1863                if satisfied {
1864                    return None;
1865                }
1866                Some(UnsatisfiedConstraint::RequiresWhen {
1867                    field: field.clone(),
1868                    when_field: when_field.clone(),
1869                    when_value: when_value.clone(),
1870                    severity: *severity,
1871                })
1872            }
1873            ConstraintDef::Unique { fields, severity } => {
1874                let tuple = tuple_of(entity, fields)?;
1875                let mut colliding: Vec<&str> = store
1876                    .all_entities()
1877                    .filter(|other| {
1878                        !other.stub
1879                            && other.mem == entity.mem
1880                            && other.entity_type == entity.entity_type
1881                            && Some(&other.id) != exclude
1882                            && other.id != entity.id
1883                            && tuple_of(other, fields).as_ref() == Some(&tuple)
1884                    })
1885                    .map(|other| other.id.0.as_str())
1886                    .collect();
1887                colliding.sort_unstable();
1888                let first = colliding.first()?;
1889                Some(UnsatisfiedConstraint::Unique {
1890                    fields: fields.clone(),
1891                    values: tuple,
1892                    colliding: first.to_string(),
1893                    severity: *severity,
1894                })
1895            }
1896            ConstraintDef::EnumFromNeighbour {
1897                field,
1898                rel_type,
1899                section,
1900                severity,
1901            } => {
1902                let value = entity
1903                    .metadata
1904                    .get(field.as_str())
1905                    .map(|v| v.to_frontmatter_string())
1906                    .filter(|v| !v.trim().is_empty())?;
1907                let backed = entity
1908                    .relationships
1909                    .iter()
1910                    .filter(|rel| rel.rel_type == *rel_type)
1911                    .filter_map(|rel| store.get(&rel.target))
1912                    .filter_map(|neighbour| neighbour.sections.get(section.as_str()))
1913                    .any(|body| bullet_entries(body).contains(&value));
1914                if backed {
1915                    return None;
1916                }
1917                Some(UnsatisfiedConstraint::EnumFromNeighbour {
1918                    field: field.clone(),
1919                    value,
1920                    rel_type: rel_type.clone(),
1921                    section: section.clone(),
1922                    severity: *severity,
1923                })
1924            }
1925            ConstraintDef::StatusPropagation { .. } => None,
1926            ConstraintDef::TransitionRequiresChecks {
1927                field,
1928                to_value,
1929                relationships,
1930                direction,
1931                severity,
1932            } => {
1933                let triggered = entity
1934                    .metadata
1935                    .get(field.as_str())
1936                    .is_some_and(|v| v.to_frontmatter_string() == *to_value);
1937                if !triggered {
1938                    return None;
1939                }
1940                let (_, unchecked) = transition_gate_standing(
1941                    store,
1942                    entity,
1943                    relationships,
1944                    *direction,
1945                    exclude,
1946                    checks,
1947                );
1948                if unchecked.is_empty() {
1949                    return None;
1950                }
1951                Some(UnsatisfiedConstraint::TransitionRequiresChecks {
1952                    field: field.clone(),
1953                    to_value: to_value.clone(),
1954                    relationships: relationships.clone(),
1955                    direction: *direction,
1956                    unchecked,
1957                    severity: *severity,
1958                })
1959            }
1960        })
1961        .collect()
1962}
1963
1964/// The standing of one gated-transition constraint's related set
1965/// against one entity, independent of whether the entity currently
1966/// holds the gated value: `(total related, those lacking a fresh
1967/// confirming check record)`, the unconfirmed sorted by id. THE single
1968/// related-set enumeration — shared by the write-time evaluator arm
1969/// above and the gates-brief renderer, so the brief can never disagree
1970/// with the refusal. Outgoing reads the entity's own edges (its
1971/// written state); incoming scans the store for edge sources pointing
1972/// at it, excluding the entity's own stored copy (`exclude`) so an
1973/// update never gates on its pre-write self.
1974pub fn transition_gate_standing(
1975    store: &Store,
1976    entity: &crate::entity::Entity,
1977    relationships: &[String],
1978    direction: memstead_schema::PropagationDirection,
1979    exclude: Option<&crate::entity::EntityId>,
1980    checks: Option<CheckStateProvider<'_>>,
1981) -> (usize, Vec<UncheckedRelated>) {
1982    let related: Vec<&crate::entity::Entity> = match direction {
1983        memstead_schema::PropagationDirection::Outgoing => entity
1984            .relationships
1985            .iter()
1986            .filter(|rel| relationships.contains(&rel.rel_type))
1987            .filter_map(|rel| store.get(&rel.target))
1988            .collect(),
1989        memstead_schema::PropagationDirection::Incoming => store
1990            .all_entities()
1991            .filter(|other| {
1992                other.id != entity.id
1993                    && Some(&other.id) != exclude
1994                    && other
1995                        .relationships
1996                        .iter()
1997                        .any(|rel| rel.target == entity.id && relationships.contains(&rel.rel_type))
1998            })
1999            .collect(),
2000    };
2001    let total = related.len();
2002    let mut unchecked: Vec<UncheckedRelated> = related
2003        .into_iter()
2004        .filter_map(|rel_entity| {
2005            // An ok check confirms only when it is independent of the
2006            // executors (engine::independence): the executor's own ok
2007            // reads `self_checked` here and does not close the gate.
2008            let standing = match checks {
2009                Some(provider) => provider(rel_entity),
2010                None => crate::engine::independence::CheckStanding {
2011                    state: crate::check::CheckState::NeverChecked,
2012                    independence: None,
2013                },
2014            };
2015            if standing.confirms() {
2016                None
2017            } else {
2018                Some(UncheckedRelated {
2019                    id: rel_entity.id.0.clone(),
2020                    state: standing.label().to_string(),
2021                })
2022            }
2023        })
2024        .collect();
2025    unchecked.sort_by(|a, b| a.id.cmp(&b.id));
2026    (total, unchecked)
2027}
2028
2029/// The entity's tuple of frontmatter values for `fields`, in
2030/// declaration order — `None` when any field is unset or blank (no
2031/// tuple, nothing to compare).
2032fn tuple_of(entity: &crate::entity::Entity, fields: &[String]) -> Option<Vec<String>> {
2033    fields
2034        .iter()
2035        .map(|f| {
2036            entity
2037                .metadata
2038                .get(f.as_str())
2039                .map(|v| v.to_frontmatter_string())
2040                .filter(|v| !v.trim().is_empty())
2041        })
2042        .collect()
2043}
2044
2045/// The bullet entries of a section body — trimmed text of `- item` /
2046/// `* item` lines. The legal-value shape `enum_from_neighbour` reads.
2047fn bullet_entries(body: &str) -> Vec<String> {
2048    // A bullet inside a code block is an example of the list, not a
2049    // member of it — the same referee every other content reader uses
2050    // ([`crate::markdown`]). Masking preserves byte offsets and line
2051    // count, so each masked line pairs with its original.
2052    let masked = crate::markdown::mask_code_blocks_and_spans(body);
2053    body.lines()
2054        .zip(masked.lines())
2055        .filter_map(|(line, masked_line)| {
2056            let m = masked_line.trim_start();
2057            if m.starts_with("- ") || m.starts_with("* ") {
2058                let t = line.trim_start();
2059                t.strip_prefix("- ")
2060                    .or_else(|| t.strip_prefix("* "))
2061                    .map(|e| e.trim().to_string())
2062            } else {
2063                None
2064            }
2065        })
2066        .collect()
2067}
2068
2069/// One entity's violated declared constraints, surfaced from the
2070/// health-time scan (`include=["constraints"]`). Mirrors
2071/// [`MissingRequiredOutgoingReport`]'s envelope shape — the two
2072/// includes read the same way.
2073#[derive(Debug, Clone, serde::Serialize)]
2074pub struct ConstraintFindingReport {
2075    pub id: crate::entity::EntityId,
2076    pub title: String,
2077    pub entity_type: String,
2078    pub mem: String,
2079    pub violations: Vec<UnsatisfiedConstraint>,
2080    /// Standing violations of the entity's declared section formats
2081    /// (plan 08) — additive: consumers of the pre-format shape see an
2082    /// absent key, never an empty list.
2083    #[serde(skip_serializing_if = "Vec::is_empty")]
2084    pub format_violations: Vec<crate::section_format::SectionFormatViolation>,
2085}
2086
2087/// Collect every non-stub entity whose declared `constraints` its
2088/// current state violates. Two passes: the per-entity forms
2089/// (`requires_when`, `unique`, `enum_from_neighbour`) through the
2090/// shared [`unsatisfied_constraints`] evaluation, then the
2091/// `status_propagation` graph sweep — for each entity holding a
2092/// declared terminal value, every entity reaching it (transitively)
2093/// via the declared rel-type and direction gains a finding naming that
2094/// tainting ancestor. Deterministic — reports sorted by `(mem, id)`,
2095/// violations in declaration order then by tainting ancestor.
2096pub fn collect_constraint_findings(
2097    store: &Store,
2098    mem_filter: Option<&str>,
2099    mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
2100    checks: Option<CheckStateProvider<'_>>,
2101) -> Vec<ConstraintFindingReport> {
2102    use memstead_schema::ConstraintDef;
2103    type Bucket = (
2104        Vec<UnsatisfiedConstraint>,
2105        Vec<crate::section_format::SectionFormatViolation>,
2106    );
2107    let mut by_entity: std::collections::BTreeMap<String, Bucket> = Default::default();
2108
2109    // Reverse adjacency for `must_reach` incoming walks — built once
2110    // per sweep, and only when some pinned schema declares one (a
2111    // workspace without the form pays nothing).
2112    let needs_reverse = mem_schemas.values().any(|s| {
2113        s.types.values().any(|t| {
2114            t.must_reach
2115                .iter()
2116                .any(|ob| ob.direction == memstead_schema::ReachDirection::In)
2117        })
2118    });
2119    let reverse: ReverseIndex = if needs_reverse {
2120        build_reverse_index(store)
2121    } else {
2122        ReverseIndex::default()
2123    };
2124
2125    for entity in store.all_entities() {
2126        if entity.stub {
2127            continue;
2128        }
2129        if let Some(v) = mem_filter
2130            && entity.mem != v
2131        {
2132            continue;
2133        }
2134        let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
2135            continue;
2136        };
2137        let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
2138            continue;
2139        };
2140
2141        // Section-format sweep (plan 08) — standing violations of a
2142        // declared markdown shape, every severity (block-tier
2143        // pre-existing violations are health findings too; the next
2144        // write of the section is the sanctioned repair point).
2145        for def in &td.sections {
2146            if def.compiled_content.is_none() {
2147                continue;
2148            }
2149            let Some(body) = entity.sections.get(def.key.as_str()) else {
2150                continue;
2151            };
2152            let violations = crate::section_format::check_section_format(def, body);
2153            if !violations.is_empty() {
2154                by_entity
2155                    .entry(entity.id.0.clone())
2156                    .or_default()
2157                    .1
2158                    .extend(violations);
2159            }
2160        }
2161
2162        // Reachability obligations — health-sweep only by design (no
2163        // single write completes a transitive absence, so the write
2164        // path never evaluates these). The finding echoes the whole
2165        // declaration.
2166        for ob in &td.must_reach {
2167            if !reaches_terminal(store, &reverse, &entity.id, ob) {
2168                by_entity.entry(entity.id.0.clone()).or_default().0.push(
2169                    UnsatisfiedConstraint::MustReach {
2170                        relationships: ob.relationships.clone(),
2171                        direction: ob.direction,
2172                        terminal_types: ob.terminal_types.clone(),
2173                        max_depth: ob.max_depth,
2174                        severity: ob.severity,
2175                    },
2176                );
2177            }
2178        }
2179
2180        if td.constraints.is_empty() {
2181            continue;
2182        }
2183
2184        // Pass 1 — per-entity forms.
2185        let violations = unsatisfied_constraints(store, entity, td, None, checks);
2186        if !violations.is_empty() {
2187            by_entity
2188                .entry(entity.id.0.clone())
2189                .or_default()
2190                .0
2191                .extend(violations);
2192        }
2193
2194        // Pass 2 — this entity as a taint source: it holds a declared
2195        // terminal value, so sweep its dependents. The taint walks
2196        // the declared relation set's union subgraph — a single
2197        // `rel_type` is a one-element set.
2198        for c in &td.constraints {
2199            let ConstraintDef::StatusPropagation {
2200                field,
2201                value,
2202                rel_type,
2203                rel_types,
2204                direction,
2205                severity,
2206            } = c
2207            else {
2208                continue;
2209            };
2210            let terminal = entity
2211                .metadata
2212                .get(field.as_str())
2213                .is_some_and(|v| v.to_frontmatter_string() == *value);
2214            if !terminal {
2215                continue;
2216            }
2217            let set = c
2218                .propagation_rel_types()
2219                .expect("StatusPropagation always yields a set");
2220            for tainted in reach_transitively(store, &entity.id, &set, *direction) {
2221                if let Some(v) = mem_filter
2222                    && tainted.mem() != v
2223                {
2224                    continue;
2225                }
2226                by_entity.entry(tainted.0.clone()).or_default().0.push(
2227                    UnsatisfiedConstraint::StatusPropagation {
2228                        field: field.clone(),
2229                        value: value.clone(),
2230                        rel_type: rel_type.clone(),
2231                        rel_types: rel_types.clone(),
2232                        tainted_by: entity.id.to_string(),
2233                        severity: *severity,
2234                    },
2235                );
2236            }
2237        }
2238    }
2239
2240    let mut out: Vec<ConstraintFindingReport> = by_entity
2241        .into_iter()
2242        .filter_map(|(id, (violations, format_violations))| {
2243            let id = crate::entity::EntityId(id);
2244            let entity = store.get(&id)?;
2245            Some(ConstraintFindingReport {
2246                id,
2247                title: entity.title.clone(),
2248                entity_type: entity.entity_type.clone(),
2249                mem: entity.mem.clone(),
2250                violations,
2251                format_violations,
2252            })
2253        })
2254        .collect();
2255    out.sort_by(|a, b| a.mem.cmp(&b.mem).then_with(|| a.id.0.cmp(&b.id.0)));
2256    out
2257}
2258
2259/// Transitive reachability along one rel-type from `start`, excluding
2260/// `start` itself. `Incoming` walks against edge direction (the
2261/// entities whose `rel_type` edges point at the frontier — "what
2262/// stands on this"); `Outgoing` follows the frontier's own edges.
2263/// Stubs are traversed (an edge through a stub still transmits the
2264/// taint) but stubs themselves are not returned.
2265fn reach_transitively(
2266    store: &Store,
2267    start: &crate::entity::EntityId,
2268    rel_types: &[String],
2269    direction: memstead_schema::PropagationDirection,
2270) -> Vec<crate::entity::EntityId> {
2271    use memstead_schema::PropagationDirection;
2272    let mut seen: std::collections::HashSet<crate::entity::EntityId> =
2273        std::iter::once(start.clone()).collect();
2274    let mut frontier = vec![start.clone()];
2275    let mut reached = Vec::new();
2276    while let Some(current) = frontier.pop() {
2277        let next: Vec<crate::entity::EntityId> = match direction {
2278            PropagationDirection::Incoming => store
2279                .all_entities()
2280                .filter(|e| {
2281                    e.relationships
2282                        .iter()
2283                        .any(|r| rel_types.iter().any(|n| n == &r.rel_type) && r.target == current)
2284                })
2285                .map(|e| e.id.clone())
2286                .collect(),
2287            PropagationDirection::Outgoing => store
2288                .get(&current)
2289                .map(|e| {
2290                    e.relationships
2291                        .iter()
2292                        .filter(|r| rel_types.iter().any(|n| n == &r.rel_type))
2293                        .map(|r| r.target.clone())
2294                        .collect()
2295                })
2296                .unwrap_or_default(),
2297        };
2298        for id in next {
2299            if seen.insert(id.clone()) {
2300                if store.get(&id).is_some_and(|e| !e.stub) {
2301                    reached.push(id.clone());
2302                }
2303                frontier.push(id);
2304            }
2305        }
2306    }
2307    reached
2308}
2309
2310/// Reverse adjacency for `must_reach` incoming walks: target id →
2311/// `(rel_type, source id)` pairs. Built once per sweep so the
2312/// incoming direction stays O(edges) instead of re-scanning the store
2313/// per frontier node.
2314type ReverseIndex =
2315    std::collections::HashMap<crate::entity::EntityId, Vec<(String, crate::entity::EntityId)>>;
2316
2317fn build_reverse_index(store: &Store) -> ReverseIndex {
2318    let mut idx = ReverseIndex::default();
2319    for entity in store.all_entities() {
2320        for rel in &entity.relationships {
2321            idx.entry(rel.target.clone())
2322                .or_default()
2323                .push((rel.rel_type.clone(), entity.id.clone()));
2324        }
2325    }
2326    idx
2327}
2328
2329/// Whether `start` reaches at least one non-stub entity of a terminal
2330/// type along the obligation's relation set, direction, and depth
2331/// bound. Breadth-first with visited-set discipline (cycles along the
2332/// walked set terminate); stubs terminate no obligation — they carry
2333/// no outgoing edges and never count as reached terminals. Cross-mem
2334/// edges are followed like any edge, matching the propagation walk
2335/// and the cycle check (the engine's established traversal posture);
2336/// the start entity itself never satisfies its own obligation.
2337fn reaches_terminal(
2338    store: &Store,
2339    reverse: &ReverseIndex,
2340    start: &crate::entity::EntityId,
2341    ob: &memstead_schema::MustReach,
2342) -> bool {
2343    use memstead_schema::ReachDirection;
2344    let mut seen: std::collections::HashSet<crate::entity::EntityId> =
2345        std::iter::once(start.clone()).collect();
2346    let mut frontier = vec![start.clone()];
2347    let mut depth: u32 = 0;
2348    while !frontier.is_empty() {
2349        if let Some(max) = ob.max_depth
2350            && depth >= max
2351        {
2352            return false;
2353        }
2354        depth += 1;
2355        let mut next_frontier = Vec::new();
2356        for current in frontier {
2357            let next: Vec<crate::entity::EntityId> = match ob.direction {
2358                ReachDirection::Out => store
2359                    .get(&current)
2360                    .map(|e| {
2361                        e.relationships
2362                            .iter()
2363                            .filter(|r| ob.relationships.iter().any(|n| n == &r.rel_type))
2364                            .map(|r| r.target.clone())
2365                            .collect()
2366                    })
2367                    .unwrap_or_default(),
2368                ReachDirection::In => reverse
2369                    .get(&current)
2370                    .map(|sources| {
2371                        sources
2372                            .iter()
2373                            .filter(|(rel, _)| ob.relationships.iter().any(|n| n == rel))
2374                            .map(|(_, src)| src.clone())
2375                            .collect()
2376                    })
2377                    .unwrap_or_default(),
2378            };
2379            for id in next {
2380                if seen.insert(id.clone()) {
2381                    if store.get(&id).is_some_and(|e| {
2382                        !e.stub && ob.terminal_types.iter().any(|t| t == &e.entity_type)
2383                    }) {
2384                        return true;
2385                    }
2386                    next_frontier.push(id);
2387                }
2388            }
2389        }
2390        frontier = next_frontier;
2391    }
2392    false
2393}
2394
2395/// One entity's above-`none` signals, surfaced from the include-gated
2396/// `signals` health axis. Mirrors [`ConstraintFindingReport`]'s
2397/// envelope shape; the `signals` entries carry value, level, and
2398/// contributors (the evidence ships with the number, always).
2399#[derive(Debug, Clone, serde::Serialize)]
2400pub struct SignalReport {
2401    pub id: crate::entity::EntityId,
2402    pub title: String,
2403    pub entity_type: String,
2404    pub mem: String,
2405    /// Only signals whose level is not `none`, in declaration order.
2406    pub signals: Vec<super::signals::ComputedSignal>,
2407}
2408
2409impl SignalReport {
2410    /// Whether any entry is `warn`-level — the `--strict`
2411    /// participation test (a `notice` never participates; that is the
2412    /// whole difference between the two levels).
2413    pub fn has_warn(&self) -> bool {
2414        self.signals
2415            .iter()
2416            .any(|s| s.level == Some(memstead_schema::SignalLevel::Warn))
2417    }
2418}
2419
2420/// Collect every non-stub entity carrying at least one declared
2421/// signal above `none`. Deterministic — sorted by `(mem, id)`;
2422/// signals in declaration order, contributors sorted.
2423pub fn collect_signal_reports(
2424    store: &Store,
2425    mem_filter: Option<&str>,
2426    mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
2427) -> Vec<SignalReport> {
2428    let mut out = Vec::new();
2429    for entity in store.all_entities() {
2430        if entity.stub {
2431            continue;
2432        }
2433        if let Some(v) = mem_filter
2434            && entity.mem != v
2435        {
2436            continue;
2437        }
2438        let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
2439            continue;
2440        };
2441        let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
2442            continue;
2443        };
2444        if td.signals.is_empty() {
2445            continue;
2446        }
2447        let above: Vec<super::signals::ComputedSignal> =
2448            super::signals::compute_signals(store, td, &entity.id)
2449                .into_iter()
2450                .filter(|s| s.level.is_some())
2451                .collect();
2452        if above.is_empty() {
2453            continue;
2454        }
2455        out.push(SignalReport {
2456            id: entity.id.clone(),
2457            title: entity.title.clone(),
2458            entity_type: entity.entity_type.clone(),
2459            mem: entity.mem.clone(),
2460            signals: above,
2461        });
2462    }
2463    out.sort_by(|a, b| a.mem.cmp(&b.mem).then_with(|| a.id.0.cmp(&b.id.0)));
2464    out
2465}
2466
2467/// A defective section-format declaration a loaded schema carries
2468/// (recorded by the lenient boot path; install would have refused).
2469/// Surfaced under the health `constraints` include so a sealed schema
2470/// with a bad declaration is visible without bricking boot.
2471#[derive(Debug, Clone, serde::Serialize)]
2472pub struct SchemaFormatDefect {
2473    pub schema: String,
2474    pub type_name: String,
2475    pub section: String,
2476    pub problems: Vec<String>,
2477}
2478
2479/// Collect the defective section-format declarations across the
2480/// mounted mems' pinned schemas, deduplicated per schema ref,
2481/// deterministic order.
2482pub fn collect_schema_format_defects(
2483    mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
2484) -> Vec<SchemaFormatDefect> {
2485    let mut seen: std::collections::BTreeSet<String> = Default::default();
2486    let mut out = Vec::new();
2487    let mut schemas: Vec<&Arc<memstead_schema::Schema>> = mem_schemas.values().collect();
2488    schemas.sort_by_key(|s| (s.manifest.name.clone(), s.version.clone()));
2489    for schema in schemas {
2490        let schema_ref = format!("{}@{}", schema.manifest.name, schema.version);
2491        if !seen.insert(schema_ref.clone()) {
2492            continue;
2493        }
2494        for td in schema.types.values() {
2495            for section in &td.sections {
2496                if !section.format_problems.is_empty() {
2497                    out.push(SchemaFormatDefect {
2498                        schema: schema_ref.clone(),
2499                        type_name: td.name.clone(),
2500                        section: section.key.clone(),
2501                        problems: section.format_problems.clone(),
2502                    });
2503                }
2504            }
2505        }
2506    }
2507    out.sort_by(|a, b| {
2508        (&a.schema, &a.type_name, &a.section).cmp(&(&b.schema, &b.type_name, &b.section))
2509    });
2510    out
2511}
2512
2513/// One entity's unsatisfied `required_outgoing` blocks, surfaced from
2514/// the health-time scan. `missing` reuses the per-write warning's wire
2515/// block type — one struct, one serialized shape (`{ relationships,
2516/// cardinality }`) on both surfaces — and adds the `mem` name (the
2517/// warning's `entity_id` already encodes it via the mem prefix, but
2518/// health is multi-mem by default and an explicit field is cheaper for
2519/// downstream filters).
2520#[derive(Debug, Clone, serde::Serialize)]
2521pub struct MissingRequiredOutgoingReport {
2522    pub id: crate::entity::EntityId,
2523    pub title: String,
2524    pub entity_type: String,
2525    pub mem: String,
2526    pub missing: Vec<super::MissingRequiredOutgoingBlock>,
2527}
2528
2529/// Render the workspace-config projection the health surface serves —
2530/// per-writable-mem detail (`origin`, storage/durability, `vcs`
2531/// `gitdir`/`worktree`/`head`, title/subject, `write_guidance`,
2532/// `extra`) plus the `mutations` and `plugin` policy values. One
2533/// implementation, every surface: the MCP composer reaches it through
2534/// `include_config: true` OR the `config` include key; the CLI through
2535/// `--include config`. `mutations` / `plugin` are passed prebuilt so a
2536/// server that owns its own copies inserts them verbatim; callers
2537/// without server state derive them from `Engine::settings()` (see
2538/// [`config_projection_from_settings`]). Returns the three top-level
2539/// entries (`mems`, `mutations`, `plugin`) for the caller to merge —
2540/// callers gate on their own opt-in flag and must render at most once.
2541pub fn config_projection(
2542    engine: &crate::Engine,
2543    writable_mems: &[String],
2544    mutations: serde_json::Value,
2545    plugin: serde_json::Value,
2546) -> serde_json::Map<String, serde_json::Value> {
2547    // Per-mem storage backend → durability marker, derived from the
2548    // mount's `MountStorage` kind. Lives alongside `vcs` so an agent
2549    // reading per-mem config learns whether a `write_id` this mem
2550    // returns is durable-on-disk or volatile-in-RAM.
2551    let backend_by_mem: std::collections::HashMap<&str, (&'static str, bool)> = engine
2552        .mounts()
2553        .iter()
2554        .map(|m| {
2555            (
2556                m.mem.as_str(),
2557                (m.storage.backend_id(), m.storage.is_durable()),
2558            )
2559        })
2560        .collect();
2561    let mems_detail: Vec<serde_json::Value> = writable_mems
2562        .iter()
2563        .map(|name| {
2564            let origin = engine
2565                .mem_router()
2566                .origin_for_mem(name)
2567                .map(|o| o.kind())
2568                .unwrap_or("explicit");
2569            let mut entry = serde_json::Map::new();
2570            entry.insert("name".into(), serde_json::json!(name));
2571            entry.insert("origin".into(), serde_json::json!(origin));
2572            if let Some((storage, durable)) = backend_by_mem.get(name.as_str()).copied() {
2573                entry.insert("storage".into(), serde_json::json!(storage));
2574                entry.insert("durable".into(), serde_json::json!(durable));
2575            }
2576            let mut vcs_obj = serde_json::Map::new();
2577            if let Ok(gitdir) = engine.gitdir_for(name) {
2578                vcs_obj.insert("gitdir".into(), serde_json::json!(gitdir));
2579            }
2580            if let Ok(worktree) = engine.worktree_for(name) {
2581                vcs_obj.insert("worktree".into(), serde_json::json!(worktree));
2582            }
2583            if let Some(sha) = engine.mem_head_sha(name).ok().flatten() {
2584                vcs_obj.insert("head".into(), serde_json::json!(sha));
2585            }
2586            if !vcs_obj.is_empty() {
2587                entry.insert("vcs".into(), serde_json::Value::Object(vcs_obj));
2588            }
2589            if let Some(cfg) = engine.mem_config_for(name) {
2590                // Display title + subject block, when set — the
2591                // config projection prefers the title wherever a
2592                // mem is printed; the name stays the identity.
2593                if let Some(title) = &cfg.title {
2594                    entry.insert("title".into(), serde_json::json!(title));
2595                }
2596                if let Some(subject) = &cfg.subject {
2597                    entry.insert("subject".into(), serde_json::json!(subject));
2598                }
2599                let guidance = serde_json::Map::from_iter(
2600                    cfg.write_guidance
2601                        .iter()
2602                        .map(|(k, v)| (k.clone(), v.clone())),
2603                );
2604                entry.insert("write_guidance".into(), serde_json::Value::Object(guidance));
2605                let extra = serde_json::Map::from_iter(
2606                    cfg.extra.iter().map(|(k, v)| (k.clone(), v.clone())),
2607                );
2608                entry.insert("extra".into(), serde_json::Value::Object(extra));
2609            }
2610            serde_json::Value::Object(entry)
2611        })
2612        .collect();
2613
2614    let mut out = serde_json::Map::new();
2615    out.insert("mems".into(), serde_json::json!(mems_detail));
2616    out.insert("mutations".into(), mutations);
2617    out.insert("plugin".into(), plugin);
2618    out
2619}
2620
2621/// The `(mutations, plugin)` pair for [`config_projection`], derived
2622/// from the engine's own [`crate::workspace::WorkspaceSettings`] — for
2623/// callers (the CLI) that carry no server-owned config copies. Produces
2624/// the same bytes the MCP server passes when both were loaded from the
2625/// same `workspace.toml`.
2626pub fn config_projection_from_settings(
2627    settings: &crate::workspace::WorkspaceSettings,
2628) -> (serde_json::Value, serde_json::Value) {
2629    let mutations = serde_json::json!({ "require_notes": settings.mutations.require_notes });
2630    let plugin_map: serde_json::Map<String, serde_json::Value> = settings
2631        .plugin
2632        .iter()
2633        .map(|(k, v)| {
2634            (
2635                k.clone(),
2636                serde_json::to_value(v).unwrap_or(serde_json::Value::Null),
2637            )
2638        })
2639        .collect();
2640    (mutations, serde_json::Value::Object(plugin_map))
2641}
2642
2643/// Detect the section-fork condition for one declared section: the
2644/// parsed content under `key` is empty, the schema's declared heading
2645/// for the key does not derive back to it
2646/// (`derive_section_key(heading) != key`), and the file carries that
2647/// declared heading — so the content is present in the file but
2648/// unreachable under the key: absorbed into the catch-all when the
2649/// type declares one, dropped from the parsed sections otherwise.
2650///
2651/// Returns the distinct `SECTION_HEADING_MISMATCH` issue naming both
2652/// the found heading and what a deriving heading would look like. The
2653/// caller must NOT also report the section as missing — collapsing the
2654/// two conditions into the missing-section report is exactly the
2655/// misdirection this finding exists to prevent (the operator goes
2656/// hunting for absent content that is in fact present).
2657pub(crate) fn section_heading_mismatch_issue(
2658    entity: &crate::entity::Entity,
2659    schema: &TypeDefinition,
2660    key: &str,
2661) -> Option<HealthIssue> {
2662    let def = schema.section(key)?;
2663    let derived = memstead_schema::derive_section_key(&def.heading);
2664    if derived == key {
2665        return None;
2666    }
2667    if !entity
2668        .raw_section_headings
2669        .iter()
2670        .any(|h| h == &def.heading)
2671    {
2672        return None;
2673    }
2674    let landing = match schema.catch_all_section() {
2675        Some(c) => format!(
2676            "the content was absorbed into catch-all section '{}'",
2677            c.key
2678        ),
2679        None => "the content is unreachable under any declared key".to_string(),
2680    };
2681    Some(HealthIssue {
2682        field: key.to_string(),
2683        code: super::HealthIssueCode::SectionHeadingMismatch,
2684        message: format!(
2685            "SECTION_HEADING_MISMATCH: section '{key}' is not missing — its content sits \
2686             under heading '{found}', which derives to '{derived}', not '{key}'; {landing}. \
2687             The schema's declared heading cannot round-trip to its key (expected a heading \
2688             that derives to '{key}'); fix the schema's heading/key pair — new installs of \
2689             such a schema are refused",
2690            found = def.heading,
2691        ),
2692    })
2693}
2694
2695/// Get a single entity's health report.
2696pub fn entity_health(entity: &crate::entity::Entity, schema: &TypeDefinition) -> HealthReport {
2697    let mut issues = Vec::new();
2698
2699    for field in &schema.health_required_fields {
2700        if schema.section(field).is_some() {
2701            let content = entity.sections.get(field.as_str());
2702            if content.is_none_or(|c| c.trim().is_empty()) {
2703                if let Some(issue) = section_heading_mismatch_issue(entity, schema, field) {
2704                    issues.push(issue);
2705                } else {
2706                    issues.push(HealthIssue {
2707                        field: field.clone(),
2708                        code: super::HealthIssueCode::Missing,
2709                        message: format!("required section '{field}' is empty"),
2710                    });
2711                }
2712            }
2713        } else {
2714            let value = entity.metadata.get(field.as_str());
2715            if value.is_none() {
2716                issues.push(HealthIssue {
2717                    field: field.clone(),
2718                    code: super::HealthIssueCode::Missing,
2719                    message: format!("required field '{field}' is missing"),
2720                });
2721            }
2722        }
2723    }
2724
2725    // The mismatch condition is drift worth surfacing on every declared
2726    // section, not only the health-required ones — an optional section
2727    // whose content forked away is just as invisible to readers.
2728    for s in schema.sections.iter().filter(|s| !s.catch_all) {
2729        if schema.health_required_fields.contains(&s.key) {
2730            continue; // already handled above
2731        }
2732        let content = entity.sections.get(s.key.as_str());
2733        if content.is_none_or(|c| c.trim().is_empty())
2734            && let Some(issue) = section_heading_mismatch_issue(entity, schema, &s.key)
2735        {
2736            issues.push(issue);
2737        }
2738    }
2739
2740    let total = schema.health_required_fields.len();
2741    let score = if total > 0 {
2742        (total.saturating_sub(issues.len()) as f32) / (total as f32)
2743    } else {
2744        1.0
2745    };
2746
2747    HealthReport {
2748        id: entity.id.clone(),
2749        title: entity.title.clone(),
2750        score,
2751        issues,
2752    }
2753}
2754
2755// ---------------------------------------------------------------------------
2756// Date helpers
2757// ---------------------------------------------------------------------------
2758
2759/// Get current days since Unix epoch.
2760///
2761/// `SystemTime::now()` is unimplemented on `wasm32-unknown-unknown` —
2762/// it traps with `RuntimeError: unreachable` and poisons the wasm
2763/// instance (cold-start F11) — so the wasm build reads the JS-backed
2764/// clock instead. Same value, same summary shape on every target.
2765/// Today as whole days since the Unix epoch, the clock every day-threshold
2766/// reading in health uses. `MEMSTEAD_TODAY=YYYY-MM-DD` pins it (the
2767/// injection a fixture needs to age entities without waiting), honoured
2768/// by every binary alike so the CLI and the MCP server read the same day.
2769pub fn days_since_epoch() -> u64 {
2770    if let Some(pinned) = std::env::var("MEMSTEAD_TODAY")
2771        .ok()
2772        .and_then(|s| crate::engine::due::pinned_days_since_epoch(&s))
2773    {
2774        return pinned;
2775    }
2776    #[cfg(target_arch = "wasm32")]
2777    {
2778        (js_sys::Date::now() / 1000.0) as u64 / 86400
2779    }
2780    #[cfg(not(target_arch = "wasm32"))]
2781    {
2782        std::time::SystemTime::now()
2783            .duration_since(std::time::UNIX_EPOCH)
2784            .unwrap_or_default()
2785            .as_secs()
2786            / 86400
2787    }
2788}
2789
2790/// Parse an ISO 8601 date string to days since epoch.
2791/// Supports `YYYY-MM-DD` and `YYYY-MM-DDTHH:MM:SSZ`.
2792pub fn parse_iso_to_days(date: &str) -> Option<u64> {
2793    let date_part = date.split('T').next()?;
2794    let parts: Vec<&str> = date_part.split('-').collect();
2795    if parts.len() != 3 {
2796        return None;
2797    }
2798    let year: u64 = parts[0].parse().ok()?;
2799    let month: u64 = parts[1].parse().ok()?;
2800    let day: u64 = parts[2].parse().ok()?;
2801    Some(ymd_to_days(year, month, day))
2802}
2803
2804/// Convert (year, month, day) to days since Unix epoch.
2805/// Inverse of the algorithm in generator.rs.
2806fn ymd_to_days(year: u64, month: u64, day: u64) -> u64 {
2807    // Algorithm from http://howardhinnant.github.io/date_algorithms.html
2808    let y = if month <= 2 { year - 1 } else { year };
2809    let m = if month <= 2 { month + 9 } else { month - 3 };
2810    let era = y / 400;
2811    let yoe = y - era * 400;
2812    let doy = (153 * m + 2) / 5 + day - 1;
2813    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
2814    let days = era * 146097 + doe;
2815    days - 719468
2816}
2817
2818#[cfg(test)]
2819mod tests {
2820    use super::*;
2821    use crate::entity::{Entity, EntityId, MetadataValue};
2822    use crate::ops::DanglingLinkKind;
2823    use crate::store::Store;
2824    use indexmap::IndexMap;
2825    use memstead_schema::type_by_name;
2826
2827    /// A bullet inside a code block is an example of the list, not a
2828    /// member of it. `enum_from_neighbour` harvests legal values from a
2829    /// neighbour's section body, so an unmasked scan would accept any
2830    /// value someone documented in a fenced sample.
2831    #[test]
2832    fn bullet_entries_ignores_code() {
2833        let body = "- real-one\n- real-two\n\n```\n- fenced-ghost\n```\n\n    - indented-ghost\n\nA `- span-ghost` sample.\n";
2834        let entries = bullet_entries(body);
2835        assert_eq!(
2836            entries,
2837            vec!["real-one".to_string(), "real-two".to_string()],
2838            "only prose bullets are legal values: {entries:?}"
2839        );
2840    }
2841
2842    /// Complement: indentation, `*` markers and inline formatting in a
2843    /// prose bullet all still read exactly as before — the entry text
2844    /// comes from the original, not the mask.
2845    #[test]
2846    fn bullet_entries_still_reads_prose_bullets_verbatim() {
2847        let entries = bullet_entries("- alpha\n  * beta\n* `gamma`\n");
2848        assert_eq!(
2849            entries,
2850            vec![
2851                "alpha".to_string(),
2852                "beta".to_string(),
2853                "`gamma`".to_string()
2854            ]
2855        );
2856    }
2857
2858    /// A destination config
2859    /// declaring its process mem resolves the pairing regardless of
2860    /// naming — with no binding at all — and a declaration naming a
2861    /// missing mem surfaces as the typed finding, never a silent
2862    /// fallback.
2863    #[test]
2864    fn declared_process_mem_pairs_and_missing_declaration_is_typed() {
2865        use crate::engine::test_helpers::folder_mount;
2866        let tmp = tempfile::TempDir::new().unwrap();
2867        let dest_dir = tmp.path().join("dest");
2868        let proc_dir = tmp.path().join("oddly-named-process");
2869        std::fs::create_dir_all(dest_dir.join(".memstead")).unwrap();
2870        std::fs::create_dir_all(&proc_dir).unwrap();
2871        // Declaration: the destination pairs with a mem whose name no
2872        // convention would derive.
2873        std::fs::write(
2874            dest_dir.join(".memstead").join("config.json"),
2875            r#"{ "schema": "default@1.0.0", "processMem": "oddly-named-process" }"#,
2876        )
2877        .unwrap();
2878        let engine = crate::Engine::from_mounts(vec![
2879            (
2880                folder_mount("dest", dest_dir.clone()),
2881                Box::new(crate::storage::FilesystemMemWriter::new(dest_dir.clone()))
2882                    as Box<dyn crate::backend::MemBackend>,
2883            ),
2884            (
2885                folder_mount("oddly-named-process", proc_dir.clone()),
2886                Box::new(crate::storage::FilesystemMemWriter::new(proc_dir))
2887                    as Box<dyn crate::backend::MemBackend>,
2888            ),
2889        ])
2890        .unwrap();
2891
2892        // The one resolution function: declaration wins.
2893        let r = crate::ingest::resolve::resolve_process_mem(&engine, "dest", "dest-derived");
2894        assert!(r.declared && r.mounted);
2895        assert_eq!(r.mem, "oddly-named-process");
2896        // No declaration → derivation fallback, byte-identical to the
2897        // pre-declaration behaviour.
2898        let r =
2899            crate::ingest::resolve::resolve_process_mem(&engine, "oddly-named-process", "whatever");
2900        assert!(!r.declared && !r.mounted);
2901        assert_eq!(r.mem, "whatever");
2902
2903        // The axis pairs the declared mem with no binding present.
2904        let axis = health_open_questions_axis(&engine, Some("dest"));
2905        let process = &axis["dest"]["process"];
2906        assert_eq!(process[0]["process_mem"], "oddly-named-process", "{axis}");
2907        assert_eq!(process[0]["declared"], true, "{axis}");
2908        assert_eq!(process[0]["resolvable"], true, "{axis}");
2909
2910        // Declaration naming a missing mem: typed finding.
2911        std::fs::write(
2912            dest_dir.join(".memstead").join("config.json"),
2913            r#"{ "schema": "default@1.0.0", "processMem": "nowhere" }"#,
2914        )
2915        .unwrap();
2916        let engine2 = crate::Engine::from_mounts(vec![(
2917            folder_mount("dest", dest_dir.clone()),
2918            Box::new(crate::storage::FilesystemMemWriter::new(dest_dir))
2919                as Box<dyn crate::backend::MemBackend>,
2920        )])
2921        .unwrap();
2922        let axis = health_open_questions_axis(&engine2, Some("dest"));
2923        let process = &axis["dest"]["process"];
2924        assert_eq!(
2925            process[0]["finding"], "DECLARED_PROCESS_MEM_MISSING",
2926            "{axis}"
2927        );
2928        assert_eq!(process[0]["resolvable"], false, "{axis}");
2929    }
2930
2931    /// The independence gate compares
2932    /// caller-declared identities and nothing else (with
2933    /// the transport complement): equal identities read
2934    /// `self_checked` even across DIFFERING `(actor, client)` pairs,
2935    /// differing identities read `confirmed_independent` even on the
2936    /// SAME pair, a missing identity on either side reads
2937    /// `unconfirmable` — the pair provably does not participate.
2938    #[test]
2939    fn independence_gate_compares_identities_only() {
2940        use crate::engine::test_helpers::folder_mount;
2941        let tmp = tempfile::TempDir::new().unwrap();
2942        let dir = tmp.path().join("gate");
2943        std::fs::create_dir_all(&dir).unwrap();
2944        let mut engine = crate::Engine::from_mounts(vec![(
2945            folder_mount("gate", dir.clone()),
2946            Box::new(crate::storage::FilesystemMemWriter::new(dir))
2947                as Box<dyn crate::backend::MemBackend>,
2948        )])
2949        .unwrap();
2950        engine.set_workspace_root(tmp.path().to_path_buf());
2951
2952        let create = |engine: &mut crate::Engine, title: &str, identity: Option<&str>| {
2953            engine.set_identity(identity.map(str::to_string));
2954            engine
2955                .create_entity(
2956                    crate::CreateEntityArgs {
2957                        mem: "gate".to_string(),
2958                        title: title.to_string(),
2959                        entity_type: "spec".to_string(),
2960                        sections: [
2961                            ("identity".to_string(), "x".to_string()),
2962                            ("purpose".to_string(), "y".to_string()),
2963                        ]
2964                        .into_iter()
2965                        .collect(),
2966                        metadata: Default::default(),
2967                        relations: Vec::new(),
2968                        anchors: Vec::new(),
2969                        dry_run: false,
2970                    },
2971                    crate::vcs::Actor::Cli,
2972                    None,
2973                    None,
2974                )
2975                .unwrap()
2976                .id
2977                .0
2978        };
2979        let a = create(&mut engine, "Self Checked", Some("alice"));
2980        let b = create(&mut engine, "Independent", Some("alice"));
2981        let c = create(&mut engine, "No Author Identity", None);
2982
2983        let check = |engine: &mut crate::Engine,
2984                     id: &str,
2985                     identity: Option<&str>,
2986                     actor: crate::vcs::Actor,
2987                     client: Option<&crate::vcs::ClientId>| {
2988            engine.set_identity(identity.map(str::to_string));
2989            engine
2990                .record_check(
2991                    "gate",
2992                    id,
2993                    crate::check::Verdict::Ok,
2994                    crate::check::CheckKind::Verification,
2995                    None,
2996                    actor,
2997                    client,
2998                )
2999                .unwrap();
3000        };
3001        let other_client = crate::vcs::ClientId {
3002            name: "claude-code".into(),
3003            version: "9.9".into(),
3004        };
3005        // a: authored (cli, no client), checked (agent, claude-code) —
3006        // DIFFERING pairs, equal identities → self_checked.
3007        check(
3008            &mut engine,
3009            &a,
3010            Some("alice"),
3011            crate::vcs::Actor::Agent,
3012            Some(&other_client),
3013        );
3014        // b: SAME pair as its author record, differing identities →
3015        // confirmed_independent.
3016        check(&mut engine, &b, Some("bob"), crate::vcs::Actor::Cli, None);
3017        // c: checker declared, author never did → unconfirmable.
3018        check(&mut engine, &c, Some("carol"), crate::vcs::Actor::Cli, None);
3019
3020        let axis = health_checks_axis(&engine, Some("gate"));
3021        let gate = &axis["gate"]["independence"];
3022        assert_eq!(
3023            gate["self_checked"]["items"],
3024            serde_json::json!([a]),
3025            "{axis}"
3026        );
3027        assert_eq!(
3028            gate["confirmed_independent"]["items"],
3029            serde_json::json!([b]),
3030            "{axis}"
3031        );
3032        assert_eq!(
3033            gate["unconfirmable"]["items"],
3034            serde_json::json!([c]),
3035            "{axis}"
3036        );
3037
3038        // The recorded identity is served by the provenance block and
3039        // the check record (the engine half of the gate).
3040        let prov = engine.entity_provenance("gate", &a).unwrap();
3041        assert_eq!(
3042            prov.created_by.as_ref().and_then(|r| r.identity.as_deref()),
3043            Some("alice"),
3044            "created-by serves the declared identity"
3045        );
3046        assert_eq!(
3047            prov.last_check.as_ref().and_then(|r| r.identity.as_deref()),
3048            Some("alice"),
3049            "the check record serves the declared identity"
3050        );
3051    }
3052
3053    fn make_entity(name: &str, has_required: bool) -> Entity {
3054        let mut metadata = IndexMap::new();
3055        metadata.insert("level".into(), MetadataValue::String("M0".into()));
3056        metadata.insert("type".into(), MetadataValue::String("spec".into()));
3057        metadata.insert(
3058            "created_date".into(),
3059            MetadataValue::String("2026-01-15".into()),
3060        );
3061        metadata.insert(
3062            "last_modified".into(),
3063            MetadataValue::String("2026-04-12".into()),
3064        );
3065
3066        let mut sections = IndexMap::new();
3067        if has_required {
3068            sections.insert("identity".into(), "Has identity.".into());
3069            sections.insert("purpose".into(), "Has purpose.".into());
3070        }
3071
3072        Entity {
3073            id: EntityId::new("specs", name),
3074            title: name.into(),
3075            entity_type: "spec".into(),
3076            mem: "specs".into(),
3077            file_path: format!("{name}.md"),
3078            metadata,
3079            sections,
3080            relationships: Vec::new(),
3081            content_hash: String::new(),
3082            stub: false,
3083            stub_kind: None,
3084            heading_spans: std::collections::HashMap::new(),
3085            raw_section_headings: Vec::new(),
3086        }
3087    }
3088
3089    /// A sealed-violator type: section key `answers` with heading
3090    /// `Answers argued` (derives to `answers_argued`) — the plenum
3091    /// finding's exact shape. Loads fine; only new installs refuse.
3092    fn violating_type() -> std::sync::Arc<TypeDefinition> {
3093        let manifest = r#"name: debate
3094version: 0.1.0
3095description: sealed-violator fixture
3096when_to_use: health tests
3097types:
3098  - question
3099relationships:
3100  mode: strict
3101  definitions:
3102    - name: PART_OF
3103      description: hier
3104      default_weight: 3.0
3105    - name: _default
3106      description: fallback
3107      default_weight: 1.0
3108community:
3109  resolution: 1.0
3110  seed: 42
3111"#;
3112        let type_yaml = r#"name: question
3113description: t
3114when_to_use: tests
3115sections:
3116  - key: answers
3117    heading: Answers argued
3118    required: true
3119    search_weight: 10.0
3120    write_rules: []
3121  - key: notes
3122    heading: Notes
3123    required: false
3124    search_weight: 3.0
3125    catch_all: true
3126    write_rules: []
3127metadata_fields: []
3128title_weight: 100.0
3129text_fields:
3130  - answers
3131  - notes
3132hierarchy_relationship: PART_OF
3133no_self_loop_relationships: []
3134updatable_fields:
3135  - title
3136  - answers
3137  - notes
3138health_required_fields:
3139  - answers
3140staleness_threshold_days: 90
3141write_rules: []
3142"#;
3143        memstead_schema::load_schema_from_memory(
3144            manifest,
3145            &[("question".to_string(), type_yaml.to_string())],
3146        )
3147        .expect("violating schema still loads")
3148        .get_type("question")
3149        .expect("question type")
3150    }
3151
3152    /// Health must report the distinct SECTION_HEADING_MISMATCH finding
3153    /// — naming both headings and the catch-all the content landed in —
3154    /// for content sitting under a non-deriving heading, and must NOT
3155    /// report that section as missing. A genuinely absent section keeps
3156    /// the missing report; a conforming entity gets neither.
3157    #[test]
3158    fn health_distinguishes_heading_mismatch_from_missing_section() {
3159        let schema = violating_type();
3160
3161        // Content present under the declared (non-deriving) heading.
3162        let md = "---\ntype: question\n---\n# Q\n\n## Answers argued\n\nTwo answers.\n";
3163        let parsed = crate::entity::parser::parse_markdown(md, "q.md", &schema, "debate")
3164            .expect("parses")
3165            .entity;
3166        let report = entity_health(&parsed, &schema);
3167        let mismatch: Vec<_> = report
3168            .issues
3169            .iter()
3170            .filter(|i| i.code == super::super::HealthIssueCode::SectionHeadingMismatch)
3171            .collect();
3172        assert_eq!(mismatch.len(), 1, "issues: {:?}", report.issues);
3173        let msg = &mismatch[0].message;
3174        assert!(
3175            msg.contains("'Answers argued'") && msg.contains("'answers_argued'"),
3176            "names found heading and derived key: {msg}"
3177        );
3178        assert!(
3179            msg.contains("'notes'"),
3180            "names the catch-all landing: {msg}"
3181        );
3182        assert!(
3183            !report.issues.iter().any(|i| i.message.contains("is empty")),
3184            "must not also report the section as missing: {:?}",
3185            report.issues
3186        );
3187
3188        // Genuinely missing section: missing report exactly as today.
3189        let md_missing = "---\ntype: question\n---\n# Q2\n";
3190        let parsed_missing =
3191            crate::entity::parser::parse_markdown(md_missing, "q2.md", &schema, "debate")
3192                .expect("parses")
3193                .entity;
3194        let report_missing = entity_health(&parsed_missing, &schema);
3195        assert!(
3196            report_missing
3197                .issues
3198                .iter()
3199                .any(|i| i.code == super::super::HealthIssueCode::Missing
3200                    && i.message == "required section 'answers' is empty"),
3201            "absent section keeps the missing report (structured MISSING code): {:?}",
3202            report_missing.issues
3203        );
3204        assert!(
3205            !report_missing
3206                .issues
3207                .iter()
3208                .any(|i| i.code == super::super::HealthIssueCode::SectionHeadingMismatch),
3209            "no mismatch finding when the heading is not in the file"
3210        );
3211
3212        // Conforming entity (content under a heading deriving to the
3213        // key would need a deriving heading — for this violating
3214        // schema no heading can reach `answers`, so use the conforming
3215        // catch-all only): neither finding for a section with content.
3216        let ok_type = crate::entity::parser::parse_markdown(
3217            "---\ntype: question\n---\n# Q3\n\n## Answers\n\nfree.\n",
3218            "q3.md",
3219            &schema,
3220            "debate",
3221        )
3222        .expect("parses")
3223        .entity;
3224        let report_ok = entity_health(&ok_type, &schema);
3225        assert!(
3226            !report_ok
3227                .issues
3228                .iter()
3229                .any(|i| i.code == super::super::HealthIssueCode::SectionHeadingMismatch),
3230            "mismatch fires only when the declared heading is present: {:?}",
3231            report_ok.issues
3232        );
3233    }
3234
3235    fn make_concept_entity(name: &str, with_definition: bool) -> Entity {
3236        let mut metadata = IndexMap::new();
3237        metadata.insert("type".into(), MetadataValue::String("concept".into()));
3238        metadata.insert("maturity".into(), MetadataValue::String("emerging".into()));
3239        metadata.insert(
3240            "abstraction_level".into(),
3241            MetadataValue::String("concrete".into()),
3242        );
3243        metadata.insert(
3244            "created_date".into(),
3245            MetadataValue::String("2026-01-15".into()),
3246        );
3247        metadata.insert(
3248            "last_modified".into(),
3249            MetadataValue::String("2026-04-12".into()),
3250        );
3251
3252        let mut sections = IndexMap::new();
3253        if with_definition {
3254            sections.insert("definition".into(), "Precise definition.".into());
3255        }
3256        sections.insert("explanation".into(), "How it works.".into());
3257
3258        Entity {
3259            id: EntityId::new("concepts", name),
3260            title: name.into(),
3261            entity_type: "concept".into(),
3262            mem: "concepts".into(),
3263            file_path: format!("{name}.md"),
3264            metadata,
3265            sections,
3266            relationships: Vec::new(),
3267            content_hash: String::new(),
3268            stub: false,
3269            stub_kind: None,
3270            heading_spans: std::collections::HashMap::new(),
3271            raw_section_headings: Vec::new(),
3272        }
3273    }
3274
3275    #[test]
3276    fn health_concept_missing_definition_reports_definition_field() {
3277        let schema = &type_by_name("concept").unwrap();
3278        let entity = make_concept_entity("clarity", false);
3279        let report = entity_health(&entity, schema);
3280
3281        // The missing-field issue must name the concept schema's required
3282        // section ("definition"), not spec's "identity".
3283        assert!(report.issues.iter().any(|i| i.field == "definition"));
3284        assert!(!report.issues.iter().any(|i| i.field == "identity"));
3285        assert!(!report.issues.iter().any(|i| i.field == "purpose"));
3286        assert!(report.score < 1.0);
3287
3288        // An entity with the definition filled in has no issue for that field.
3289        let healthy = make_concept_entity("clarity-ok", true);
3290        let healthy_report = entity_health(&healthy, schema);
3291        assert!(
3292            !healthy_report
3293                .issues
3294                .iter()
3295                .any(|i| i.field == "definition")
3296        );
3297    }
3298
3299    #[test]
3300    fn health_detects_missing_sections() {
3301        let schema = &type_by_name("spec").unwrap();
3302        let entity = make_entity("incomplete", false);
3303        let report = entity_health(&entity, schema);
3304        assert!(!report.issues.is_empty());
3305        assert!(report.score < 1.0);
3306    }
3307
3308    #[test]
3309    fn health_clean_entity() {
3310        let schema = &type_by_name("spec").unwrap();
3311        let entity = make_entity("complete", true);
3312        let report = entity_health(&entity, schema);
3313        // May still have issues for other required fields, but identity/purpose are covered
3314        let section_issues: Vec<_> = report
3315            .issues
3316            .iter()
3317            .filter(|i| i.field == "identity" || i.field == "purpose")
3318            .collect();
3319        assert!(section_issues.is_empty());
3320    }
3321
3322    #[test]
3323    fn health_summary_counts() {
3324        let mut store = Store::new();
3325        let e1 = make_entity("healthy", true);
3326        let e2 = make_entity("unhealthy", false);
3327        store.upsert(e1.id.clone(), e1);
3328        store.upsert(e2.id.clone(), e2);
3329
3330        let schema = &type_by_name("spec").unwrap();
3331        let summary = compute_health(&store, schema, &HashMap::new(), None);
3332        assert_eq!(summary.orphan_count, 2); // No edges between them
3333        assert_eq!(summary.stub_count, 0);
3334    }
3335
3336    #[test]
3337    fn health_surfaces_invalid_rel_shape_on_existing_edges() {
3338        // software@0.1.0 declares `source_types: [actor]` on OWNS.
3339        // Seed a non-actor source with an outgoing OWNS edge — the
3340        // health scan must surface `INVALID_REL_SHAPE` in the
3341        // entity's issues so an agent running a sweep can identify
3342        // edges to clean up via `memstead_relate remove=true`.
3343        use crate::entity::Relationship;
3344        use memstead_schema::SchemaRegistry;
3345
3346        let registry = SchemaRegistry::builtin();
3347        let software = registry
3348            .get("software", &semver::Version::new(0, 2, 0))
3349            .expect("software schema ships as a builtin");
3350
3351        let mut store = Store::new();
3352        // Source entity is `spec`, not `actor`. Add an OWNS edge to
3353        // a target whose type doesn't matter for source-side shape.
3354        let mut bad = make_entity("bad-owns-source", true);
3355        bad.entity_type = "spec".into();
3356        bad.metadata
3357            .insert("level".into(), MetadataValue::String("M0".into()));
3358        bad.metadata
3359            .insert("stability".into(), MetadataValue::String("evolving".into()));
3360        bad.relationships.push(Relationship {
3361            rel_type: "OWNS".into(),
3362            target: EntityId::new("specs", "victim"),
3363            description: None,
3364        });
3365        let mut victim = make_entity("victim", true);
3366        victim.entity_type = "spec".into();
3367        store.upsert(bad.id.clone(), bad);
3368        store.upsert(victim.id.clone(), victim);
3369
3370        let mut mem_schemas = HashMap::new();
3371        mem_schemas.insert("specs".to_string(), software);
3372
3373        let schema = &type_by_name("spec").unwrap();
3374        let summary = compute_health(&store, schema, &mem_schemas, None);
3375        let report = summary
3376            .missing_fields
3377            .iter()
3378            .find(|r| r.id.as_ref() == "specs--bad-owns-source")
3379            .expect("shape-violating entity must surface");
3380        let issue = report
3381            .issues
3382            .iter()
3383            .find(|i| i.field == "relationships" && i.message.contains("INVALID_REL_SHAPE"))
3384            .expect("shape violation must produce an INVALID_REL_SHAPE issue");
3385        assert!(
3386            issue.message.contains("OWNS"),
3387            "issue must name the offending rel_type: {}",
3388            issue.message
3389        );
3390        assert!(
3391            issue.message.contains("spec"),
3392            "issue must name the actual source type: {}",
3393            issue.message
3394        );
3395        assert!(
3396            issue.message.contains("actor"),
3397            "issue must name the allowed source type: {}",
3398            issue.message
3399        );
3400        assert!(
3401            issue.message.contains("remove=true"),
3402            "issue must surface the recovery path: {}",
3403            issue.message
3404        );
3405    }
3406
3407    #[test]
3408    fn health_does_not_flag_shape_compliant_edges() {
3409        // Sanity counterpart: an actor source with OWNS edge satisfies
3410        // `source_types: [actor]` — no INVALID_REL_SHAPE issue surfaces.
3411        use crate::entity::Relationship;
3412        use memstead_schema::SchemaRegistry;
3413
3414        let registry = SchemaRegistry::builtin();
3415        let software = registry
3416            .get("software", &semver::Version::new(0, 2, 0))
3417            .expect("software schema ships as a builtin");
3418
3419        let mut store = Store::new();
3420        let mut owner = make_entity("owner", true);
3421        owner.entity_type = "actor".into();
3422        owner
3423            .metadata
3424            .insert("kind".into(), MetadataValue::String("team".into()));
3425        owner
3426            .metadata
3427            .insert("active".into(), MetadataValue::Bool(true));
3428        owner
3429            .metadata
3430            .insert("handle".into(), MetadataValue::String("owner".into()));
3431        owner.relationships.push(Relationship {
3432            rel_type: "OWNS".into(),
3433            target: EntityId::new("specs", "owned"),
3434            description: None,
3435        });
3436        let mut owned = make_entity("owned", true);
3437        owned.entity_type = "spec".into();
3438        store.upsert(owner.id.clone(), owner);
3439        store.upsert(owned.id.clone(), owned);
3440
3441        let mut mem_schemas = HashMap::new();
3442        mem_schemas.insert("specs".to_string(), software);
3443
3444        let schema = &type_by_name("spec").unwrap();
3445        let summary = compute_health(&store, schema, &mem_schemas, None);
3446        let shape_issue = summary
3447            .missing_fields
3448            .iter()
3449            .flat_map(|r| r.issues.iter())
3450            .find(|i| i.message.contains("INVALID_REL_SHAPE"));
3451        assert!(
3452            shape_issue.is_none(),
3453            "shape-compliant edge must not surface a shape issue, got: {shape_issue:?}"
3454        );
3455    }
3456
3457    #[test]
3458    fn health_warns_on_undeclared_relationship_in_existing_entity() {
3459        use crate::entity::Relationship;
3460        use memstead_schema::Schema;
3461
3462        let mut store = Store::new();
3463        let mut entity = make_entity("with-bad-rel", true);
3464        // Author an edge using a name that does not exist in the default
3465        // schema's vocabulary. The load-side contract per decision 3 is
3466        // about unknown *types*; unknown *relationships* on an already-
3467        // loaded entity land in the soft health surface instead so an
3468        // agent running `memstead_health` after a schema edit sees the drift.
3469        entity.relationships.push(Relationship {
3470            rel_type: "CONJURES".into(),
3471            target: EntityId::new("specs", "unknown"),
3472            description: None,
3473        });
3474        store.upsert(entity.id.clone(), entity);
3475
3476        let mut mem_schemas = HashMap::new();
3477        mem_schemas.insert("specs".to_string(), Schema::builtin_default());
3478
3479        let schema = &type_by_name("spec").unwrap();
3480        let summary = compute_health(&store, schema, &mem_schemas, None);
3481        let report = summary
3482            .missing_fields
3483            .iter()
3484            .find(|r| r.id.as_ref() == "specs--with-bad-rel")
3485            .expect("entity must surface in missing_fields");
3486        let rel_issue = report
3487            .issues
3488            .iter()
3489            .find(|i| i.field == "relationships")
3490            .expect("undeclared relationship must produce an issue");
3491        assert!(
3492            rel_issue.message.contains("CONJURES"),
3493            "issue message must name the offending relationship: {}",
3494            rel_issue.message
3495        );
3496        assert!(
3497            rel_issue.message.contains("default@1.0.0"),
3498            "issue must name the schema pin: {}",
3499            rel_issue.message
3500        );
3501    }
3502
3503    // -------------------------------------------------------------------
3504    // Dangling wiki-link detection
3505    // -------------------------------------------------------------------
3506
3507    /// Build an entity with an arbitrary section body so the test can seed
3508    /// inline wiki-links at will. Mem defaults to `specs`.
3509    fn make_entity_with_body(name: &str, section_key: &str, body: &str) -> Entity {
3510        let mut entity = make_entity(name, true);
3511        entity.sections.insert(section_key.into(), body.to_string());
3512        entity
3513    }
3514
3515    #[test]
3516    fn dangling_link_detected_after_delete() {
3517        use crate::entity::store_builder::make_stub;
3518
3519        let mut store = Store::new();
3520        let a = make_entity_with_body("a", "purpose", "Refers to [[b]] in prose.");
3521        store.upsert(a.id.clone(), a.clone());
3522
3523        // Seed b as a stub — the signal that its markdown file is gone
3524        // (post-delete, pre-recreate, or never authored).
3525        let b_id = EntityId::new("specs", "b");
3526        store.upsert(b_id.clone(), make_stub(b_id.clone()));
3527
3528        let dangling = super::collect_dangling_links(&store, None);
3529        assert_eq!(dangling.len(), 1, "exactly one dangling link expected");
3530        let d = &dangling[0];
3531        assert_eq!(d.from, a.id);
3532        assert_eq!(d.target_id, b_id);
3533        assert_eq!(d.target_path, "b");
3534        assert_eq!(d.section.as_deref(), Some("purpose"));
3535        assert_eq!(d.kind, DanglingLinkKind::LinkTargetMissing);
3536    }
3537
3538    /// 04/06: the three conditions the fused `DANGLING_LINK` name used
3539    /// to cover are discriminated at the producer, and each carries its
3540    /// own repair. Two of them (a body link to a written entity with no
3541    /// relationship, and a relationship row whose target is absent from
3542    /// the store) were not separable at all before — the payload
3543    /// distinguished them only by whether `section` happened to be
3544    /// null, which is a rendering accident, not a condition.
3545    #[test]
3546    fn the_three_dangling_conditions_are_discriminated() {
3547        use crate::entity::store_builder::make_stub;
3548
3549        let mut store = Store::new();
3550
3551        // (1) Body link whose target has no markdown file at all.
3552        let gone = make_entity_with_body("gone-link", "purpose", "See [[absent]].");
3553        store.upsert(gone.id.clone(), gone.clone());
3554        let absent = EntityId::new("specs", "absent");
3555        store.upsert(absent.clone(), make_stub(absent.clone()));
3556
3557        // (2) Body link to a fully written entity that the source does
3558        // not relate to. The target exists; the edge does not.
3559        let written = make_entity("written", true);
3560        store.upsert(written.id.clone(), written.clone());
3561        let unrelated = make_entity_with_body("unrelated-link", "purpose", "See [[written]].");
3562        store.upsert(unrelated.id.clone(), unrelated.clone());
3563
3564        // (3) Relationship row naming an entity that is not in the
3565        // store at all — not even as a stub. Auto-stubbing means this
3566        // only arises from out-of-band edits or historical corruption.
3567        let mut rel_source = make_entity("rel-source", true);
3568        rel_source.relationships.push(crate::entity::Relationship {
3569            rel_type: "DEPENDS_ON".to_string(),
3570            target: EntityId::new("specs", "vanished"),
3571            description: None,
3572        });
3573        store.upsert(rel_source.id.clone(), rel_source.clone());
3574
3575        let found = super::collect_dangling_links(&store, None);
3576        let kind_of = |from: &str| {
3577            found
3578                .iter()
3579                .find(|d| d.from.path() == from)
3580                .unwrap_or_else(|| panic!("no dangling link from {from}: {found:?}"))
3581                .kind
3582        };
3583        assert_eq!(kind_of("gone-link"), DanglingLinkKind::LinkTargetMissing);
3584        assert_eq!(kind_of("unrelated-link"), DanglingLinkKind::LinkNotRelated);
3585        assert_eq!(
3586            kind_of("rel-source"),
3587            DanglingLinkKind::RelationTargetMissing
3588        );
3589
3590        // Three conditions, three codes, three repairs: no two of them
3591        // collapse onto the same string.
3592        let codes: std::collections::BTreeSet<_> = found.iter().map(|d| d.kind.code()).collect();
3593        let repairs: std::collections::BTreeSet<_> =
3594            found.iter().map(|d| d.kind.repair()).collect();
3595        assert_eq!(codes.len(), 3, "{found:?}");
3596        assert_eq!(repairs.len(), 3, "{found:?}");
3597    }
3598
3599    /// The relationships row keeps its tolerance.
3600    /// A row whose target is a stub is a legitimate forward reference —
3601    /// the alias machinery auto-stubs absent targets by design — and the
3602    /// split must not start reporting them. The body scan treats the
3603    /// same stub as missing, which is the whole reason the two axes
3604    /// needed separate codes rather than one.
3605    #[test]
3606    fn a_relationship_row_pointing_at_a_stub_is_still_not_flagged() {
3607        use crate::entity::store_builder::make_stub;
3608
3609        let mut store = Store::new();
3610        let stub_id = EntityId::new("specs", "forward");
3611        store.upsert(stub_id.clone(), make_stub(stub_id.clone()));
3612
3613        let mut source = make_entity("forward-ref", true);
3614        source.relationships.push(crate::entity::Relationship {
3615            rel_type: "DEPENDS_ON".to_string(),
3616            target: stub_id.clone(),
3617            description: None,
3618        });
3619        store.upsert(source.id.clone(), source.clone());
3620
3621        assert!(
3622            super::collect_dangling_links(&store, None).is_empty(),
3623            "a forward reference through the relationships table stays unflagged"
3624        );
3625
3626        // The complement of the complement: the SAME stub reached from a
3627        // body wiki-link is the target-missing condition.
3628        let body = make_entity_with_body("body-ref", "purpose", "See [[forward]].");
3629        store.upsert(body.id.clone(), body.clone());
3630        let found = super::collect_dangling_links(&store, None);
3631        assert_eq!(found.len(), 1, "{found:?}");
3632        assert_eq!(found[0].from, body.id);
3633        assert_eq!(found[0].kind, DanglingLinkKind::LinkTargetMissing);
3634    }
3635
3636    /// Decision 18: dangling-links and stubs
3637    /// output is deterministic — the store iterates a HashMap, so the
3638    /// collectors sort before serving. Two independently built
3639    /// identical stores must produce byte-identical lists, in the
3640    /// documented (from, target, section) / id order.
3641    #[test]
3642    fn dangling_links_and_stubs_serve_in_deterministic_order() {
3643        use crate::entity::store_builder::make_stub;
3644
3645        let build = || {
3646            let mut store = Store::new();
3647            // Insert in an order unrelated to the expected output order.
3648            for name in ["zeta", "alpha", "mid"] {
3649                let e = make_entity_with_body(
3650                    name,
3651                    "purpose",
3652                    &format!("See [[gone-{name}]] and [[lost-{name}]]."),
3653                );
3654                store.upsert(e.id.clone(), e);
3655            }
3656            for name in ["zeta", "alpha", "mid"] {
3657                for pre in ["gone", "lost"] {
3658                    let id = EntityId::new("specs", &format!("{pre}-{name}"));
3659                    store.upsert(id.clone(), make_stub(id));
3660                }
3661            }
3662            store
3663        };
3664
3665        let store_a = build();
3666        let store_b = build();
3667
3668        let key =
3669            |d: &super::DanglingLink| (d.from.0.clone(), d.target_id.0.clone(), d.section.clone());
3670        let dangling_a: Vec<_> = super::collect_dangling_links(&store_a, None)
3671            .iter()
3672            .map(key)
3673            .collect();
3674        let dangling_b: Vec<_> = super::collect_dangling_links(&store_b, None)
3675            .iter()
3676            .map(key)
3677            .collect();
3678        assert_eq!(dangling_a, dangling_b, "identical stores, identical order");
3679        let mut sorted = dangling_a.clone();
3680        sorted.sort();
3681        assert_eq!(dangling_a, sorted, "served pre-sorted by (from, target)");
3682        assert_eq!(dangling_a.len(), 6);
3683
3684        let stub_ids = |s: &Store| -> Vec<String> {
3685            crate::graph::query::find_stubs(s)
3686                .into_iter()
3687                .map(|(id, _)| id.0)
3688                .collect()
3689        };
3690        let stubs_a = stub_ids(&store_a);
3691        assert_eq!(stubs_a, stub_ids(&store_b), "stub order is deterministic");
3692        let mut sorted = stubs_a.clone();
3693        sorted.sort();
3694        assert_eq!(stubs_a, sorted, "stubs served pre-sorted by id");
3695        assert_eq!(stubs_a.len(), 6);
3696    }
3697
3698    #[test]
3699    fn dangling_link_does_not_flag_stub_target_of_explicit_relationship() {
3700        use crate::entity::Relationship;
3701        use crate::entity::store_builder::make_stub;
3702
3703        let mut store = Store::new();
3704        // A has NO inline link in its body — only an explicit relationship
3705        // edge pointing at a stub.
3706        let mut a = make_entity("a", true);
3707        let b_id = EntityId::new("specs", "b");
3708        a.relationships.push(Relationship {
3709            rel_type: "REFERENCES".into(),
3710            target: b_id.clone(),
3711            description: None,
3712        });
3713        store.upsert(a.id.clone(), a);
3714        store.upsert(b_id.clone(), make_stub(b_id));
3715
3716        let dangling = super::collect_dangling_links(&store, None);
3717        assert!(
3718            dangling.is_empty(),
3719            "explicit relationships to stubs are valid by design \
3720             (stubs are first-class placeholders); only inline-body \
3721             wiki-links to stubs must surface"
3722        );
3723    }
3724
3725    #[test]
3726    fn dangling_link_does_not_flag_real_reference() {
3727        use crate::entity::Relationship;
3728
3729        let mut store = Store::new();
3730        let mut a = make_entity_with_body("a", "purpose", "Refers to [[b]] in prose.");
3731        // Backing relation makes the body link a valid alias.
3732        a.relationships.push(Relationship {
3733            rel_type: "REFERENCES".into(),
3734            target: EntityId::new("specs", "b"),
3735            description: None,
3736        });
3737        let b = make_entity("b", true);
3738        store.upsert(a.id.clone(), a);
3739        store.upsert(b.id.clone(), b);
3740
3741        let dangling = super::collect_dangling_links(&store, None);
3742        assert!(
3743            dangling.is_empty(),
3744            "real reference backed by relation — not dangling, not alias-orphan"
3745        );
3746    }
3747
3748    /// F12: a `## Relationships` row pointing at a fully-absent target
3749    /// (out-of-band file edit, mem-delete corruption) must surface.
3750    /// The scan covers both axes; relationship-table danglers ship
3751    /// `section: None` to mark the source axis.
3752    #[test]
3753    fn dangling_link_relationship_section_target_absent() {
3754        use crate::entity::Relationship;
3755
3756        let mut store = Store::new();
3757        let mut a = make_entity("a", true);
3758        // Note: NO stub in the store for `gone` — out-of-band edit
3759        // removed the stub but left the relationship row.
3760        a.relationships.push(Relationship {
3761            rel_type: "DEPENDS_ON".into(),
3762            target: EntityId::new("specs", "gone"),
3763            description: None,
3764        });
3765        store.upsert(a.id.clone(), a.clone());
3766
3767        let dangling = super::collect_dangling_links(&store, None);
3768        assert_eq!(
3769            dangling.len(),
3770            1,
3771            "exactly one relationship-section dangler"
3772        );
3773        let d = &dangling[0];
3774        assert_eq!(d.from, a.id);
3775        assert_eq!(d.target_id, EntityId::new("specs", "gone"));
3776        assert!(
3777            d.section.is_none(),
3778            "relationship-section danglers ship `section: None`, got {:?}",
3779            d.section
3780        );
3781    }
3782
3783    /// Relationship rows pointing at stubs are NOT flagged. Auto-stub
3784    /// is the alias machinery's forward-reference mechanism; flagging
3785    /// stubs would conflate the "engine-managed placeholder" case with
3786    /// corruption.
3787    #[test]
3788    fn dangling_link_relationship_section_stub_target_not_flagged() {
3789        use crate::entity::Relationship;
3790        use crate::entity::store_builder::make_stub;
3791
3792        let mut store = Store::new();
3793        let mut a = make_entity("a", true);
3794        let b_id = EntityId::new("specs", "b");
3795        a.relationships.push(Relationship {
3796            rel_type: "DEPENDS_ON".into(),
3797            target: b_id.clone(),
3798            description: None,
3799        });
3800        store.upsert(a.id.clone(), a);
3801        store.upsert(b_id.clone(), make_stub(b_id));
3802
3803        let dangling = super::collect_dangling_links(&store, None);
3804        assert!(
3805            dangling.is_empty(),
3806            "relationship targets that resolve to stubs are forward-references, not corruption"
3807        );
3808    }
3809
3810    /// When both the body and the relationship section point at the
3811    /// same fully-absent target, the dangler dedupes to a single entry
3812    /// on whichever axis fired first (body-scan runs
3813    /// before relationship-scan in the implementation; the body axis
3814    /// wins). Stub-shaped duplicates are not possible because the
3815    /// relationship-section scan skips stubs.
3816    #[test]
3817    fn dangling_link_dedups_across_body_and_relations() {
3818        use crate::entity::Relationship;
3819        use crate::entity::store_builder::make_stub;
3820
3821        let mut store = Store::new();
3822        let mut a = make_entity_with_body("a", "purpose", "Refers to [[b]] in prose.");
3823        let b_id = EntityId::new("specs", "b");
3824        a.relationships.push(Relationship {
3825            rel_type: "REFERENCES".into(),
3826            target: b_id.clone(),
3827            description: None,
3828        });
3829        store.upsert(a.id.clone(), a.clone());
3830        store.upsert(b_id.clone(), make_stub(b_id.clone()));
3831
3832        let dangling = super::collect_dangling_links(&store, None);
3833        assert_eq!(
3834            dangling.len(),
3835            1,
3836            "body + relations both pointing at the same stub should dedup"
3837        );
3838        // Body scan fires first; the surviving entry carries
3839        // `section: Some(_)`.
3840        assert!(dangling[0].section.is_some(), "body axis wins the dedup");
3841    }
3842
3843    #[test]
3844    fn dangling_links_scope_to_mem_filter() {
3845        use crate::entity::store_builder::make_stub;
3846
3847        let mut store = Store::new();
3848
3849        // specs--a with body [[gone]] → dangling in specs.
3850        let a = make_entity_with_body("a", "purpose", "Refers to [[gone]] in prose.");
3851        store.upsert(a.id.clone(), a);
3852        let gone_specs = EntityId::new("specs", "gone");
3853        store.upsert(gone_specs.clone(), make_stub(gone_specs));
3854
3855        // web--x with body [[gone]] → dangling in web (different stub).
3856        let mut x = make_entity("x", true);
3857        x.id = EntityId::new("web", "x");
3858        x.mem = "web".into();
3859        x.file_path = "x.md".into();
3860        x.sections
3861            .insert("purpose".into(), "Refers to [[gone]] in prose.".into());
3862        store.upsert(x.id.clone(), x);
3863        let gone_web = EntityId::new("web", "gone");
3864        store.upsert(gone_web.clone(), make_stub(gone_web));
3865
3866        let all = super::collect_dangling_links(&store, None);
3867        assert_eq!(all.len(), 2);
3868
3869        let specs_only = super::collect_dangling_links(&store, Some("specs"));
3870        assert_eq!(specs_only.len(), 1);
3871        assert_eq!(specs_only[0].from.mem(), "specs");
3872
3873        let web_only = super::collect_dangling_links(&store, Some("web"));
3874        assert_eq!(web_only.len(), 1);
3875        assert_eq!(web_only[0].from.mem(), "web");
3876    }
3877
3878    #[test]
3879    fn parse_iso_date() {
3880        let days = parse_iso_to_days("2026-04-12").unwrap();
3881        assert!(days > 0);
3882
3883        let days_with_time = parse_iso_to_days("2026-04-12T10:00:00Z").unwrap();
3884        assert_eq!(days, days_with_time);
3885    }
3886
3887    #[test]
3888    fn ymd_roundtrip() {
3889        // 2026-01-01
3890        let days = ymd_to_days(2026, 1, 1);
3891        assert!(days > 20000); // sanity check
3892    }
3893
3894    // ---------------------------------------------------------------------
3895    // collect_tag_distribution — #18
3896    // ---------------------------------------------------------------------
3897
3898    fn make_entity_with_tags(name: &str, mem: &str, entity_type: &str, tags: &str) -> Entity {
3899        let mut e = make_entity(name, true);
3900        e.id = EntityId::new(mem, name);
3901        e.mem = mem.into();
3902        e.entity_type = entity_type.into();
3903        e.metadata
3904            .insert("tags".into(), MetadataValue::String(tags.into()));
3905        e
3906    }
3907
3908    fn make_entity_no_tags(name: &str) -> Entity {
3909        make_entity(name, true)
3910    }
3911
3912    #[test]
3913    fn tag_distribution_aggregates_across_entities() {
3914        let mut store = Store::new();
3915        let a = make_entity_with_tags("a", "specs", "spec", "decision, plan");
3916        let b = make_entity_with_tags("b", "specs", "spec", "decision, plan");
3917        let c = make_entity_with_tags("c", "specs", "spec", "plan");
3918        store.upsert(a.id.clone(), a);
3919        store.upsert(b.id.clone(), b);
3920        store.upsert(c.id.clone(), c);
3921
3922        let (dist, _folded, untagged) = collect_tag_distribution(&store, None, 10);
3923        assert_eq!(dist.len(), 2);
3924        assert_eq!(dist[0].tag, "plan");
3925        assert_eq!(dist[0].count, 3);
3926        assert_eq!(dist[0].by_entity_type.get("spec"), Some(&3));
3927        assert_eq!(dist[1].tag, "decision");
3928        assert_eq!(dist[1].count, 2);
3929        assert_eq!(untagged.total, 0);
3930    }
3931
3932    #[test]
3933    fn tag_distribution_case_sensitive() {
3934        let mut store = Store::new();
3935        let a = make_entity_with_tags("a", "specs", "spec", "Decision");
3936        let b = make_entity_with_tags("b", "specs", "spec", "decision");
3937        store.upsert(a.id.clone(), a);
3938        store.upsert(b.id.clone(), b);
3939
3940        let (dist, folded, _untagged) = collect_tag_distribution(&store, None, 10);
3941        assert_eq!(dist.len(), 2, "`decision` and `Decision` stay distinct");
3942        let tags: std::collections::HashSet<&str> = dist.iter().map(|t| t.tag.as_str()).collect();
3943        assert!(tags.contains("decision"));
3944        assert!(tags.contains("Decision"));
3945
3946        // Drift sidecar surfaces the collision.
3947        assert_eq!(folded.len(), 1);
3948        assert_eq!(folded[0].canonical, "decision");
3949        assert_eq!(folded[0].total, 2);
3950        assert_eq!(folded[0].variants.len(), 2);
3951    }
3952
3953    #[test]
3954    fn untagged_entities_counts_missing_and_empty() {
3955        let mut store = Store::new();
3956        let a = make_entity_no_tags("a"); // no `tags` metadata
3957        let b = make_entity_with_tags("b", "specs", "spec", "");
3958        let c = make_entity_with_tags("c", "specs", "spec", " , , ");
3959        store.upsert(a.id.clone(), a);
3960        store.upsert(b.id.clone(), b);
3961        store.upsert(c.id.clone(), c);
3962
3963        let (dist, _folded, untagged) = collect_tag_distribution(&store, None, 10);
3964        assert!(dist.is_empty(), "no effective tags → empty distribution");
3965        assert_eq!(untagged.total, 3);
3966        assert_eq!(untagged.by_entity_type.get("spec"), Some(&3));
3967    }
3968
3969    #[test]
3970    fn tag_distribution_respects_mem_filter() {
3971        let mut store = Store::new();
3972        let a = make_entity_with_tags("a", "specs", "spec", "decision");
3973        let b = make_entity_with_tags("b", "memos", "memo", "observation");
3974        let c = make_entity_no_tags("c");
3975        store.upsert(a.id.clone(), a);
3976        store.upsert(b.id.clone(), b);
3977        store.upsert(c.id.clone(), c);
3978
3979        let (dist, _folded, untagged) = collect_tag_distribution(&store, Some("memos"), 10);
3980        assert_eq!(dist.len(), 1);
3981        assert_eq!(dist[0].tag, "observation");
3982        assert_eq!(untagged.total, 0, "untagged scoped to filter mem");
3983    }
3984
3985    #[test]
3986    fn tag_distribution_respects_limit() {
3987        let mut store = Store::new();
3988        for (name, tag) in [
3989            ("a", "t-alpha"),
3990            ("b", "t-beta"),
3991            ("c", "t-gamma"),
3992            ("d", "t-delta"),
3993            ("e", "t-epsilon"),
3994        ] {
3995            let e = make_entity_with_tags(name, "specs", "spec", tag);
3996            store.upsert(e.id.clone(), e);
3997        }
3998
3999        let (dist, _folded, _untagged) = collect_tag_distribution(&store, None, 3);
4000        assert_eq!(dist.len(), 3);
4001        // Every tag appears once → ties across all 5; deterministic tie-break is
4002        // lex ascending: alpha, beta, delta (first 3 sorted).
4003        assert_eq!(dist[0].tag, "t-alpha");
4004        assert_eq!(dist[1].tag, "t-beta");
4005        assert_eq!(dist[2].tag, "t-delta");
4006    }
4007
4008    // ----------------------------------------------------------------------
4009    // required_outgoing health collector
4010    // ----------------------------------------------------------------------
4011
4012    /// Build a minimal schema fixture pinning `decision` with two
4013    /// `required_outgoing` blocks (CHOSEN + REJECTED), `note` with none.
4014    fn required_outgoing_fixture_schema() -> std::sync::Arc<memstead_schema::Schema> {
4015        let manifest = r#"name: tests-ro-health
4016version: 0.1.0
4017description: required_outgoing health test schema
4018when_to_use: tests
4019types:
4020  - decision
4021  - note
4022relationships:
4023  mode: strict
4024  definitions:
4025    - name: PART_OF
4026      description: Hier
4027      default_weight: 3.0
4028      acyclic: true
4029    - name: CHOSEN
4030      description: ch
4031      default_weight: 3.0
4032    - name: REJECTED
4033      description: rj
4034      default_weight: 2.0
4035    - name: REFERENCES
4036      description: ref
4037      default_weight: 0.5
4038    - name: _default
4039      description: Fallback
4040      default_weight: 1.0
4041community:
4042  resolution: 1.0
4043  seed: 42
4044"#;
4045        let body_section = "sections:\n  - key: body\n    heading: Body\n    required: true\n    search_weight: 10.0\n    catch_all: true\n    write_rules: []\nmetadata_fields: []\ntitle_weight: 100.0\ntext_fields:\n  - body\nhierarchy_relationship: PART_OF\nno_self_loop_relationships: []\nupdatable_fields:\n  - title\n  - body\nhealth_required_fields:\n  - body\nstaleness_threshold_days: 90\nwrite_rules: []\n";
4046        let decision_yaml = format!(
4047            "name: decision\ndescription: t\nwhen_to_use: Here\n{body_section}required_outgoing:\n  - relationships: [CHOSEN]\n    cardinality: at_least_one\n  - relationships: [REJECTED]\n    cardinality: at_least_one\n",
4048        );
4049        let note_yaml = format!("name: note\ndescription: t\nwhen_to_use: Here\n{body_section}",);
4050        std::sync::Arc::new(
4051            memstead_schema::load_schema_from_memory(
4052                manifest,
4053                &[
4054                    ("decision".to_string(), decision_yaml),
4055                    ("note".to_string(), note_yaml),
4056                ],
4057            )
4058            .expect("ro fixture schema must parse"),
4059        )
4060    }
4061
4062    fn make_typed_entity(mem: &str, slug: &str, entity_type: &str) -> crate::entity::Entity {
4063        use crate::entity::MetadataValue;
4064        let mut metadata = IndexMap::new();
4065        metadata.insert("type".into(), MetadataValue::String(entity_type.into()));
4066        let mut sections = IndexMap::new();
4067        sections.insert("body".into(), "Body.".into());
4068        crate::entity::Entity {
4069            id: EntityId::new(mem, slug),
4070            title: slug.to_string(),
4071            entity_type: entity_type.into(),
4072            mem: mem.into(),
4073            file_path: format!("{slug}.md"),
4074            metadata,
4075            sections,
4076            relationships: Vec::new(),
4077            content_hash: String::new(),
4078            stub: false,
4079            stub_kind: None,
4080            heading_spans: std::collections::HashMap::new(),
4081            raw_section_headings: Vec::new(),
4082        }
4083    }
4084
4085    #[test]
4086    fn missing_required_outgoing_collects_violators_only() {
4087        let schema = required_outgoing_fixture_schema();
4088        let mut store = Store::new();
4089        // Two decisions: one without any edges (violates 2 blocks), one
4090        // with both edges satisfied. One note (no requirement).
4091        let mut violator = make_typed_entity("plan", "stalled", "decision");
4092        let mut satisfied = make_typed_entity("plan", "wired", "decision");
4093        let opt_a = make_typed_entity("plan", "a", "note");
4094        let opt_b = make_typed_entity("plan", "b", "note");
4095        let happy_note = make_typed_entity("plan", "side", "note");
4096        satisfied.relationships.push(crate::entity::Relationship {
4097            rel_type: "CHOSEN".into(),
4098            target: opt_a.id.clone(),
4099            description: None,
4100        });
4101        satisfied.relationships.push(crate::entity::Relationship {
4102            rel_type: "REJECTED".into(),
4103            target: opt_b.id.clone(),
4104            description: None,
4105        });
4106        for e in [violator.clone(), satisfied, opt_a, opt_b, happy_note] {
4107            store.upsert(e.id.clone(), e);
4108        }
4109
4110        let mut mem_schemas = HashMap::new();
4111        mem_schemas.insert("plan".to_string(), schema);
4112
4113        let reports = collect_missing_required_outgoing(&store, None, &mem_schemas);
4114        assert_eq!(
4115            reports.len(),
4116            1,
4117            "exactly one violator (the empty decision); got {reports:?}"
4118        );
4119        let r = &reports[0];
4120        assert_eq!(r.id, violator.id);
4121        assert_eq!(r.entity_type, "decision");
4122        assert_eq!(r.mem, "plan");
4123        assert_eq!(r.missing.len(), 2);
4124        let names: Vec<&str> = r
4125            .missing
4126            .iter()
4127            .flat_map(|b| b.relationships.iter().map(String::as_str))
4128            .collect();
4129        assert!(names.contains(&"CHOSEN"));
4130        assert!(names.contains(&"REJECTED"));
4131
4132        // mark warning still doesn't propagate when violator is removed.
4133        violator.relationships.push(crate::entity::Relationship {
4134            rel_type: "CHOSEN".into(),
4135            target: EntityId::new("plan", "x"),
4136            description: None,
4137        });
4138    }
4139
4140    #[test]
4141    fn missing_required_outgoing_respects_mem_filter() {
4142        // Plan: "a write to mem A doesn't surface mem B's violations
4143        // in memstead_health mem=A; mem-scoped aggregation is correct."
4144        let schema = required_outgoing_fixture_schema();
4145        let mut store = Store::new();
4146        let v_a = make_typed_entity("alpha", "stalled", "decision");
4147        let v_b = make_typed_entity("beta", "stalled", "decision");
4148        store.upsert(v_a.id.clone(), v_a);
4149        store.upsert(v_b.id.clone(), v_b.clone());
4150
4151        let mut mem_schemas = HashMap::new();
4152        mem_schemas.insert("alpha".to_string(), schema.clone());
4153        mem_schemas.insert("beta".to_string(), schema);
4154
4155        let alpha_only = collect_missing_required_outgoing(&store, Some("alpha"), &mem_schemas);
4156        assert_eq!(alpha_only.len(), 1);
4157        assert_eq!(alpha_only[0].mem, "alpha");
4158
4159        let both = collect_missing_required_outgoing(&store, None, &mem_schemas);
4160        assert_eq!(both.len(), 2);
4161    }
4162
4163    #[test]
4164    fn missing_required_outgoing_skips_stubs_and_unschemaed_mems() {
4165        // Stubs have no entity_type; unschemaed mems can't be evaluated
4166        // — both must be silently skipped.
4167        let schema = required_outgoing_fixture_schema();
4168        let mut store = Store::new();
4169        let mut stub = make_typed_entity("plan", "ghost", "");
4170        stub.stub = true;
4171        stub.entity_type = String::new();
4172        let other = make_typed_entity("uncharted", "lonely", "decision");
4173        store.upsert(stub.id.clone(), stub);
4174        store.upsert(other.id.clone(), other);
4175
4176        let mut mem_schemas = HashMap::new();
4177        mem_schemas.insert("plan".to_string(), schema);
4178
4179        let reports = collect_missing_required_outgoing(&store, None, &mem_schemas);
4180        assert!(
4181            reports.is_empty(),
4182            "stub (no schema lookup) and unschemaed mem must be skipped; got {reports:?}",
4183        );
4184    }
4185
4186    /// A conditional block arms only on the trigger value: the sweep
4187    /// reports the armed violator (with the trigger named in the
4188    /// block entry), and skips both the other-value and the
4189    /// edge-satisfied entities.
4190    #[test]
4191    fn missing_required_outgoing_conditional_blocks_arm_on_trigger() {
4192        use crate::entity::MetadataValue;
4193        let manifest = r#"name: tests-ro-cond
4194version: 0.1.0
4195description: conditional required_outgoing health test schema
4196when_to_use: tests
4197types:
4198  - task
4199relationships:
4200  mode: strict
4201  definitions:
4202    - name: PART_OF
4203      description: Hier
4204      default_weight: 3.0
4205    - name: _default
4206      description: Fallback
4207      default_weight: 1.0
4208community:
4209  resolution: 1.0
4210  seed: 42
4211"#;
4212        let task_yaml = "name: task\ndescription: t\nwhen_to_use: Here\nsections:\n  - key: body\n    heading: Body\n    required: true\n    search_weight: 10.0\n    catch_all: true\n    write_rules: []\nmetadata_fields:\n  - key: status\n    description: workflow state\n    field_type: string\n    enum_values: [open, checked]\ntitle_weight: 100.0\ntext_fields:\n  - body\nhierarchy_relationship: PART_OF\nno_self_loop_relationships: []\nupdatable_fields:\n  - title\n  - body\n  - status\nhealth_required_fields:\n  - body\nstaleness_threshold_days: 90\nwrite_rules: []\nrequired_outgoing:\n  - relationships: [PART_OF]\n    cardinality: at_least_one\n    when_field: status\n    when_value: checked\n";
4213        let schema = std::sync::Arc::new(
4214            memstead_schema::load_schema_from_memory(
4215                manifest,
4216                &[("task".to_string(), task_yaml.to_string())],
4217            )
4218            .expect("conditional ro fixture schema must parse"),
4219        );
4220
4221        let mut store = Store::new();
4222        let mut armed = make_typed_entity("plan", "armed", "task");
4223        armed
4224            .metadata
4225            .insert("status".into(), MetadataValue::String("checked".into()));
4226        let mut other_value = make_typed_entity("plan", "quiet", "task");
4227        other_value
4228            .metadata
4229            .insert("status".into(), MetadataValue::String("open".into()));
4230        let unset = make_typed_entity("plan", "blank", "task");
4231        let parent = make_typed_entity("plan", "parent", "task");
4232        let mut satisfied = make_typed_entity("plan", "wired", "task");
4233        satisfied
4234            .metadata
4235            .insert("status".into(), MetadataValue::String("checked".into()));
4236        satisfied.relationships.push(crate::entity::Relationship {
4237            rel_type: "PART_OF".into(),
4238            target: parent.id.clone(),
4239            description: None,
4240        });
4241        for e in [armed.clone(), other_value, unset, parent, satisfied] {
4242            store.upsert(e.id.clone(), e);
4243        }
4244
4245        let mut mem_schemas = HashMap::new();
4246        mem_schemas.insert("plan".to_string(), schema);
4247
4248        let reports = collect_missing_required_outgoing(&store, None, &mem_schemas);
4249        assert_eq!(
4250            reports.len(),
4251            1,
4252            "only the armed edge-less entity is reported; got {reports:?}"
4253        );
4254        let r = &reports[0];
4255        assert_eq!(r.id, armed.id);
4256        assert_eq!(r.missing.len(), 1);
4257        assert_eq!(r.missing[0].when_field.as_deref(), Some("status"));
4258        assert_eq!(r.missing[0].when_value.as_deref(), Some("checked"));
4259    }
4260
4261    // ----------------------------------------------------------------------
4262    // must_reach reachability obligations
4263    // ----------------------------------------------------------------------
4264
4265    /// Three-type argument-shaped fixture: claim / inference /
4266    /// evidence over GROUNDS / CONCLUDES. The per-type `must_reach`
4267    /// blocks are injected by the caller (empty string = none).
4268    fn must_reach_schema(
4269        claim_extra: &str,
4270        inference_extra: &str,
4271    ) -> std::sync::Arc<memstead_schema::Schema> {
4272        let manifest = r#"name: tests-must-reach
4273version: 0.1.0
4274description: must_reach health test schema
4275when_to_use: tests
4276types:
4277  - claim
4278  - inference
4279  - evidence
4280relationships:
4281  mode: strict
4282  definitions:
4283    - name: GROUNDS
4284      description: g
4285      default_weight: 3.0
4286    - name: CONCLUDES
4287      description: c
4288      default_weight: 3.0
4289    - name: PART_OF
4290      description: hier
4291      default_weight: 1.0
4292    - name: _default
4293      description: fallback
4294      default_weight: 1.0
4295community:
4296  resolution: 1.0
4297  seed: 42
4298"#;
4299        let body = "sections:\n  - key: body\n    heading: Body\n    required: true\n    search_weight: 10.0\n    catch_all: true\n    write_rules: []\nmetadata_fields: []\ntitle_weight: 100.0\ntext_fields:\n  - body\nhierarchy_relationship: PART_OF\nno_self_loop_relationships: []\nupdatable_fields:\n  - title\n  - body\nhealth_required_fields:\n  - body\nstaleness_threshold_days: 90\nwrite_rules: []\n";
4300        let claim = format!("name: claim\ndescription: t\nwhen_to_use: Here\n{body}{claim_extra}");
4301        let inference =
4302            format!("name: inference\ndescription: t\nwhen_to_use: Here\n{body}{inference_extra}");
4303        let evidence = format!("name: evidence\ndescription: t\nwhen_to_use: Here\n{body}");
4304        std::sync::Arc::new(
4305            memstead_schema::load_schema_from_memory(
4306                manifest,
4307                &[
4308                    ("claim".to_string(), claim),
4309                    ("inference".to_string(), inference),
4310                    ("evidence".to_string(), evidence),
4311                ],
4312            )
4313            .expect("must_reach fixture schema must parse"),
4314        )
4315    }
4316
4317    fn link(from: &mut crate::entity::Entity, rel: &str, to: &crate::entity::EntityId) {
4318        from.relationships.push(crate::entity::Relationship {
4319            rel_type: rel.into(),
4320            target: to.clone(),
4321            description: None,
4322        });
4323    }
4324
4325    fn must_reach_violations(r: &ConstraintFindingReport) -> Vec<&UnsatisfiedConstraint> {
4326        r.violations
4327            .iter()
4328            .filter(|v| matches!(v, UnsatisfiedConstraint::MustReach { .. }))
4329            .collect()
4330    }
4331
4332    const CLAIM_GROUNDS_EVIDENCE: &str = "must_reach:\n  - relationships: [GROUNDS]\n    direction: out\n    terminal_types: [evidence]\n";
4333
4334    /// A conforming path (direct or transitive through a non-terminal)
4335    /// is silent; an entity without one carries a finding echoing the
4336    /// whole declaration.
4337    #[test]
4338    fn must_reach_conforming_path_silent_gap_reported() {
4339        let schema = must_reach_schema(CLAIM_GROUNDS_EVIDENCE, "");
4340        let mut store = Store::new();
4341        let ev = make_typed_entity("arg", "ev", "evidence");
4342        let mut direct = make_typed_entity("arg", "direct", "claim");
4343        link(&mut direct, "GROUNDS", &ev.id);
4344        let mut mid = make_typed_entity("arg", "mid", "claim");
4345        let mut chained = make_typed_entity("arg", "chained", "claim");
4346        link(&mut chained, "GROUNDS", &mid.id);
4347        link(&mut mid, "GROUNDS", &ev.id);
4348        let floating = make_typed_entity("arg", "floating", "claim");
4349        for e in [ev, direct, mid, chained, floating.clone()] {
4350            store.upsert(e.id.clone(), e);
4351        }
4352        let mut mem_schemas = HashMap::new();
4353        mem_schemas.insert("arg".to_string(), schema);
4354
4355        let reports = collect_constraint_findings(&store, None, &mem_schemas, None);
4356        assert_eq!(reports.len(), 1, "only the pathless claim: {reports:?}");
4357        assert_eq!(reports[0].id, floating.id);
4358        let v = must_reach_violations(&reports[0]);
4359        assert_eq!(v.len(), 1);
4360        let UnsatisfiedConstraint::MustReach {
4361            relationships,
4362            direction,
4363            terminal_types,
4364            max_depth,
4365            ..
4366        } = v[0]
4367        else {
4368            panic!("expected must_reach finding");
4369        };
4370        assert_eq!(relationships, &vec!["GROUNDS".to_string()]);
4371        assert_eq!(*direction, memstead_schema::ReachDirection::Out);
4372        assert_eq!(terminal_types, &vec!["evidence".to_string()]);
4373        assert_eq!(*max_depth, None);
4374    }
4375
4376    /// The floating leap: an inference no premise reaches (zero
4377    /// incoming edges of the set) is a finding; one incoming premise
4378    /// edge silences it. Incoming direction with depth 1 is the
4379    /// required-incoming-edge case.
4380    #[test]
4381    fn must_reach_one_hop_incoming_floating_leap() {
4382        let schema = must_reach_schema(
4383            "",
4384            "must_reach:\n  - relationships: [GROUNDS]\n    direction: in\n    terminal_types: [claim]\n    max_depth: 1\n",
4385        );
4386        let mut store = Store::new();
4387        let leap = make_typed_entity("arg", "leap", "inference");
4388        let grounded = make_typed_entity("arg", "grounded", "inference");
4389        let mut premise = make_typed_entity("arg", "premise", "claim");
4390        link(&mut premise, "GROUNDS", &grounded.id);
4391        for e in [leap.clone(), grounded, premise] {
4392            store.upsert(e.id.clone(), e);
4393        }
4394        let mut mem_schemas = HashMap::new();
4395        mem_schemas.insert("arg".to_string(), schema);
4396
4397        let reports = collect_constraint_findings(&store, None, &mem_schemas, None);
4398        assert_eq!(reports.len(), 1, "only the floating leap: {reports:?}");
4399        assert_eq!(reports[0].id, leap.id);
4400    }
4401
4402    /// A chain ending in a stub or in non-terminal types is a finding;
4403    /// adding one conforming path clears it on the next sweep.
4404    #[test]
4405    fn must_reach_stub_and_non_terminal_chains_then_cleared() {
4406        let schema = must_reach_schema(CLAIM_GROUNDS_EVIDENCE, "");
4407        let mut store = Store::new();
4408        let mut stub_ev = make_typed_entity("arg", "ghost", "evidence");
4409        stub_ev.stub = true;
4410        let mut to_stub = make_typed_entity("arg", "to-stub", "claim");
4411        link(&mut to_stub, "GROUNDS", &stub_ev.id);
4412        let dead_end = make_typed_entity("arg", "dead-end", "claim");
4413        let mut to_claim = make_typed_entity("arg", "to-claim", "claim");
4414        link(&mut to_claim, "GROUNDS", &dead_end.id);
4415        for e in [stub_ev, to_stub.clone(), dead_end, to_claim.clone()] {
4416            store.upsert(e.id.clone(), e);
4417        }
4418        let mut mem_schemas = HashMap::new();
4419        mem_schemas.insert("arg".to_string(), schema.clone());
4420
4421        let reports = collect_constraint_findings(&store, None, &mem_schemas, None);
4422        let ids: Vec<&str> = reports.iter().map(|r| r.id.0.as_str()).collect();
4423        assert!(
4424            ids.contains(&to_stub.id.0.as_str()),
4425            "stub terminates no obligation: {ids:?}"
4426        );
4427        assert!(
4428            ids.contains(&to_claim.id.0.as_str()),
4429            "non-terminal chain is a finding: {ids:?}"
4430        );
4431
4432        // One conforming edge clears the finding on the next call.
4433        let ev = make_typed_entity("arg", "real-ev", "evidence");
4434        let mut repaired = store.get(&to_stub.id).unwrap().clone();
4435        link(&mut repaired, "GROUNDS", &ev.id);
4436        store.upsert(ev.id.clone(), ev);
4437        store.upsert(repaired.id.clone(), repaired);
4438        let reports = collect_constraint_findings(&store, None, &mem_schemas, None);
4439        let ids: Vec<&str> = reports.iter().map(|r| r.id.0.as_str()).collect();
4440        assert!(
4441            !ids.contains(&to_stub.id.0.as_str()),
4442            "conforming path clears the finding: {ids:?}"
4443        );
4444    }
4445
4446    /// A cycle along the walked set terminates (visited-set
4447    /// discipline): the sweep returns findings for both cycle members
4448    /// instead of hanging.
4449    #[test]
4450    fn must_reach_cycles_terminate() {
4451        let schema = must_reach_schema(CLAIM_GROUNDS_EVIDENCE, "");
4452        let mut store = Store::new();
4453        let mut a = make_typed_entity("arg", "cyc-a", "claim");
4454        let mut b = make_typed_entity("arg", "cyc-b", "claim");
4455        link(&mut a, "GROUNDS", &b.id);
4456        link(&mut b, "GROUNDS", &a.id);
4457        for e in [a, b] {
4458            store.upsert(e.id.clone(), e);
4459        }
4460        let mut mem_schemas = HashMap::new();
4461        mem_schemas.insert("arg".to_string(), schema);
4462
4463        let reports = collect_constraint_findings(&store, None, &mem_schemas, None);
4464        assert_eq!(reports.len(), 2, "both cycle members lack evidence");
4465    }
4466
4467    /// Depth bound: a conforming path within the bound is silent; a
4468    /// graph whose only conforming path exceeds the bound is a
4469    /// finding.
4470    #[test]
4471    fn must_reach_depth_bound() {
4472        let two_hop_store = || {
4473            let mut store = Store::new();
4474            let ev = make_typed_entity("arg", "ev", "evidence");
4475            let mut mid = make_typed_entity("arg", "mid", "claim");
4476            let mut start = make_typed_entity("arg", "start", "claim");
4477            link(&mut start, "GROUNDS", &mid.id);
4478            link(&mut mid, "GROUNDS", &ev.id);
4479            for e in [ev, mid, start] {
4480                store.upsert(e.id.clone(), e);
4481            }
4482            store
4483        };
4484        let bounded = |depth: u32| {
4485            must_reach_schema(
4486                &format!(
4487                    "must_reach:\n  - relationships: [GROUNDS]\n    direction: out\n    terminal_types: [evidence]\n    max_depth: {depth}\n"
4488                ),
4489                "",
4490            )
4491        };
4492
4493        let store = two_hop_store();
4494        let mut mem_schemas = HashMap::new();
4495        mem_schemas.insert("arg".to_string(), bounded(1));
4496        let reports = collect_constraint_findings(&store, None, &mem_schemas, None);
4497        assert_eq!(
4498            reports.len(),
4499            1,
4500            "the two-hop path exceeds depth 1 for the start claim: {reports:?}"
4501        );
4502        assert_eq!(reports[0].id.0, "arg--start");
4503
4504        let mut mem_schemas = HashMap::new();
4505        mem_schemas.insert("arg".to_string(), bounded(2));
4506        let reports = collect_constraint_findings(&store, None, &mem_schemas, None);
4507        assert!(
4508            reports.is_empty(),
4509            "the same path satisfies depth 2: {reports:?}"
4510        );
4511    }
4512
4513    /// Two obligations on one type: exactly one finding, naming the
4514    /// unsatisfied block.
4515    #[test]
4516    fn must_reach_two_obligations_one_finding() {
4517        let schema = must_reach_schema(
4518            "must_reach:\n  - relationships: [GROUNDS]\n    direction: out\n    terminal_types: [evidence]\n  - relationships: [CONCLUDES]\n    direction: out\n    terminal_types: [inference]\n",
4519            "",
4520        );
4521        let mut store = Store::new();
4522        let ev = make_typed_entity("arg", "ev", "evidence");
4523        let mut c = make_typed_entity("arg", "half", "claim");
4524        link(&mut c, "GROUNDS", &ev.id);
4525        for e in [ev, c.clone()] {
4526            store.upsert(e.id.clone(), e);
4527        }
4528        let mut mem_schemas = HashMap::new();
4529        mem_schemas.insert("arg".to_string(), schema);
4530
4531        let reports = collect_constraint_findings(&store, None, &mem_schemas, None);
4532        assert_eq!(reports.len(), 1);
4533        assert_eq!(reports[0].id, c.id);
4534        let v = must_reach_violations(&reports[0]);
4535        assert_eq!(v.len(), 1, "only the unsatisfied obligation: {v:?}");
4536        let UnsatisfiedConstraint::MustReach { relationships, .. } = v[0] else {
4537            panic!("expected must_reach finding");
4538        };
4539        assert_eq!(relationships, &vec!["CONCLUDES".to_string()]);
4540    }
4541
4542    /// `status_propagation` with `rel_types`: the taint crosses
4543    /// rel-type boundaries along the union subgraph (the experiment's
4544    /// withdrawn-evidence chain in the two-rel-type modelling), and
4545    /// the finding echoes the set (`rel_types` present, `rel_type`
4546    /// absent).
4547    #[test]
4548    fn status_propagation_rel_types_taints_across_type_boundaries() {
4549        use crate::entity::MetadataValue;
4550        let manifest = r#"name: tests-prop-set
4551version: 0.1.0
4552description: propagation relation-set test schema
4553when_to_use: tests
4554types:
4555  - claim
4556relationships:
4557  mode: strict
4558  definitions:
4559    - name: GROUNDS
4560      description: g
4561      default_weight: 3.0
4562    - name: CONCLUDES
4563      description: c
4564      default_weight: 3.0
4565    - name: PART_OF
4566      description: hier
4567      default_weight: 1.0
4568    - name: _default
4569      description: fallback
4570      default_weight: 1.0
4571community:
4572  resolution: 1.0
4573  seed: 42
4574"#;
4575        let claim_yaml = "name: claim\ndescription: t\nwhen_to_use: Here\nsections:\n  - key: body\n    heading: Body\n    required: true\n    search_weight: 10.0\n    catch_all: true\n    write_rules: []\nmetadata_fields:\n  - key: standing\n    description: dialectical standing\n    field_type: string\n    enum_values: [active, withdrawn]\ntitle_weight: 100.0\ntext_fields:\n  - body\nhierarchy_relationship: PART_OF\nno_self_loop_relationships: []\nupdatable_fields:\n  - title\n  - body\n  - standing\nhealth_required_fields:\n  - body\nstaleness_threshold_days: 90\nwrite_rules: []\nconstraints:\n  - kind: status_propagation\n    field: standing\n    value: withdrawn\n    rel_types: [GROUNDS, CONCLUDES]\n    direction: incoming\n";
4576        let schema = std::sync::Arc::new(
4577            memstead_schema::load_schema_from_memory(
4578                manifest,
4579                &[("claim".to_string(), claim_yaml.to_string())],
4580            )
4581            .expect("propagation-set fixture schema must parse"),
4582        );
4583
4584        let mut store = Store::new();
4585        let mut withdrawn = make_typed_entity("arg", "withdrawn-ev", "claim");
4586        withdrawn
4587            .metadata
4588            .insert("standing".into(), MetadataValue::String("withdrawn".into()));
4589        let mut inference = make_typed_entity("arg", "inference", "claim");
4590        link(&mut inference, "GROUNDS", &withdrawn.id);
4591        let mut conclusion = make_typed_entity("arg", "conclusion", "claim");
4592        link(&mut conclusion, "CONCLUDES", &inference.id);
4593        let bystander = make_typed_entity("arg", "bystander", "claim");
4594        for e in [withdrawn, inference.clone(), conclusion.clone(), bystander] {
4595            store.upsert(e.id.clone(), e);
4596        }
4597        let mut mem_schemas = HashMap::new();
4598        mem_schemas.insert("arg".to_string(), schema);
4599
4600        let reports = collect_constraint_findings(&store, None, &mem_schemas, None);
4601        let ids: Vec<&str> = reports.iter().map(|r| r.id.0.as_str()).collect();
4602        assert_eq!(
4603            ids,
4604            vec![conclusion.id.0.as_str(), inference.id.0.as_str()],
4605            "the taint crosses the CONCLUDES/GROUNDS boundary, nothing else"
4606        );
4607        let UnsatisfiedConstraint::StatusPropagation {
4608            rel_type,
4609            rel_types,
4610            tainted_by,
4611            ..
4612        } = &reports[0].violations[0]
4613        else {
4614            panic!("expected status_propagation finding");
4615        };
4616        assert_eq!(*rel_type, None, "set declarations echo no single name");
4617        assert_eq!(
4618            rel_types.as_deref(),
4619            Some(&["GROUNDS".to_string(), "CONCLUDES".to_string()][..])
4620        );
4621        assert_eq!(tainted_by, "arg--withdrawn-ev");
4622    }
4623
4624    /// Cross-mem edges satisfy an obligation like any edge; a mem
4625    /// filter reports findings only for entities of the filtered mem.
4626    #[test]
4627    fn must_reach_cross_mem_path_and_mem_filter() {
4628        let schema = must_reach_schema(CLAIM_GROUNDS_EVIDENCE, "");
4629        let mut store = Store::new();
4630        let far_ev = make_typed_entity("ground", "far-ev", "evidence");
4631        let mut crossing = make_typed_entity("arg", "crossing", "claim");
4632        link(&mut crossing, "GROUNDS", &far_ev.id);
4633        let floating_arg = make_typed_entity("arg", "floating", "claim");
4634        let floating_ground = make_typed_entity("ground", "floating", "claim");
4635        for e in [far_ev, crossing, floating_arg.clone(), floating_ground] {
4636            store.upsert(e.id.clone(), e);
4637        }
4638        let mut mem_schemas = HashMap::new();
4639        mem_schemas.insert("arg".to_string(), schema.clone());
4640        mem_schemas.insert("ground".to_string(), schema);
4641
4642        let all = collect_constraint_findings(&store, None, &mem_schemas, None);
4643        assert_eq!(
4644            all.len(),
4645            2,
4646            "the crossing claim is satisfied via the cross-mem edge: {all:?}"
4647        );
4648        let filtered = collect_constraint_findings(&store, Some("arg"), &mem_schemas, None);
4649        assert_eq!(filtered.len(), 1, "mem filter narrows: {filtered:?}");
4650        assert_eq!(filtered[0].id, floating_arg.id);
4651    }
4652
4653    // ----------------------------------------------------------------------
4654    // transition_requires_checks (form 6)
4655    // ----------------------------------------------------------------------
4656
4657    /// Two-type gated-transition fixture: criterion --VERIFIES--> plan,
4658    /// plan gates `status: complete` on incoming VERIFIES checks.
4659    fn gated_transition_schema() -> std::sync::Arc<memstead_schema::Schema> {
4660        let manifest = r#"name: tests-gated
4661version: 0.1.0
4662description: transition_requires_checks test schema
4663when_to_use: tests
4664types:
4665  - plan
4666  - criterion
4667relationships:
4668  mode: strict
4669  definitions:
4670    - name: VERIFIES
4671      description: v
4672      default_weight: 3.0
4673      acyclic: true
4674    - name: PART_OF
4675      description: hier
4676      default_weight: 1.0
4677      acyclic: true
4678    - name: _default
4679      description: fallback
4680      default_weight: 1.0
4681community:
4682  resolution: 1.0
4683  seed: 42
4684"#;
4685        let plan_yaml = "name: plan\ndescription: p\nwhen_to_use: t\nsections:\n  - key: body\n    heading: Body\n    required: true\n    search_weight: 10.0\n    catch_all: true\n    write_rules: []\nmetadata_fields:\n  - key: status\n    description: s\n    field_type: string\n    default_value: draft\n    enum_values: [draft, complete]\ntitle_weight: 100.0\ntext_fields:\n  - body\nhierarchy_relationship: PART_OF\nupdatable_fields:\n  - title\nhealth_required_fields: []\nstaleness_threshold_days: 90\nwrite_rules: []\nconstraints:\n  - kind: transition_requires_checks\n    field: status\n    to_value: complete\n    relationships: [VERIFIES]\n    direction: incoming\n    severity: block\n";
4686        let criterion_yaml = "name: criterion\ndescription: c\nwhen_to_use: t\nsections:\n  - key: body\n    heading: Body\n    required: true\n    search_weight: 10.0\n    catch_all: true\n    write_rules: []\nmetadata_fields: []\ntitle_weight: 100.0\ntext_fields:\n  - body\nhierarchy_relationship: PART_OF\nupdatable_fields:\n  - title\nhealth_required_fields: []\nstaleness_threshold_days: 90\nwrite_rules: []\n";
4687        std::sync::Arc::new(
4688            memstead_schema::load_schema_from_memory(
4689                manifest,
4690                &[
4691                    ("plan".to_string(), plan_yaml.to_string()),
4692                    ("criterion".to_string(), criterion_yaml.to_string()),
4693                ],
4694            )
4695            .expect("gated-transition fixture schema loads"),
4696        )
4697    }
4698
4699    /// The gate triggers only at the declared value, quantifies over
4700    /// the declared incoming edges, requires derived `checked_ok`
4701    /// (stale and failed do not confirm), and treats a missing
4702    /// provider as never_checked — the no-ledger honesty posture. An
4703    /// empty related set satisfies (universal quantification).
4704    #[test]
4705    fn transition_requires_checks_gates_on_derived_state() {
4706        use crate::check::CheckState;
4707        use crate::entity::MetadataValue;
4708        let schema = gated_transition_schema();
4709        let td = schema.types.get("plan").unwrap().clone();
4710        let mut store = Store::default();
4711
4712        let mut plan = make_typed_entity("g", "the-plan", "plan");
4713        plan.metadata
4714            .insert("status".into(), MetadataValue::String("complete".into()));
4715        let mut ok_crit = make_typed_entity("g", "ok-crit", "criterion");
4716        ok_crit.relationships.push(crate::entity::Relationship {
4717            rel_type: "VERIFIES".into(),
4718            target: plan.id.clone(),
4719            description: None,
4720        });
4721        let mut stale_crit = make_typed_entity("g", "stale-crit", "criterion");
4722        stale_crit.relationships.push(crate::entity::Relationship {
4723            rel_type: "VERIFIES".into(),
4724            target: plan.id.clone(),
4725            description: None,
4726        });
4727        for e in [plan.clone(), ok_crit.clone(), stale_crit.clone()] {
4728            store.upsert(e.id.clone(), e);
4729        }
4730
4731        let state_of = |e: &crate::entity::Entity| {
4732            if e.id.0.contains("ok-crit") {
4733                CheckState::CheckedOk
4734            } else {
4735                CheckState::CheckStale
4736            }
4737        };
4738        let provider = |e: &crate::entity::Entity| {
4739            crate::engine::independence::CheckStanding::assumed_independent(state_of(e))
4740        };
4741        let violations = unsatisfied_constraints(&store, &plan, &td, None, Some(&provider));
4742        assert_eq!(violations.len(), 1, "{violations:?}");
4743        match &violations[0] {
4744            UnsatisfiedConstraint::TransitionRequiresChecks {
4745                unchecked,
4746                severity,
4747                ..
4748            } => {
4749                assert_eq!(
4750                    unchecked.len(),
4751                    1,
4752                    "only the unconfirmed criterion is listed"
4753                );
4754                assert_eq!(unchecked[0].id, "g--stale-crit");
4755                assert_eq!(unchecked[0].state, "check_stale");
4756                assert_eq!(*severity, memstead_schema::ConstraintSeverity::Block);
4757            }
4758            other => panic!("expected the gated-transition violation, got {other:?}"),
4759        }
4760        assert!(
4761            violations[0].describe().contains("g--stale-crit")
4762                && violations[0].describe().contains("check_stale"),
4763            "describe names the offender and its state: {}",
4764            violations[0].describe()
4765        );
4766
4767        // Every related entity confirmed -> satisfied.
4768        let all_ok = |_: &crate::entity::Entity| {
4769            crate::engine::independence::CheckStanding::assumed_independent(CheckState::CheckedOk)
4770        };
4771        assert!(
4772            unsatisfied_constraints(&store, &plan, &td, None, Some(&all_ok)).is_empty(),
4773            "all confirmed satisfies the gate"
4774        );
4775
4776        // Not at the gated value -> no evaluation.
4777        let mut draft = plan.clone();
4778        draft
4779            .metadata
4780            .insert("status".into(), MetadataValue::String("draft".into()));
4781        assert!(
4782            unsatisfied_constraints(&store, &draft, &td, None, Some(&provider)).is_empty(),
4783            "the gate triggers only at to_value"
4784        );
4785
4786        // No provider -> every related entity derives never_checked.
4787        let violations = unsatisfied_constraints(&store, &plan, &td, None, None);
4788        assert_eq!(violations.len(), 1);
4789        match &violations[0] {
4790            UnsatisfiedConstraint::TransitionRequiresChecks { unchecked, .. } => {
4791                assert_eq!(unchecked.len(), 2, "no ledger access confirms nothing");
4792                assert!(unchecked.iter().all(|u| u.state == "never_checked"));
4793            }
4794            other => panic!("expected the gated-transition violation, got {other:?}"),
4795        }
4796
4797        // Empty related set -> vacuously satisfied.
4798        let mut lone = make_typed_entity("g", "lone-plan", "plan");
4799        lone.metadata
4800            .insert("status".into(), MetadataValue::String("complete".into()));
4801        store.upsert(lone.id.clone(), lone.clone());
4802        assert!(
4803            unsatisfied_constraints(&store, &lone, &td, None, Some(&provider)).is_empty(),
4804            "an empty related set satisfies the universal quantification"
4805        );
4806    }
4807}