memstead_base/ops/health_types.rs
1//! Health-summary types and their axes.
2
3use super::*;
4
5// ---------------------------------------------------------------------------
6// Health types
7// ---------------------------------------------------------------------------
8
9/// Health check result for one entity.
10#[derive(Debug, Clone, Serialize)]
11pub struct HealthReport {
12 pub id: EntityId,
13 pub title: String,
14 pub score: f32,
15 pub issues: Vec<HealthIssue>,
16}
17
18/// Machine-readable condition discriminator for a [`HealthIssue`] —
19/// the enumeration lives here, with the issue type, and is never
20/// re-derived per projection. A projection that lists issues carries
21/// the code; the code is NEVER only a message-string prefix (a
22/// projection that drops messages would silently collapse distinct
23/// conditions — the exact misdirection `SECTION_HEADING_MISMATCH`
24/// exists to prevent).
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
26#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
27pub enum HealthIssueCode {
28 /// The required section/field is genuinely absent or empty.
29 Missing,
30 /// The section's content is present in the file but sits under a
31 /// heading that does not derive back to the section key — NOT
32 /// missing; fix the schema's heading/key pair.
33 SectionHeadingMismatch,
34 /// The entity carries a relationship whose rel-type the mem's
35 /// schema does not declare.
36 UndeclaredRelationship,
37 /// An existing edge violates the rel-type's declared
38 /// `source_types` / `target_types` shape.
39 InvalidRelShape,
40}
41
42impl HealthIssueCode {
43 /// Stable wire string — matches the serde `SCREAMING_SNAKE_CASE`
44 /// serialization, exposed for text renderers.
45 pub fn as_wire(&self) -> &'static str {
46 match self {
47 HealthIssueCode::Missing => "MISSING",
48 HealthIssueCode::SectionHeadingMismatch => "SECTION_HEADING_MISMATCH",
49 HealthIssueCode::UndeclaredRelationship => "UNDECLARED_RELATIONSHIP",
50 HealthIssueCode::InvalidRelShape => "INVALID_REL_SHAPE",
51 }
52 }
53}
54
55#[derive(Debug, Clone, Serialize)]
56pub struct HealthIssue {
57 pub field: String,
58 /// Which condition this issue reports — see [`HealthIssueCode`].
59 pub code: HealthIssueCode,
60 pub message: String,
61}
62
63/// One quarantine-roster entry on [`HealthSummary`]: the mem, the
64/// typed reason code, and the full reason message (repair command
65/// included).
66#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
67pub struct QuarantinedMemReport {
68 pub mem: String,
69 pub reason_code: String,
70 pub reason_message: String,
71}
72
73/// One per-file load failure surfaced on the health report. `file` is
74/// the path the loader reported (absolute for folder mounts after the
75/// reload-normalization pass); `error` is the loader's message, which
76/// names the remedy where one exists (the merge-conflict refusal names
77/// `memstead conflicts resolve`).
78#[derive(Debug, Clone, serde::Serialize)]
79pub struct LoadErrorReport {
80 pub file: String,
81 pub error: String,
82}
83
84/// Aggregated health report for the whole graph.
85#[derive(Debug, Clone, Serialize)]
86pub struct HealthSummary {
87 pub stale_entities: Vec<StaleEntity>,
88 /// Entities the day threshold would list as stale but whose anchors
89 /// resolve: fresh by the anchor clock, absent from `stale_entities`,
90 /// listed here so the reading names the clock that overruled the
91 /// threshold. Empty whenever no anchor spoke.
92 pub anchor_fresh: Vec<StaleEntity>,
93 pub missing_fields: Vec<HealthReport>,
94 pub orphan_count: usize,
95 pub stub_count: usize,
96 /// Typed non-fatal issues visible to every caller of `Engine::health()`.
97 /// Populated in two layers: `Engine.load_warnings` contributes drift
98 /// warnings surfaced during mem load / reload / attach
99 /// (`SuspiciousNestedPrefix`, future load-time checks); the MCP
100 /// handler additionally appends request-scoped warnings (unknown
101 /// `include` keys, clamped `limit`) on top of whatever the engine
102 /// merged. Empty on the happy path.
103 #[serde(default, skip_serializing_if = "Vec::is_empty")]
104 pub warnings: Vec<WarningHint>,
105 /// Quarantine roster: mems that failed their mem-level boot step
106 /// and serve nothing until repaired + reloaded. Always present in
107 /// `Engine::health()` output when non-empty — a boot-honesty fact,
108 /// never behind an include gate. Empty (and omitted from the wire)
109 /// on a healthy workspace, keeping default output byte-unchanged.
110 #[serde(default, skip_serializing_if = "Vec::is_empty")]
111 pub quarantined: Vec<QuarantinedMemReport>,
112 /// Per-file load failures: entity files the loader refused (git
113 /// merge-conflict markers, unreadable bytes, parser failures). The
114 /// same boot-honesty class as `quarantined` — always present when
115 /// non-empty, never behind an include gate — because each entry's
116 /// message names the remedy (e.g. the conflict refusal names
117 /// `memstead conflicts resolve`), and a remedy no surface renders
118 /// is a capability nobody finds at the moment it is needed. Empty
119 /// (and omitted from the wire) on a clean workspace.
120 #[serde(default, skip_serializing_if = "Vec::is_empty")]
121 pub load_errors: Vec<LoadErrorReport>,
122 /// Workspace-level boot diagnosis from a diagnostic-shell engine
123 /// (`{code, message}`): why the real workspace could not boot at
124 /// all. Absent on every ordinarily booted engine.
125 #[serde(default, skip_serializing_if = "Option::is_none")]
126 pub boot_diagnosis: Option<serde_json::Value>,
127 /// Real-entity count per leaf-declared type (`<schema_ref>:<type>`
128 /// keys) — the population the orphan axis exempts because those
129 /// types are terminal by construction.
130 /// Visible, never vanished. Empty (and omitted from the wire) for
131 /// schemas that declare nothing, keeping default output
132 /// byte-unchanged.
133 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
134 pub leaf_entities_by_type: std::collections::BTreeMap<String, usize>,
135 /// Dangling references: the three conditions [`DanglingLink`] carries,
136 /// which are NOT all "a body wiki-link to a missing file" — that is one
137 /// of them. See [`DanglingLinkKind`] for the other two (a body link to
138 /// a written entity the referrer does not relate to, and a
139 /// relationships row naming an absent entity) and their repairs.
140 /// Populated only when the caller
141 /// opts in via `include=["dangling_links"]`; `None` otherwise, so
142 /// absence-of-key means "not requested" and presence-of-empty-array
143 /// means "requested, zero findings". Scan is handler-driven (same
144 /// pattern as `warnings` above), so non-MCP callers of
145 /// `Engine::health()` always see `None` unless they invoke
146 /// [`health::collect_dangling_links`] directly.
147 #[serde(default, skip_serializing_if = "Option::is_none")]
148 pub dangling_links: Option<Vec<DanglingLink>>,
149 /// Integrity findings (`{ id, axis, code, detail }`) over the
150 /// conformance axis — and, under `include=["integrity"]`, the
151 /// consistency axis too. Populated only when the caller opts in
152 /// via `include=["conformance"]` / `include=["integrity"]`;
153 /// `None` otherwise (same handler-driven pattern as
154 /// `dangling_links`: absence means "not requested", an empty
155 /// array means "requested, fully integral").
156 #[serde(default, skip_serializing_if = "Option::is_none")]
157 pub findings: Option<Vec<integrity::IntegrityFinding>>,
158 /// Tag distribution (count per distinct tag, case-sensitive) over non-stub
159 /// entities. Populated only when the caller opts in via `include=["tags"]`.
160 /// Case-variant drift is surfaced via the sibling field [`tag_distribution_folded`].
161 #[serde(default, skip_serializing_if = "Option::is_none")]
162 pub tag_distribution: Option<Vec<TagDistribution>>,
163 /// Case-drift audit sidecar: entries where two or more casings of the same
164 /// canonical tag (lowercase) both appear in authored tags. Only entries with
165 /// `variants.len() > 1` are returned — the default read of `tag_distribution`
166 /// stays untouched. Populated alongside `tag_distribution`.
167 #[serde(default, skip_serializing_if = "Option::is_none")]
168 pub tag_distribution_folded: Option<Vec<FoldedTag>>,
169 /// Count of non-stub entities whose `tags` metadata is missing, empty,
170 /// or resolves to zero effective tags after splitting on `,` and trimming.
171 /// Populated alongside `tag_distribution` when `include=["tags"]`.
172 #[serde(default, skip_serializing_if = "Option::is_none")]
173 pub untagged_entities: Option<UntaggedStats>,
174}
175
176#[derive(Debug, Clone, Serialize)]
177pub struct StaleEntity {
178 pub id: EntityId,
179 pub title: String,
180 pub days_since_modified: u64,
181 /// The anchor state that produced this row when the anchor clock
182 /// spoke (`drifted` or `recheck`, or `resolves` on a fresh-by-anchor
183 /// row); `None` means the day threshold produced it. The two clocks
184 /// never both speak for one entity: an entity with an adjudicated
185 /// hash-bearing anchor reads by its anchors, the rest by the day
186 /// threshold.
187 pub anchor_state: Option<String>,
188}
189
190/// One entry in the tag distribution surface: an authored tag string, the
191/// number of non-stub entities carrying it, and the per-entity-type breakdown
192/// of those hits. Comparison is case-sensitive — `decision` and `Decision`
193/// count as distinct entries here (see `tag_distribution_folded` for the
194/// drift-aware sidecar).
195#[derive(Debug, Clone, Serialize)]
196pub struct TagDistribution {
197 pub tag: String,
198 pub count: usize,
199 pub by_entity_type: HashMap<String, usize>,
200}
201
202/// Case-drift audit entry. Surfaces when two or more casings of the same
203/// canonical (lowercased) tag appear in the authored graph — the agent-hostile
204/// bug where `decision` and `Decision` look like two healthy low-count tags
205/// in the case-sensitive primary surface.
206#[derive(Debug, Clone, Serialize)]
207pub struct FoldedTag {
208 /// Lowercase form — the canonical key.
209 pub canonical: String,
210 /// Sum of counts across every casing variant.
211 pub total: usize,
212 /// Authored casings (as-written), each with its individual count.
213 /// Sorted by `count` descending; ties broken by `tag` ascending.
214 pub variants: Vec<TagVariant>,
215}
216
217#[derive(Debug, Clone, Serialize)]
218pub struct TagVariant {
219 pub tag: String,
220 pub count: usize,
221}
222
223/// Aggregate count of non-stub entities with zero effective tags, broken
224/// down by `entity_type`. "Untagged" collapses three states: missing `tags`
225/// metadata, empty string value, and comma-only value (e.g. `","`).
226#[derive(Debug, Clone, Serialize)]
227pub struct UntaggedStats {
228 pub total: usize,
229 pub by_entity_type: HashMap<String, usize>,
230}
231
232/// One dangling-reference finding surfaced by
233/// `memstead_health include=["dangling_links"]` and projected onto the
234/// consistency axis by `include=["integrity"]`.
235///
236/// Three conditions reach this type, and [`kind`](Self::kind) says which:
237/// a body wiki-link whose target has no markdown file (the post-delete /
238/// renamed-without-rewrite / typo signal), a body wiki-link to a fully
239/// written entity that the referrer does not relate to, and a relationships
240/// row naming an entity absent from the store. Their repairs differ, so the
241/// codes differ; see [`DanglingLinkKind`].
242///
243/// The prose this replaces described only the first condition, which is how
244/// the fusion survived: the type read as if it had one subject while
245/// producing three.
246#[derive(Debug, Clone, Serialize)]
247pub struct DanglingLink {
248 /// Which of the three conditions this is, and therefore which repair
249 /// applies. Carried from the one producer, never re-derived: the split
250 /// happens where the conditions are distinguished (04/06).
251 pub kind: DanglingLinkKind,
252 pub from: EntityId,
253 /// Canonical ID the wiki-link resolves to.
254 ///
255 /// NOT necessarily a stub: it is a stub or absent for
256 /// [`DanglingLinkKind::LinkTargetMissing`] and
257 /// [`DanglingLinkKind::RelationTargetMissing`], and a real, non-stub
258 /// entity for [`DanglingLinkKind::LinkNotRelated`], where the entity is
259 /// fine and the relationship row is what is missing. The old wording said
260 /// "stub-typed in the store", which was true of one of the three
261 /// conditions this type carried.
262 pub target_id: EntityId,
263 /// Resolved mem-relative path segment of the target ID (e.g. `gone`
264 /// for `specs--gone`). This is the normalised form the engine records —
265 /// not the literal `[[…]]` characters as authored. Widening `WikiLink`
266 /// to preserve the authored form is a future-work item if agents need
267 /// grep-to-source precision.
268 pub target_path: String,
269 /// Section key the body wiki-link appears in (e.g. `"purpose"`).
270 ///
271 /// `None` for [`DanglingLinkKind::RelationTargetMissing`], whose source is
272 /// the auto-managed relationships block rather than a body section. That
273 /// absence used to be the ONLY way to tell that condition apart, which is
274 /// why `kind` exists: a reader should not have to inspect a payload for
275 /// nulls to learn which repair applies.
276 #[serde(skip_serializing_if = "Option::is_none")]
277 pub section: Option<String>,
278}
279
280/// The three conditions the one dangling-link collector distinguishes.
281///
282/// They were emitted under a single `DANGLING_LINK` code through an identical
283/// payload, so a reader could not tell which of three repairs applied, and
284/// neither could the surfaces rendering it. Two of the three were not
285/// discriminable at all. The project's error discipline is that a typed code
286/// names one condition, so each gets its own (04/06).
287///
288/// The serialised value IS the code, so a payload's `kind`, a finding's
289/// `code` and a rendered line all read the same string. A kebab-case serde
290/// name would be a second spelling of one condition, which is the shape of
291/// the defect this plan removes.
292#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
293pub enum DanglingLinkKind {
294 /// A body wiki-link whose target is absent from the store or present only
295 /// as a stub. Repair: create the target entity.
296 #[serde(rename = "DANGLING_LINK_TARGET_MISSING")]
297 LinkTargetMissing,
298 /// A body wiki-link to an existing, non-stub entity that the referrer's
299 /// relationships list does not name. The entity is fine; the relationship
300 /// row is missing. Repair: `memstead_relate` the two.
301 #[serde(rename = "DANGLING_LINK_NOT_RELATED")]
302 LinkNotRelated,
303 /// A relationships row whose target is entirely absent, neither stub nor
304 /// real. Repair: remove the row, or create the target.
305 ///
306 /// A stub target here is a legitimate forward reference (the alias
307 /// machinery auto-stubs absent targets by design) and is deliberately not
308 /// flagged.
309 #[serde(rename = "DANGLING_RELATION_TARGET_MISSING")]
310 RelationTargetMissing,
311}
312
313impl DanglingLinkKind {
314 /// The stable wire code. One code, one condition, one repair.
315 pub fn code(&self) -> &'static str {
316 match self {
317 DanglingLinkKind::LinkTargetMissing => "DANGLING_LINK_TARGET_MISSING",
318 DanglingLinkKind::LinkNotRelated => "DANGLING_LINK_NOT_RELATED",
319 DanglingLinkKind::RelationTargetMissing => "DANGLING_RELATION_TARGET_MISSING",
320 }
321 }
322
323 /// Every code this family can emit. The strict counter and any other
324 /// consumer filtering on the literal string reads THIS rather than
325 /// keeping its own copy.
326 ///
327 /// Kept honest by `all_codes_covers_every_variant`, whose exhaustive
328 /// match stops compiling when a variant is added — without it this is
329 /// just another hand-written list, and a fourth condition would fall
330 /// out of the strict gate silently, which is the failure the roster
331 /// exists to prevent.
332 pub const ALL_CODES: &'static [&'static str] = &[
333 "DANGLING_LINK_TARGET_MISSING",
334 "DANGLING_LINK_NOT_RELATED",
335 "DANGLING_RELATION_TARGET_MISSING",
336 ];
337
338 /// What to do about it, in one clause.
339 pub fn repair(&self) -> &'static str {
340 match self {
341 DanglingLinkKind::LinkTargetMissing => {
342 "create the target entity, or remove the wiki-link"
343 }
344 DanglingLinkKind::LinkNotRelated => {
345 "relate the two entities, so the body link is backed by a relationship row"
346 }
347 DanglingLinkKind::RelationTargetMissing => {
348 "remove the relationship row, or create the target entity"
349 }
350 }
351 }
352}