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        /// The chain of ids the taint travelled, from `tainted_by` first
1767        /// to this entity last, one shortest path (a stub on the way is
1768        /// named: it carried the edge). A reader of a finding on an
1769        /// entity with several parents can say through which parent the
1770        /// fall arrived instead of guessing; with several fallen sources
1771        /// each finding carries its own path.
1772        path: Vec<String>,
1773        severity: memstead_schema::ConstraintSeverity,
1774    },
1775    /// Form 6 — the entity holds the gated `to_value` while related
1776    /// entities lack a fresh confirming check record.
1777    TransitionRequiresChecks {
1778        field: String,
1779        to_value: String,
1780        relationships: Vec<String>,
1781        direction: memstead_schema::PropagationDirection,
1782        /// Every related entity NOT at derived state `checked_ok`,
1783        /// each with the state it derived, sorted by id.
1784        unchecked: Vec<UncheckedRelated>,
1785        /// How many related entities the declared edges reach.
1786        related: usize,
1787        /// The declared floor; a violation with `related < min_related`
1788        /// is the vacuous case the floor exists to refuse.
1789        min_related: usize,
1790        severity: memstead_schema::ConstraintSeverity,
1791    },
1792    /// Form 7 — the entity holds the gated `to_value` while it carries
1793    /// no fresh, independent, confirming check record of `check_kind`.
1794    TransitionRequiresSelfCheck {
1795        field: String,
1796        to_value: String,
1797        check_kind: String,
1798        /// The standing the entity's own record derived instead of an
1799        /// independent `checked_ok` (`never_checked`, `check_stale`,
1800        /// `check_failed`, `self_checked`, `unconfirmable`).
1801        state: String,
1802        severity: memstead_schema::ConstraintSeverity,
1803    },
1804    /// The entity reaches no non-stub entity of a terminal type along
1805    /// the declared relation set — the declaration is echoed whole so
1806    /// the reader sees which obligation went unmet without re-fetching
1807    /// the schema. Health-sweep only, always warn-tier.
1808    MustReach {
1809        relationships: Vec<String>,
1810        direction: memstead_schema::ReachDirection,
1811        terminal_types: Vec<String>,
1812        #[serde(skip_serializing_if = "Option::is_none")]
1813        max_depth: Option<u32>,
1814        severity: memstead_schema::ConstraintSeverity,
1815    },
1816}
1817
1818impl UnsatisfiedConstraint {
1819    pub fn severity(&self) -> memstead_schema::ConstraintSeverity {
1820        match self {
1821            Self::RequiresWhen { severity, .. }
1822            | Self::Unique { severity, .. }
1823            | Self::EnumFromNeighbour { severity, .. }
1824            | Self::StatusPropagation { severity, .. }
1825            | Self::MustReach { severity, .. }
1826            | Self::TransitionRequiresChecks { severity, .. }
1827            | Self::TransitionRequiresSelfCheck { severity, .. } => *severity,
1828        }
1829    }
1830
1831    /// One-line human rendering for warning/refusal message text.
1832    pub fn describe(&self) -> String {
1833        match self {
1834            Self::RequiresWhen {
1835                field,
1836                when_field,
1837                when_value,
1838                ..
1839            } => format!(
1840                "requires_when: '{field}' is required when {when_field}={when_value} and is unset"
1841            ),
1842            Self::Unique {
1843                fields, colliding, ..
1844            } => format!(
1845                "unique: tuple ({}) collides with '{colliding}'",
1846                fields.join(", ")
1847            ),
1848            Self::EnumFromNeighbour {
1849                field,
1850                value,
1851                rel_type,
1852                section,
1853                ..
1854            } => format!(
1855                "enum_from_neighbour: '{field}' value '{value}' has no backing entry in any \
1856                 `{section}` section reached via {rel_type}"
1857            ),
1858            Self::StatusPropagation {
1859                field,
1860                value,
1861                tainted_by,
1862                path,
1863                ..
1864            } => {
1865                format!(
1866                    "status_propagation: tainted by '{tainted_by}' ({field}={value}) via {}",
1867                    path.join(" → ")
1868                )
1869            }
1870            Self::MustReach {
1871                relationships,
1872                direction,
1873                terminal_types,
1874                max_depth,
1875                ..
1876            } => {
1877                let depth = match max_depth {
1878                    Some(d) => format!(" within {d} hop(s)"),
1879                    None => String::new(),
1880                };
1881                format!(
1882                    "must_reach: no path via [{}] ({direction}) reaches a [{}] entity{depth}",
1883                    relationships.join(", "),
1884                    terminal_types.join(", ")
1885                )
1886            }
1887            Self::TransitionRequiresChecks {
1888                field,
1889                to_value,
1890                relationships,
1891                unchecked,
1892                related,
1893                min_related,
1894                ..
1895            } => {
1896                if related < min_related {
1897                    return format!(
1898                        "transition_requires_checks: {field}={to_value} requires at least \
1899                         {min_related} related entit{} via [{}] — found {related}",
1900                        if *min_related == 1 { "y" } else { "ies" },
1901                        relationships.join(", ")
1902                    );
1903                }
1904                let listed: Vec<String> = unchecked
1905                    .iter()
1906                    .map(|u| format!("'{}' ({})", u.id, u.state))
1907                    .collect();
1908                format!(
1909                    "transition_requires_checks: {field}={to_value} requires a fresh confirming \
1910                     check record on every entity related via [{}] — unconfirmed: {}",
1911                    relationships.join(", "),
1912                    listed.join(", ")
1913                )
1914            }
1915            Self::TransitionRequiresSelfCheck {
1916                field,
1917                to_value,
1918                check_kind,
1919                state,
1920                ..
1921            } => format!(
1922                "transition_requires_self_check: {field}={to_value} requires a fresh confirming \
1923                 `{check_kind}` check record on this entity under an identity other than its \
1924                 author — derived: {state}"
1925            ),
1926        }
1927    }
1928}
1929
1930/// One related entity blocking a `transition_requires_checks` gate:
1931/// its id and the derived verification state it reads instead of the
1932/// required `checked_ok`.
1933#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
1934pub struct UncheckedRelated {
1935    pub id: String,
1936    pub state: String,
1937}
1938
1939/// The gated-transition evaluators' window into the check ledger:
1940/// the derived standing of one entity's newest check record of one
1941/// wire kind (`verification`, `conformance`, or a foreign `x-<name>`).
1942/// Callers with an engine build it from the workspace check ledger;
1943/// `None` (no ledger access — a workspace-less engine, or a call path
1944/// that cannot reach one) derives every entity as `never_checked`, so
1945/// a declared gate refuses honestly rather than passing unverified.
1946pub type CheckStateProvider<'a> =
1947    &'a dyn Fn(&crate::entity::Entity, &str) -> crate::engine::independence::CheckStanding;
1948
1949/// Evaluate one entity's declared per-entity `constraints` against its
1950/// current state (and, for the store-aware forms, against the rest of
1951/// its mem), returning the violated ones in declaration order. THE
1952/// single evaluation — shared by the health sweep
1953/// ([`collect_constraint_findings`]) and the per-mutation
1954/// `CONSTRAINT_UNSATISFIED` surface on create/update/relate; a second
1955/// implementation of any form is a defect.
1956///
1957/// Form semantics:
1958/// - `requires_when` triggers when `when_field`'s frontmatter value
1959///   equals `when_value` exactly; a triggered constraint is satisfied
1960///   when `field` — a metadata field or a section key — is present
1961///   with non-blank content.
1962/// - `unique`: the entity's tuple of `fields` values (skipped when any
1963///   field is unset/blank) must not equal another non-stub entity's
1964///   tuple within the same mem and type. `exclude` names the entity's
1965///   own id so an update does not collide with its stored self.
1966/// - `enum_from_neighbour`: a set `field` value must appear as a
1967///   bullet entry (`- value` / `* value` line) in the `section` body
1968///   of at least one entity reached via an outgoing `rel_type` edge.
1969/// - `status_propagation` is a reachability property of the graph,
1970///   not of one write — it is evaluated only by the health sweep
1971///   ([`collect_constraint_findings`]), never here.
1972pub fn unsatisfied_constraints(
1973    store: &Store,
1974    entity: &crate::entity::Entity,
1975    td: &TypeDefinition,
1976    exclude: Option<&crate::entity::EntityId>,
1977    checks: Option<CheckStateProvider<'_>>,
1978) -> Vec<UnsatisfiedConstraint> {
1979    use memstead_schema::ConstraintDef;
1980    td.constraints
1981        .iter()
1982        .filter_map(|c| match c {
1983            ConstraintDef::RequiresWhen {
1984                field,
1985                when_field,
1986                when_value,
1987                severity,
1988            } => {
1989                let triggered = entity
1990                    .metadata
1991                    .get(when_field.as_str())
1992                    .is_some_and(|v| v.to_frontmatter_string() == *when_value);
1993                if !triggered {
1994                    return None;
1995                }
1996                let satisfied = entity
1997                    .metadata
1998                    .get(field.as_str())
1999                    .is_some_and(|v| !v.to_frontmatter_string().trim().is_empty())
2000                    || entity
2001                        .sections
2002                        .get(field.as_str())
2003                        .is_some_and(|body| !body.trim().is_empty());
2004                if satisfied {
2005                    return None;
2006                }
2007                Some(UnsatisfiedConstraint::RequiresWhen {
2008                    field: field.clone(),
2009                    when_field: when_field.clone(),
2010                    when_value: when_value.clone(),
2011                    severity: *severity,
2012                })
2013            }
2014            ConstraintDef::Unique { fields, severity } => {
2015                let tuple = tuple_of(entity, fields)?;
2016                let mut colliding: Vec<&str> = store
2017                    .all_entities()
2018                    .filter(|other| {
2019                        !other.stub
2020                            && other.mem == entity.mem
2021                            && other.entity_type == entity.entity_type
2022                            && Some(&other.id) != exclude
2023                            && other.id != entity.id
2024                            && tuple_of(other, fields).as_ref() == Some(&tuple)
2025                    })
2026                    .map(|other| other.id.0.as_str())
2027                    .collect();
2028                colliding.sort_unstable();
2029                let first = colliding.first()?;
2030                Some(UnsatisfiedConstraint::Unique {
2031                    fields: fields.clone(),
2032                    values: tuple,
2033                    colliding: first.to_string(),
2034                    severity: *severity,
2035                })
2036            }
2037            ConstraintDef::EnumFromNeighbour {
2038                field,
2039                rel_type,
2040                section,
2041                severity,
2042            } => {
2043                let value = entity
2044                    .metadata
2045                    .get(field.as_str())
2046                    .map(|v| v.to_frontmatter_string())
2047                    .filter(|v| !v.trim().is_empty())?;
2048                let backed = entity
2049                    .relationships
2050                    .iter()
2051                    .filter(|rel| rel.rel_type == *rel_type)
2052                    .filter_map(|rel| store.get(&rel.target))
2053                    .filter_map(|neighbour| neighbour.sections.get(section.as_str()))
2054                    .any(|body| bullet_entries(body).contains(&value));
2055                if backed {
2056                    return None;
2057                }
2058                Some(UnsatisfiedConstraint::EnumFromNeighbour {
2059                    field: field.clone(),
2060                    value,
2061                    rel_type: rel_type.clone(),
2062                    section: section.clone(),
2063                    severity: *severity,
2064                })
2065            }
2066            ConstraintDef::StatusPropagation { .. } => None,
2067            ConstraintDef::TransitionRequiresChecks {
2068                field,
2069                to_value,
2070                relationships,
2071                direction,
2072                min_related,
2073                severity,
2074            } => {
2075                let triggered = entity
2076                    .metadata
2077                    .get(field.as_str())
2078                    .is_some_and(|v| v.to_frontmatter_string() == *to_value);
2079                if !triggered {
2080                    return None;
2081                }
2082                let (related, unchecked) = transition_gate_standing(
2083                    store,
2084                    entity,
2085                    relationships,
2086                    *direction,
2087                    exclude,
2088                    checks,
2089                );
2090                if unchecked.is_empty() && related >= *min_related {
2091                    return None;
2092                }
2093                Some(UnsatisfiedConstraint::TransitionRequiresChecks {
2094                    field: field.clone(),
2095                    to_value: to_value.clone(),
2096                    relationships: relationships.clone(),
2097                    direction: *direction,
2098                    unchecked,
2099                    related,
2100                    min_related: *min_related,
2101                    severity: *severity,
2102                })
2103            }
2104            ConstraintDef::TransitionRequiresSelfCheck {
2105                field,
2106                to_value,
2107                check_kind,
2108                severity,
2109            } => {
2110                let triggered = entity
2111                    .metadata
2112                    .get(field.as_str())
2113                    .is_some_and(|v| v.to_frontmatter_string() == *to_value);
2114                if !triggered {
2115                    return None;
2116                }
2117                // The entity's own record of the declared kind, read
2118                // through the same provider form 6 reads related
2119                // entities with: no ledger derives never_checked, the
2120                // author's own ok reads self_checked, neither confirms.
2121                let standing = match checks {
2122                    Some(provider) => provider(entity, check_kind),
2123                    None => crate::engine::independence::CheckStanding {
2124                        state: crate::check::CheckState::NeverChecked,
2125                        independence: None,
2126                        role: crate::vcs::Role::Unspecified,
2127                    },
2128                };
2129                if standing.confirms() {
2130                    return None;
2131                }
2132                Some(UnsatisfiedConstraint::TransitionRequiresSelfCheck {
2133                    field: field.clone(),
2134                    to_value: to_value.clone(),
2135                    check_kind: check_kind.clone(),
2136                    state: standing.label().to_string(),
2137                    severity: *severity,
2138                })
2139            }
2140        })
2141        .collect()
2142}
2143
2144/// The standing of one gated-transition constraint's related set
2145/// against one entity, independent of whether the entity currently
2146/// holds the gated value: `(total related, those lacking a fresh
2147/// confirming check record)`, the unconfirmed sorted by id. THE single
2148/// related-set enumeration — shared by the write-time evaluator arm
2149/// above and the gates-brief renderer, so the brief can never disagree
2150/// with the refusal. Outgoing reads the entity's own edges (its
2151/// written state); incoming scans the store for edge sources pointing
2152/// at it, excluding the entity's own stored copy (`exclude`) so an
2153/// update never gates on its pre-write self.
2154pub fn transition_gate_standing(
2155    store: &Store,
2156    entity: &crate::entity::Entity,
2157    relationships: &[String],
2158    direction: memstead_schema::PropagationDirection,
2159    exclude: Option<&crate::entity::EntityId>,
2160    checks: Option<CheckStateProvider<'_>>,
2161) -> (usize, Vec<UncheckedRelated>) {
2162    let related: Vec<&crate::entity::Entity> = match direction {
2163        memstead_schema::PropagationDirection::Outgoing => entity
2164            .relationships
2165            .iter()
2166            .filter(|rel| relationships.contains(&rel.rel_type))
2167            .filter_map(|rel| store.get(&rel.target))
2168            .collect(),
2169        memstead_schema::PropagationDirection::Incoming => store
2170            .all_entities()
2171            .filter(|other| {
2172                other.id != entity.id
2173                    && Some(&other.id) != exclude
2174                    && other
2175                        .relationships
2176                        .iter()
2177                        .any(|rel| rel.target == entity.id && relationships.contains(&rel.rel_type))
2178            })
2179            .collect(),
2180    };
2181    let total = related.len();
2182    let mut unchecked: Vec<UncheckedRelated> = related
2183        .into_iter()
2184        .filter_map(|rel_entity| {
2185            // An ok check confirms only when it is independent of the
2186            // executors (engine::independence): the executor's own ok
2187            // reads `self_checked` here and does not close the gate.
2188            let standing = match checks {
2189                Some(provider) => {
2190                    provider(rel_entity, crate::check::CheckKind::Verification.as_str())
2191                }
2192                None => crate::engine::independence::CheckStanding {
2193                    state: crate::check::CheckState::NeverChecked,
2194                    independence: None,
2195                    role: crate::vcs::Role::Unspecified,
2196                },
2197            };
2198            if standing.confirms() {
2199                None
2200            } else {
2201                Some(UncheckedRelated {
2202                    id: rel_entity.id.0.clone(),
2203                    state: standing.label().to_string(),
2204                })
2205            }
2206        })
2207        .collect();
2208    unchecked.sort_by(|a, b| a.id.cmp(&b.id));
2209    (total, unchecked)
2210}
2211
2212/// The entity's tuple of frontmatter values for `fields`, in
2213/// declaration order — `None` when any field is unset or blank (no
2214/// tuple, nothing to compare).
2215fn tuple_of(entity: &crate::entity::Entity, fields: &[String]) -> Option<Vec<String>> {
2216    fields
2217        .iter()
2218        .map(|f| {
2219            entity
2220                .metadata
2221                .get(f.as_str())
2222                .map(|v| v.to_frontmatter_string())
2223                .filter(|v| !v.trim().is_empty())
2224        })
2225        .collect()
2226}
2227
2228/// The bullet entries of a section body — trimmed text of `- item` /
2229/// `* item` lines. The legal-value shape `enum_from_neighbour` reads.
2230fn bullet_entries(body: &str) -> Vec<String> {
2231    // A bullet inside a code block is an example of the list, not a
2232    // member of it — the same referee every other content reader uses
2233    // ([`crate::markdown`]). Masking preserves byte offsets and line
2234    // count, so each masked line pairs with its original.
2235    let masked = crate::markdown::mask_code_blocks_and_spans(body);
2236    body.lines()
2237        .zip(masked.lines())
2238        .filter_map(|(line, masked_line)| {
2239            let m = masked_line.trim_start();
2240            if m.starts_with("- ") || m.starts_with("* ") {
2241                let t = line.trim_start();
2242                t.strip_prefix("- ")
2243                    .or_else(|| t.strip_prefix("* "))
2244                    .map(|e| e.trim().to_string())
2245            } else {
2246                None
2247            }
2248        })
2249        .collect()
2250}
2251
2252/// One entity's violated declared constraints, surfaced from the
2253/// health-time scan (`include=["constraints"]`). Mirrors
2254/// [`MissingRequiredOutgoingReport`]'s envelope shape — the two
2255/// includes read the same way.
2256#[derive(Debug, Clone, serde::Serialize)]
2257pub struct ConstraintFindingReport {
2258    pub id: crate::entity::EntityId,
2259    pub title: String,
2260    pub entity_type: String,
2261    pub mem: String,
2262    pub violations: Vec<UnsatisfiedConstraint>,
2263    /// Standing violations of the entity's declared section formats
2264    /// (plan 08) — additive: consumers of the pre-format shape see an
2265    /// absent key, never an empty list.
2266    #[serde(skip_serializing_if = "Vec::is_empty")]
2267    pub format_violations: Vec<crate::section_format::SectionFormatViolation>,
2268}
2269
2270/// Collect every non-stub entity whose declared `constraints` its
2271/// current state violates. Two passes: the per-entity forms
2272/// (`requires_when`, `unique`, `enum_from_neighbour`) through the
2273/// shared [`unsatisfied_constraints`] evaluation, then the
2274/// `status_propagation` graph sweep — for each entity holding a
2275/// declared terminal value, every entity reaching it (transitively)
2276/// via the declared rel-type and direction gains a finding naming that
2277/// tainting ancestor. Deterministic — reports sorted by `(mem, id)`,
2278/// violations in declaration order then by tainting ancestor.
2279pub fn collect_constraint_findings(
2280    store: &Store,
2281    mem_filter: Option<&str>,
2282    mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
2283    checks: Option<CheckStateProvider<'_>>,
2284) -> Vec<ConstraintFindingReport> {
2285    use memstead_schema::ConstraintDef;
2286    type Bucket = (
2287        Vec<UnsatisfiedConstraint>,
2288        Vec<crate::section_format::SectionFormatViolation>,
2289    );
2290    let mut by_entity: std::collections::BTreeMap<String, Bucket> = Default::default();
2291
2292    // Reverse adjacency for `must_reach` incoming walks — built once
2293    // per sweep, and only when some pinned schema declares one (a
2294    // workspace without the form pays nothing).
2295    let needs_reverse = mem_schemas.values().any(|s| {
2296        s.types.values().any(|t| {
2297            t.must_reach
2298                .iter()
2299                .any(|ob| ob.direction == memstead_schema::ReachDirection::In)
2300        })
2301    });
2302    let reverse: ReverseIndex = if needs_reverse {
2303        build_reverse_index(store)
2304    } else {
2305        ReverseIndex::default()
2306    };
2307
2308    for entity in store.all_entities() {
2309        if entity.stub {
2310            continue;
2311        }
2312        if let Some(v) = mem_filter
2313            && entity.mem != v
2314        {
2315            continue;
2316        }
2317        let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
2318            continue;
2319        };
2320        let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
2321            continue;
2322        };
2323
2324        // Section-format sweep (plan 08) — standing violations of a
2325        // declared markdown shape, every severity (block-tier
2326        // pre-existing violations are health findings too; the next
2327        // write of the section is the sanctioned repair point).
2328        for def in &td.sections {
2329            if def.compiled_content.is_none() {
2330                continue;
2331            }
2332            let Some(body) = entity.sections.get(def.key.as_str()) else {
2333                continue;
2334            };
2335            let violations = crate::section_format::check_section_format(def, body);
2336            if !violations.is_empty() {
2337                by_entity
2338                    .entry(entity.id.0.clone())
2339                    .or_default()
2340                    .1
2341                    .extend(violations);
2342            }
2343        }
2344
2345        // Reachability obligations — health-sweep only by design (no
2346        // single write completes a transitive absence, so the write
2347        // path never evaluates these). The finding echoes the whole
2348        // declaration.
2349        for ob in &td.must_reach {
2350            if !reaches_terminal(store, &reverse, &entity.id, ob) {
2351                by_entity.entry(entity.id.0.clone()).or_default().0.push(
2352                    UnsatisfiedConstraint::MustReach {
2353                        relationships: ob.relationships.clone(),
2354                        direction: ob.direction,
2355                        terminal_types: ob.terminal_types.clone(),
2356                        max_depth: ob.max_depth,
2357                        severity: ob.severity,
2358                    },
2359                );
2360            }
2361        }
2362
2363        if td.constraints.is_empty() {
2364            continue;
2365        }
2366
2367        // Pass 1 — per-entity forms.
2368        let violations = unsatisfied_constraints(store, entity, td, None, checks);
2369        if !violations.is_empty() {
2370            by_entity
2371                .entry(entity.id.0.clone())
2372                .or_default()
2373                .0
2374                .extend(violations);
2375        }
2376    }
2377
2378    // Pass 2 — every entity as a taint source, whatever mem it lives
2379    // in: it holds a declared terminal value, so sweep its dependents.
2380    // The taint walks the declared relation set's union subgraph (a
2381    // single `rel_type` is a one-element set) and crosses mem
2382    // boundaries like any walk here; the mem filter narrows which
2383    // TAINTED entities are reported, never which sources are swept.
2384    // Folded into the per-entity loop above, the filter skipped a
2385    // source in another mem before its dependents in the filtered mem
2386    // were ever computed, so a mem resting on a fallen card elsewhere
2387    // read clean under `--mem` and tainted without it. Sources are
2388    // swept in id order, so an entity tainted by several ancestors
2389    // carries its findings in the same order on every run.
2390    let mut sources: Vec<&crate::entity::Entity> =
2391        store.all_entities().filter(|e| !e.stub).collect();
2392    sources.sort_by(|a, b| a.id.0.cmp(&b.id.0));
2393    for entity in sources {
2394        let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
2395            continue;
2396        };
2397        let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
2398            continue;
2399        };
2400        for c in &td.constraints {
2401            let ConstraintDef::StatusPropagation {
2402                field,
2403                value,
2404                rel_type,
2405                rel_types,
2406                direction,
2407                severity,
2408            } = c
2409            else {
2410                continue;
2411            };
2412            let terminal = entity
2413                .metadata
2414                .get(field.as_str())
2415                .is_some_and(|v| v.to_frontmatter_string() == *value);
2416            if !terminal {
2417                continue;
2418            }
2419            let set = c
2420                .propagation_rel_types()
2421                .expect("StatusPropagation always yields a set");
2422            for (tainted, path) in reach_transitively(store, &entity.id, &set, *direction) {
2423                if let Some(v) = mem_filter
2424                    && tainted.mem() != v
2425                {
2426                    continue;
2427                }
2428                by_entity.entry(tainted.0.clone()).or_default().0.push(
2429                    UnsatisfiedConstraint::StatusPropagation {
2430                        field: field.clone(),
2431                        value: value.clone(),
2432                        rel_type: rel_type.clone(),
2433                        rel_types: rel_types.clone(),
2434                        tainted_by: entity.id.to_string(),
2435                        path: path.iter().map(ToString::to_string).collect(),
2436                        severity: *severity,
2437                    },
2438                );
2439            }
2440        }
2441    }
2442
2443    let mut out: Vec<ConstraintFindingReport> = by_entity
2444        .into_iter()
2445        .filter_map(|(id, (violations, format_violations))| {
2446            let id = crate::entity::EntityId(id);
2447            let entity = store.get(&id)?;
2448            Some(ConstraintFindingReport {
2449                id,
2450                title: entity.title.clone(),
2451                entity_type: entity.entity_type.clone(),
2452                mem: entity.mem.clone(),
2453                violations,
2454                format_violations,
2455            })
2456        })
2457        .collect();
2458    out.sort_by(|a, b| a.mem.cmp(&b.mem).then_with(|| a.id.0.cmp(&b.id.0)));
2459    out
2460}
2461
2462/// Transitive reachability along one rel-type from `start`, excluding
2463/// `start` itself, each reached entity with the path the walk took to
2464/// it (`start` first, the entity last). `Incoming` walks against edge
2465/// direction (the entities whose `rel_type` edges point at the frontier
2466/// — "what stands on this"); `Outgoing` follows the frontier's own
2467/// edges. Breadth first with neighbours in id order, so the path is one
2468/// shortest path and the same one on every run. Stubs are traversed (an
2469/// edge through a stub still transmits the taint) and named on the
2470/// paths that cross them, but stubs themselves are not returned.
2471fn reach_transitively(
2472    store: &Store,
2473    start: &crate::entity::EntityId,
2474    rel_types: &[String],
2475    direction: memstead_schema::PropagationDirection,
2476) -> Vec<(crate::entity::EntityId, Vec<crate::entity::EntityId>)> {
2477    use memstead_schema::PropagationDirection;
2478    let mut parent: std::collections::HashMap<crate::entity::EntityId, crate::entity::EntityId> =
2479        Default::default();
2480    let mut seen: std::collections::HashSet<crate::entity::EntityId> =
2481        std::iter::once(start.clone()).collect();
2482    let mut frontier = std::collections::VecDeque::from([start.clone()]);
2483    let mut reached = Vec::new();
2484    while let Some(current) = frontier.pop_front() {
2485        let mut next: Vec<crate::entity::EntityId> = match direction {
2486            PropagationDirection::Incoming => store
2487                .all_entities()
2488                .filter(|e| {
2489                    e.relationships
2490                        .iter()
2491                        .any(|r| rel_types.iter().any(|n| n == &r.rel_type) && r.target == current)
2492                })
2493                .map(|e| e.id.clone())
2494                .collect(),
2495            PropagationDirection::Outgoing => store
2496                .get(&current)
2497                .map(|e| {
2498                    e.relationships
2499                        .iter()
2500                        .filter(|r| rel_types.iter().any(|n| n == &r.rel_type))
2501                        .map(|r| r.target.clone())
2502                        .collect()
2503                })
2504                .unwrap_or_default(),
2505        };
2506        next.sort_by(|a, b| a.0.cmp(&b.0));
2507        for id in next {
2508            if seen.insert(id.clone()) {
2509                parent.insert(id.clone(), current.clone());
2510                if store.get(&id).is_some_and(|e| !e.stub) {
2511                    let mut path = vec![id.clone()];
2512                    let mut at = id.clone();
2513                    while let Some(p) = parent.get(&at) {
2514                        path.push(p.clone());
2515                        at = p.clone();
2516                    }
2517                    path.reverse();
2518                    reached.push((id.clone(), path));
2519                }
2520                frontier.push_back(id);
2521            }
2522        }
2523    }
2524    reached
2525}
2526
2527/// Reverse adjacency for `must_reach` incoming walks: target id →
2528/// `(rel_type, source id)` pairs. Built once per sweep so the
2529/// incoming direction stays O(edges) instead of re-scanning the store
2530/// per frontier node.
2531type ReverseIndex =
2532    std::collections::HashMap<crate::entity::EntityId, Vec<(String, crate::entity::EntityId)>>;
2533
2534fn build_reverse_index(store: &Store) -> ReverseIndex {
2535    let mut idx = ReverseIndex::default();
2536    for entity in store.all_entities() {
2537        for rel in &entity.relationships {
2538            idx.entry(rel.target.clone())
2539                .or_default()
2540                .push((rel.rel_type.clone(), entity.id.clone()));
2541        }
2542    }
2543    idx
2544}
2545
2546/// Whether `start` reaches at least one non-stub entity of a terminal
2547/// type along the obligation's relation set, direction, and depth
2548/// bound. Breadth-first with visited-set discipline (cycles along the
2549/// walked set terminate); stubs terminate no obligation — they carry
2550/// no outgoing edges and never count as reached terminals. Cross-mem
2551/// edges are followed like any edge, matching the propagation walk
2552/// and the cycle check (the engine's established traversal posture);
2553/// the start entity itself never satisfies its own obligation.
2554fn reaches_terminal(
2555    store: &Store,
2556    reverse: &ReverseIndex,
2557    start: &crate::entity::EntityId,
2558    ob: &memstead_schema::MustReach,
2559) -> bool {
2560    use memstead_schema::ReachDirection;
2561    let mut seen: std::collections::HashSet<crate::entity::EntityId> =
2562        std::iter::once(start.clone()).collect();
2563    let mut frontier = vec![start.clone()];
2564    let mut depth: u32 = 0;
2565    while !frontier.is_empty() {
2566        if let Some(max) = ob.max_depth
2567            && depth >= max
2568        {
2569            return false;
2570        }
2571        depth += 1;
2572        let mut next_frontier = Vec::new();
2573        for current in frontier {
2574            let next: Vec<crate::entity::EntityId> = match ob.direction {
2575                ReachDirection::Out => store
2576                    .get(&current)
2577                    .map(|e| {
2578                        e.relationships
2579                            .iter()
2580                            .filter(|r| ob.relationships.iter().any(|n| n == &r.rel_type))
2581                            .map(|r| r.target.clone())
2582                            .collect()
2583                    })
2584                    .unwrap_or_default(),
2585                ReachDirection::In => reverse
2586                    .get(&current)
2587                    .map(|sources| {
2588                        sources
2589                            .iter()
2590                            .filter(|(rel, _)| ob.relationships.iter().any(|n| n == rel))
2591                            .map(|(_, src)| src.clone())
2592                            .collect()
2593                    })
2594                    .unwrap_or_default(),
2595            };
2596            for id in next {
2597                if seen.insert(id.clone()) {
2598                    if store.get(&id).is_some_and(|e| {
2599                        !e.stub && ob.terminal_types.iter().any(|t| t == &e.entity_type)
2600                    }) {
2601                        return true;
2602                    }
2603                    next_frontier.push(id);
2604                }
2605            }
2606        }
2607        frontier = next_frontier;
2608    }
2609    false
2610}
2611
2612/// One entity's above-`none` signals, surfaced from the include-gated
2613/// `signals` health axis. Mirrors [`ConstraintFindingReport`]'s
2614/// envelope shape; the `signals` entries carry value, level, and
2615/// contributors (the evidence ships with the number, always).
2616#[derive(Debug, Clone, serde::Serialize)]
2617pub struct SignalReport {
2618    pub id: crate::entity::EntityId,
2619    pub title: String,
2620    pub entity_type: String,
2621    pub mem: String,
2622    /// Only signals whose level is not `none`, in declaration order.
2623    pub signals: Vec<super::signals::ComputedSignal>,
2624}
2625
2626impl SignalReport {
2627    /// Whether any entry is `warn`-level — the `--strict`
2628    /// participation test (a `notice` never participates; that is the
2629    /// whole difference between the two levels).
2630    pub fn has_warn(&self) -> bool {
2631        self.signals
2632            .iter()
2633            .any(|s| s.level == Some(memstead_schema::SignalLevel::Warn))
2634    }
2635}
2636
2637/// Collect every non-stub entity carrying at least one declared
2638/// signal above `none`. Deterministic — sorted by `(mem, id)`;
2639/// signals in declaration order, contributors sorted.
2640pub fn collect_signal_reports(
2641    store: &Store,
2642    mem_filter: Option<&str>,
2643    mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
2644) -> Vec<SignalReport> {
2645    let mut out = Vec::new();
2646    for entity in store.all_entities() {
2647        if entity.stub {
2648            continue;
2649        }
2650        if let Some(v) = mem_filter
2651            && entity.mem != v
2652        {
2653            continue;
2654        }
2655        let Some(mem_schema) = mem_schemas.get(entity.mem.as_str()) else {
2656            continue;
2657        };
2658        let Some(td) = mem_schema.types.get(entity.entity_type.as_str()) else {
2659            continue;
2660        };
2661        if td.signals.is_empty() {
2662            continue;
2663        }
2664        let above: Vec<super::signals::ComputedSignal> =
2665            super::signals::compute_signals(store, td, &entity.id)
2666                .into_iter()
2667                .filter(|s| s.level.is_some())
2668                .collect();
2669        if above.is_empty() {
2670            continue;
2671        }
2672        out.push(SignalReport {
2673            id: entity.id.clone(),
2674            title: entity.title.clone(),
2675            entity_type: entity.entity_type.clone(),
2676            mem: entity.mem.clone(),
2677            signals: above,
2678        });
2679    }
2680    out.sort_by(|a, b| a.mem.cmp(&b.mem).then_with(|| a.id.0.cmp(&b.id.0)));
2681    out
2682}
2683
2684/// A defective section-format declaration a loaded schema carries
2685/// (recorded by the lenient boot path; install would have refused).
2686/// Surfaced under the health `constraints` include so a sealed schema
2687/// with a bad declaration is visible without bricking boot.
2688#[derive(Debug, Clone, serde::Serialize)]
2689pub struct SchemaFormatDefect {
2690    pub schema: String,
2691    pub type_name: String,
2692    pub section: String,
2693    pub problems: Vec<String>,
2694}
2695
2696/// Collect the defective section-format declarations across the
2697/// mounted mems' pinned schemas, deduplicated per schema ref,
2698/// deterministic order.
2699pub fn collect_schema_format_defects(
2700    mem_schemas: &HashMap<String, Arc<memstead_schema::Schema>>,
2701) -> Vec<SchemaFormatDefect> {
2702    let mut seen: std::collections::BTreeSet<String> = Default::default();
2703    let mut out = Vec::new();
2704    let mut schemas: Vec<&Arc<memstead_schema::Schema>> = mem_schemas.values().collect();
2705    schemas.sort_by_key(|s| (s.manifest.name.clone(), s.version.clone()));
2706    for schema in schemas {
2707        let schema_ref = format!("{}@{}", schema.manifest.name, schema.version);
2708        if !seen.insert(schema_ref.clone()) {
2709            continue;
2710        }
2711        for td in schema.types.values() {
2712            for section in &td.sections {
2713                if !section.format_problems.is_empty() {
2714                    out.push(SchemaFormatDefect {
2715                        schema: schema_ref.clone(),
2716                        type_name: td.name.clone(),
2717                        section: section.key.clone(),
2718                        problems: section.format_problems.clone(),
2719                    });
2720                }
2721            }
2722        }
2723    }
2724    out.sort_by(|a, b| {
2725        (&a.schema, &a.type_name, &a.section).cmp(&(&b.schema, &b.type_name, &b.section))
2726    });
2727    out
2728}
2729
2730/// One entity's unsatisfied `required_outgoing` blocks, surfaced from
2731/// the health-time scan. `missing` reuses the per-write warning's wire
2732/// block type — one struct, one serialized shape (`{ relationships,
2733/// cardinality }`) on both surfaces — and adds the `mem` name (the
2734/// warning's `entity_id` already encodes it via the mem prefix, but
2735/// health is multi-mem by default and an explicit field is cheaper for
2736/// downstream filters).
2737#[derive(Debug, Clone, serde::Serialize)]
2738pub struct MissingRequiredOutgoingReport {
2739    pub id: crate::entity::EntityId,
2740    pub title: String,
2741    pub entity_type: String,
2742    pub mem: String,
2743    pub missing: Vec<super::MissingRequiredOutgoingBlock>,
2744}
2745
2746/// Render the workspace-config projection the health surface serves —
2747/// per-writable-mem detail (`origin`, storage/durability, `vcs`
2748/// `gitdir`/`worktree`/`head`, title/subject, `write_guidance`,
2749/// `extra`) plus the `mutations` and `plugin` policy values. One
2750/// implementation, every surface: the MCP composer reaches it through
2751/// `include_config: true` OR the `config` include key; the CLI through
2752/// `--include config`. `mutations` / `plugin` are passed prebuilt so a
2753/// server that owns its own copies inserts them verbatim; callers
2754/// without server state derive them from `Engine::settings()` (see
2755/// [`config_projection_from_settings`]). Returns the three top-level
2756/// entries (`mems`, `mutations`, `plugin`) for the caller to merge —
2757/// callers gate on their own opt-in flag and must render at most once.
2758pub fn config_projection(
2759    engine: &crate::Engine,
2760    writable_mems: &[String],
2761    mutations: serde_json::Value,
2762    plugin: serde_json::Value,
2763) -> serde_json::Map<String, serde_json::Value> {
2764    // Per-mem storage backend → durability marker, derived from the
2765    // mount's `MountStorage` kind. Lives alongside `vcs` so an agent
2766    // reading per-mem config learns whether a `write_id` this mem
2767    // returns is durable-on-disk or volatile-in-RAM.
2768    let backend_by_mem: std::collections::HashMap<&str, (&'static str, bool)> = engine
2769        .mounts()
2770        .iter()
2771        .map(|m| {
2772            (
2773                m.mem.as_str(),
2774                (m.storage.backend_id(), m.storage.is_durable()),
2775            )
2776        })
2777        .collect();
2778    let mems_detail: Vec<serde_json::Value> = writable_mems
2779        .iter()
2780        .map(|name| {
2781            let origin = engine
2782                .mem_router()
2783                .origin_for_mem(name)
2784                .map(|o| o.kind())
2785                .unwrap_or("explicit");
2786            let mut entry = serde_json::Map::new();
2787            entry.insert("name".into(), serde_json::json!(name));
2788            entry.insert("origin".into(), serde_json::json!(origin));
2789            if let Some((storage, durable)) = backend_by_mem.get(name.as_str()).copied() {
2790                entry.insert("storage".into(), serde_json::json!(storage));
2791                entry.insert("durable".into(), serde_json::json!(durable));
2792            }
2793            let mut vcs_obj = serde_json::Map::new();
2794            if let Ok(gitdir) = engine.gitdir_for(name) {
2795                vcs_obj.insert("gitdir".into(), serde_json::json!(gitdir));
2796            }
2797            if let Ok(worktree) = engine.worktree_for(name) {
2798                vcs_obj.insert("worktree".into(), serde_json::json!(worktree));
2799            }
2800            if let Some(sha) = engine.mem_head_sha(name).ok().flatten() {
2801                vcs_obj.insert("head".into(), serde_json::json!(sha));
2802            }
2803            if !vcs_obj.is_empty() {
2804                entry.insert("vcs".into(), serde_json::Value::Object(vcs_obj));
2805            }
2806            if let Some(cfg) = engine.mem_config_for(name) {
2807                // Display title + subject block, when set — the
2808                // config projection prefers the title wherever a
2809                // mem is printed; the name stays the identity.
2810                if let Some(title) = &cfg.title {
2811                    entry.insert("title".into(), serde_json::json!(title));
2812                }
2813                if let Some(subject) = &cfg.subject {
2814                    entry.insert("subject".into(), serde_json::json!(subject));
2815                }
2816                let guidance = serde_json::Map::from_iter(
2817                    cfg.write_guidance
2818                        .iter()
2819                        .map(|(k, v)| (k.clone(), v.clone())),
2820                );
2821                entry.insert("write_guidance".into(), serde_json::Value::Object(guidance));
2822                let extra = serde_json::Map::from_iter(
2823                    cfg.extra.iter().map(|(k, v)| (k.clone(), v.clone())),
2824                );
2825                entry.insert("extra".into(), serde_json::Value::Object(extra));
2826            }
2827            serde_json::Value::Object(entry)
2828        })
2829        .collect();
2830
2831    let mut out = serde_json::Map::new();
2832    out.insert("mems".into(), serde_json::json!(mems_detail));
2833    out.insert("mutations".into(), mutations);
2834    out.insert("plugin".into(), plugin);
2835    out
2836}
2837
2838/// The `(mutations, plugin)` pair for [`config_projection`], derived
2839/// from the engine's own [`crate::workspace::WorkspaceSettings`] — for
2840/// callers (the CLI) that carry no server-owned config copies. Produces
2841/// the same bytes the MCP server passes when both were loaded from the
2842/// same `workspace.toml`.
2843pub fn config_projection_from_settings(
2844    settings: &crate::workspace::WorkspaceSettings,
2845) -> (serde_json::Value, serde_json::Value) {
2846    let mutations = serde_json::json!({ "require_notes": settings.mutations.require_notes });
2847    let plugin_map: serde_json::Map<String, serde_json::Value> = settings
2848        .plugin
2849        .iter()
2850        .map(|(k, v)| {
2851            (
2852                k.clone(),
2853                serde_json::to_value(v).unwrap_or(serde_json::Value::Null),
2854            )
2855        })
2856        .collect();
2857    (mutations, serde_json::Value::Object(plugin_map))
2858}
2859
2860/// Detect the section-fork condition for one declared section: the
2861/// parsed content under `key` is empty, the schema's declared heading
2862/// for the key does not derive back to it
2863/// (`derive_section_key(heading) != key`), and the file carries that
2864/// declared heading — so the content is present in the file but
2865/// unreachable under the key: absorbed into the catch-all when the
2866/// type declares one, dropped from the parsed sections otherwise.
2867///
2868/// Returns the distinct `SECTION_HEADING_MISMATCH` issue naming both
2869/// the found heading and what a deriving heading would look like. The
2870/// caller must NOT also report the section as missing — collapsing the
2871/// two conditions into the missing-section report is exactly the
2872/// misdirection this finding exists to prevent (the operator goes
2873/// hunting for absent content that is in fact present).
2874pub(crate) fn section_heading_mismatch_issue(
2875    entity: &crate::entity::Entity,
2876    schema: &TypeDefinition,
2877    key: &str,
2878) -> Option<HealthIssue> {
2879    let def = schema.section(key)?;
2880    let derived = memstead_schema::derive_section_key(&def.heading);
2881    if derived == key {
2882        return None;
2883    }
2884    if !entity
2885        .raw_section_headings
2886        .iter()
2887        .any(|h| h == &def.heading)
2888    {
2889        return None;
2890    }
2891    let landing = match schema.catch_all_section() {
2892        Some(c) => format!(
2893            "the content was absorbed into catch-all section '{}'",
2894            c.key
2895        ),
2896        None => "the content is unreachable under any declared key".to_string(),
2897    };
2898    Some(HealthIssue {
2899        field: key.to_string(),
2900        code: super::HealthIssueCode::SectionHeadingMismatch,
2901        message: format!(
2902            "SECTION_HEADING_MISMATCH: section '{key}' is not missing — its content sits \
2903             under heading '{found}', which derives to '{derived}', not '{key}'; {landing}. \
2904             The schema's declared heading cannot round-trip to its key (expected a heading \
2905             that derives to '{key}'); fix the schema's heading/key pair — new installs of \
2906             such a schema are refused",
2907            found = def.heading,
2908        ),
2909    })
2910}
2911
2912/// Get a single entity's health report.
2913pub fn entity_health(entity: &crate::entity::Entity, schema: &TypeDefinition) -> HealthReport {
2914    let mut issues = Vec::new();
2915
2916    for field in &schema.health_required_fields {
2917        if schema.section(field).is_some() {
2918            let content = entity.sections.get(field.as_str());
2919            if content.is_none_or(|c| c.trim().is_empty()) {
2920                if let Some(issue) = section_heading_mismatch_issue(entity, schema, field) {
2921                    issues.push(issue);
2922                } else {
2923                    issues.push(HealthIssue {
2924                        field: field.clone(),
2925                        code: super::HealthIssueCode::Missing,
2926                        message: format!("required section '{field}' is empty"),
2927                    });
2928                }
2929            }
2930        } else {
2931            let value = entity.metadata.get(field.as_str());
2932            if value.is_none() {
2933                issues.push(HealthIssue {
2934                    field: field.clone(),
2935                    code: super::HealthIssueCode::Missing,
2936                    message: format!("required field '{field}' is missing"),
2937                });
2938            }
2939        }
2940    }
2941
2942    // The mismatch condition is drift worth surfacing on every declared
2943    // section, not only the health-required ones — an optional section
2944    // whose content forked away is just as invisible to readers.
2945    for s in schema.sections.iter().filter(|s| !s.catch_all) {
2946        if schema.health_required_fields.contains(&s.key) {
2947            continue; // already handled above
2948        }
2949        let content = entity.sections.get(s.key.as_str());
2950        if content.is_none_or(|c| c.trim().is_empty())
2951            && let Some(issue) = section_heading_mismatch_issue(entity, schema, &s.key)
2952        {
2953            issues.push(issue);
2954        }
2955    }
2956
2957    let total = schema.health_required_fields.len();
2958    let score = if total > 0 {
2959        (total.saturating_sub(issues.len()) as f32) / (total as f32)
2960    } else {
2961        1.0
2962    };
2963
2964    HealthReport {
2965        id: entity.id.clone(),
2966        title: entity.title.clone(),
2967        score,
2968        issues,
2969    }
2970}
2971
2972// ---------------------------------------------------------------------------
2973// Date helpers
2974// ---------------------------------------------------------------------------
2975
2976/// Get current days since Unix epoch.
2977///
2978/// `SystemTime::now()` is unimplemented on `wasm32-unknown-unknown` —
2979/// it traps with `RuntimeError: unreachable` and poisons the wasm
2980/// instance (cold-start F11) — so the wasm build reads the JS-backed
2981/// clock instead. Same value, same summary shape on every target.
2982/// Today as whole days since the Unix epoch, the clock every day-threshold
2983/// reading in health uses. `MEMSTEAD_TODAY=YYYY-MM-DD` pins it (the
2984/// injection a fixture needs to age entities without waiting), honoured
2985/// by every binary alike so the CLI and the MCP server read the same day.
2986pub fn days_since_epoch() -> u64 {
2987    if let Some(pinned) = std::env::var("MEMSTEAD_TODAY")
2988        .ok()
2989        .and_then(|s| crate::engine::due::pinned_days_since_epoch(&s))
2990    {
2991        return pinned;
2992    }
2993    #[cfg(target_arch = "wasm32")]
2994    {
2995        (js_sys::Date::now() / 1000.0) as u64 / 86400
2996    }
2997    #[cfg(not(target_arch = "wasm32"))]
2998    {
2999        std::time::SystemTime::now()
3000            .duration_since(std::time::UNIX_EPOCH)
3001            .unwrap_or_default()
3002            .as_secs()
3003            / 86400
3004    }
3005}
3006
3007/// Parse an ISO 8601 date string to days since epoch.
3008/// Supports `YYYY-MM-DD` and `YYYY-MM-DDTHH:MM:SSZ`.
3009pub fn parse_iso_to_days(date: &str) -> Option<u64> {
3010    let date_part = date.split('T').next()?;
3011    let parts: Vec<&str> = date_part.split('-').collect();
3012    if parts.len() != 3 {
3013        return None;
3014    }
3015    let year: u64 = parts[0].parse().ok()?;
3016    let month: u64 = parts[1].parse().ok()?;
3017    let day: u64 = parts[2].parse().ok()?;
3018    Some(ymd_to_days(year, month, day))
3019}
3020
3021/// Convert (year, month, day) to days since Unix epoch.
3022/// Inverse of the algorithm in generator.rs.
3023fn ymd_to_days(year: u64, month: u64, day: u64) -> u64 {
3024    // Algorithm from http://howardhinnant.github.io/date_algorithms.html
3025    let y = if month <= 2 { year - 1 } else { year };
3026    let m = if month <= 2 { month + 9 } else { month - 3 };
3027    let era = y / 400;
3028    let yoe = y - era * 400;
3029    let doy = (153 * m + 2) / 5 + day - 1;
3030    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
3031    let days = era * 146097 + doe;
3032    days - 719468
3033}
3034
3035#[cfg(test)]
3036mod tests;