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