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