Skip to main content

memstead_base/ops/
strict.rs

1//! The strict axis: `memstead health --strict` as the graph's referee.
2//!
3//! Strict evaluates one fixed set of health includes (the referee's set,
4//! [`STRICT_INCLUDES`]) and reads three things off the composed report:
5//!
6//! * **Entity findings**, each a health condition on one entity
7//!   ([`HEALTH_CONDITIONS`]): the three dangling conditions, an
8//!   unresolved stub, an ungranted cross-mem edge, a missing required
9//!   outgoing edge, an unsatisfied constraint, a section-format violation,
10//!   a warn-level signal. Each may be **acknowledged**: a check record on
11//!   that entity whose `finding.code` names the condition, with verdict
12//!   `failed` and a method naming the owner and the plan that closes it.
13//!   An acknowledged finding is reported and does not fail the run.
14//! * **Configuration defects**, workspace- or mem-level and never
15//!   acknowledgeable: a schema pin that disagrees with its mem, a rotted
16//!   or drifted schema package, a mount that resolves to nothing, an
17//!   unreadable anchors sidecar, a schema format defect.
18//! * **Stale acknowledgements** ([`STALE_ACKNOWLEDGEMENT_CODE`]): an
19//!   acknowledgement that still stands while its finding no longer occurs.
20//!   That is a finding in its own right, so the acknowledged set shrinks
21//!   with the repairs instead of rotting into an allowlist.
22//!
23//! The run fails on any unacknowledged finding, any configuration defect
24//! and any stale acknowledgement. Stale entities, drifted anchors and
25//! generation hints stay advisory: they are on the report, never on the
26//! verdict.
27//!
28//! The finding-code namespace: a code spelled `UPPER_SNAKE` claims to
29//! name an engine condition, so [`crate::Engine::record_check_with`]
30//! refuses one that is not in [`HEALTH_CONDITIONS`]; a checker's own
31//! vocabulary keeps any other spelling (`hidden-premise`) and never
32//! acknowledges anything.
33
34use std::collections::BTreeMap;
35
36use serde::Serialize;
37
38use crate::check::{CheckLedger, CheckRecord};
39
40/// The includes strict evaluates, whatever `--include` says.
41pub const STRICT_INCLUDES: &[&str] = &[
42    "integrity",
43    "anchors",
44    "stale",
45    "missing_required_outgoing",
46    "constraints",
47    "signals",
48];
49
50/// The code of a standing acknowledgement whose finding stopped occurring.
51pub const STALE_ACKNOWLEDGEMENT_CODE: &str = "STALE_ACKNOWLEDGEMENT";
52
53/// The condition codes an entity finding carries, and the only codes an
54/// acknowledgement may name. The dangling conditions are the same three
55/// [`crate::ops::DanglingLinkKind::ALL_CODES`] lists.
56pub const HEALTH_CONDITIONS: &[&str] = &[
57    "DANGLING_LINK_TARGET_MISSING",
58    "DANGLING_LINK_NOT_RELATED",
59    "DANGLING_RELATION_TARGET_MISSING",
60    "UNRESOLVED_STUB",
61    "CROSS_MEM_EDGE_UNGRANTED",
62    "MISSING_REQUIRED_OUTGOING",
63    "CONSTRAINT_UNSATISFIED",
64    "SECTION_FORMAT_VIOLATION",
65    "SIGNAL_WARN",
66];
67
68/// Configuration defects strict refuses on; never acknowledgeable because
69/// none of them belongs to one entity.
70pub const CONFIGURATION_CONDITIONS: &[&str] = &[
71    "SCHEMA_AUTHORING_SOURCE_MISSING",
72    "SCHEMA_AUTHORING_SOURCE_DIVERGED",
73    "SCHEMA_PIN_MISMATCH",
74    "SCHEMA_UNSTAMPED_SOURCE_ROT",
75    "MOUNT_UNBACKED",
76    "ANCHORS_SIDECAR_UNREADABLE",
77    "SCHEMA_FORMAT_DEFECT",
78];
79
80/// Whether `code` is a health condition an acknowledgement may name.
81pub fn is_health_condition(code: &str) -> bool {
82    HEALTH_CONDITIONS.contains(&code)
83}
84
85/// Whether `code` is spelled in the engine's namespace: `UPPER_SNAKE`,
86/// a letter first, three characters or more. A checker's own vocabulary
87/// takes any other spelling.
88pub fn is_engine_code_shape(code: &str) -> bool {
89    code.len() >= 3
90        && code.chars().next().is_some_and(|c| c.is_ascii_uppercase())
91        && code
92            .chars()
93            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
94}
95
96/// The check record that acknowledges a finding, as the report carries it.
97#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
98pub struct Acknowledgement {
99    /// Unix epoch seconds of the record.
100    pub ts: u64,
101    /// The caller-declared identity, when one was declared.
102    #[serde(skip_serializing_if = "Option::is_none")]
103    pub identity: Option<String>,
104    /// The recorded actor (the transport).
105    pub actor: String,
106    /// The declared role, or `unspecified`.
107    pub role: String,
108    /// The owner and the closing plan, as the checker wrote them.
109    pub method: String,
110    /// The finding message the checker attached.
111    pub message: String,
112}
113
114impl Acknowledgement {
115    fn from_record(r: &CheckRecord) -> Self {
116        Self {
117            ts: r.ts,
118            identity: r.identity.clone(),
119            actor: r.actor.clone(),
120            role: r.role.clone(),
121            method: r.method.clone().unwrap_or_default(),
122            message: r
123                .finding
124                .as_ref()
125                .map(|f| f.message.clone())
126                .unwrap_or_default(),
127        }
128    }
129}
130
131/// One entity finding on the strict axis.
132#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
133pub struct StrictFinding {
134    /// One of [`HEALTH_CONDITIONS`].
135    pub code: String,
136    /// The mem-qualified entity id.
137    pub entity: String,
138    /// The mem the entity lives in.
139    pub mem: String,
140    /// What the report said about it, verbatim from the section it came from.
141    pub detail: serde_json::Value,
142    /// Whether a standing acknowledgement covers it.
143    pub acknowledged: bool,
144    /// The acknowledgement, when one stands.
145    #[serde(skip_serializing_if = "Option::is_none")]
146    pub acknowledgement: Option<Acknowledgement>,
147}
148
149/// One configuration defect on the strict axis.
150#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
151pub struct ConfigurationDefect {
152    /// One of [`CONFIGURATION_CONDITIONS`].
153    pub code: String,
154    /// The mem it concerns, when one.
155    #[serde(skip_serializing_if = "Option::is_none")]
156    pub mem: Option<String>,
157    /// The report's own row for it.
158    pub detail: serde_json::Value,
159}
160
161/// A standing acknowledgement whose finding no longer occurs.
162#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
163pub struct StaleAcknowledgement {
164    /// Always [`STALE_ACKNOWLEDGEMENT_CODE`].
165    pub code: &'static str,
166    /// The entity the acknowledgement names.
167    pub entity: String,
168    /// The condition it acknowledged.
169    pub condition: String,
170    /// The record itself, so the reader can find and withdraw it.
171    pub acknowledgement: Acknowledgement,
172}
173
174/// The strict axis, as `health --strict` serves it under `strict`.
175#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
176pub struct StrictAxis {
177    /// The includes strict evaluated ([`STRICT_INCLUDES`]).
178    pub evaluated: Vec<&'static str>,
179    /// The condition vocabulary an acknowledgement may name.
180    pub conditions: Vec<&'static str>,
181    /// Every entity finding, acknowledged or not.
182    pub findings: Vec<StrictFinding>,
183    /// Configuration defects, never acknowledgeable.
184    pub configuration: Vec<ConfigurationDefect>,
185    /// Acknowledgements whose finding no longer occurs.
186    pub stale_acknowledgements: Vec<StaleAcknowledgement>,
187    /// Violations by code, in code order: unacknowledged findings,
188    /// configuration defects, stale acknowledgements.
189    pub violations_by_code: BTreeMap<String, usize>,
190    /// The total the exit code turns on.
191    pub violations: usize,
192    /// Acknowledged findings, for the reader.
193    pub acknowledged: usize,
194}
195
196impl StrictAxis {
197    /// One line naming every violating code with its count, for the refusal.
198    pub fn summary(&self) -> String {
199        self.violations_by_code
200            .iter()
201            .map(|(code, n)| format!("{code}: {n}"))
202            .collect::<Vec<_>>()
203            .join(", ")
204    }
205}
206
207/// The mem half of a mem-qualified entity id (`mem--slug`, where the mem
208/// may carry slashes but never a double dash).
209fn mem_of(entity_id: &str) -> &str {
210    entity_id.split_once("--").map_or(entity_id, |(m, _)| m)
211}
212
213/// Read the strict axis off a composed health report (every include in
214/// [`STRICT_INCLUDES`] already rendered into `report`) and the workspace
215/// check ledger. `mem_filter` scopes the stale-acknowledgement walk the
216/// way the report itself was scoped.
217pub fn compose_strict_axis(
218    report: &serde_json::Map<String, serde_json::Value>,
219    ledger: Option<&CheckLedger>,
220    mem_filter: Option<&str>,
221) -> StrictAxis {
222    let mut findings: Vec<StrictFinding> = Vec::new();
223    let mut configuration: Vec<ConfigurationDefect> = Vec::new();
224
225    let arr = |key: &str| -> Vec<serde_json::Value> {
226        report
227            .get(key)
228            .and_then(|v| v.as_array())
229            .cloned()
230            .unwrap_or_default()
231    };
232    let s = |v: &serde_json::Value, key: &str| -> String {
233        v.get(key)
234            .and_then(|x| x.as_str())
235            .unwrap_or_default()
236            .to_string()
237    };
238
239    // Integrity findings: the consistency codes only; the conformance
240    // axis reports beside them and stays advisory here, as it always was.
241    for f in arr("findings") {
242        let code = s(&f, "code");
243        if is_health_condition(&code) {
244            let id = s(&f, "id");
245            findings.push(StrictFinding {
246                mem: mem_of(&id).to_string(),
247                code,
248                entity: id,
249                detail: f.get("detail").cloned().unwrap_or(serde_json::Value::Null),
250                acknowledged: false,
251                acknowledgement: None,
252            });
253        } else if code == "ANCHORS_SIDECAR_UNREADABLE" {
254            configuration.push(ConfigurationDefect {
255                code,
256                mem: f
257                    .get("detail")
258                    .and_then(|d| d.get("mem"))
259                    .and_then(|m| m.as_str())
260                    .map(str::to_string),
261                detail: f,
262            });
263        }
264    }
265    for m in arr("missing_required_outgoing") {
266        let id = s(&m, "id");
267        findings.push(StrictFinding {
268            code: "MISSING_REQUIRED_OUTGOING".to_string(),
269            mem: s(&m, "mem"),
270            entity: id,
271            detail: m.get("missing").cloned().unwrap_or(serde_json::Value::Null),
272            acknowledged: false,
273            acknowledgement: None,
274        });
275    }
276    for c in arr("constraints") {
277        let id = s(&c, "id");
278        let mem = s(&c, "mem");
279        if let Some(v) = c.get("violations").and_then(|x| x.as_array())
280            && !v.is_empty()
281        {
282            findings.push(StrictFinding {
283                code: "CONSTRAINT_UNSATISFIED".to_string(),
284                mem: mem.clone(),
285                entity: id.clone(),
286                detail: serde_json::Value::Array(v.clone()),
287                acknowledged: false,
288                acknowledgement: None,
289            });
290        }
291        if let Some(fv) = c.get("format_violations").and_then(|x| x.as_array())
292            && !fv.is_empty()
293        {
294            findings.push(StrictFinding {
295                code: "SECTION_FORMAT_VIOLATION".to_string(),
296                mem,
297                entity: id,
298                detail: serde_json::Value::Array(fv.clone()),
299                acknowledged: false,
300                acknowledgement: None,
301            });
302        }
303    }
304    for d in arr("schema_format_defects") {
305        configuration.push(ConfigurationDefect {
306            code: "SCHEMA_FORMAT_DEFECT".to_string(),
307            mem: d.get("mem").and_then(|m| m.as_str()).map(str::to_string),
308            detail: d,
309        });
310    }
311    if let Some(entities) = report
312        .get("signals")
313        .and_then(|sg| sg.get("entities"))
314        .and_then(|e| e.as_array())
315    {
316        for e in entities {
317            // A row lists every signal above `none`; the entity is a
318            // warn-level finding when any of them sits at `warn`.
319            let warn: Vec<serde_json::Value> = e
320                .get("signals")
321                .and_then(|x| x.as_array())
322                .into_iter()
323                .flatten()
324                .filter(|sg| s(sg, "level") == "warn")
325                .cloned()
326                .collect();
327            if !warn.is_empty() {
328                let id = s(e, "id");
329                findings.push(StrictFinding {
330                    code: "SIGNAL_WARN".to_string(),
331                    mem: mem_of(&id).to_string(),
332                    entity: id,
333                    detail: serde_json::Value::Array(warn),
334                    acknowledged: false,
335                    acknowledgement: None,
336                });
337            }
338        }
339    }
340    if let Some(mems) = report.get("anchors").and_then(|a| a.as_object()) {
341        for (mem, row) in mems {
342            if let Some(cond) = row.get("condition").filter(|c| !c.is_null()) {
343                configuration.push(ConfigurationDefect {
344                    code: "ANCHORS_SIDECAR_UNREADABLE".to_string(),
345                    mem: Some(mem.clone()),
346                    detail: cond.clone(),
347                });
348            }
349        }
350    }
351    for w in arr("warnings") {
352        let code = s(&w, "code");
353        if CONFIGURATION_CONDITIONS.contains(&code.as_str()) {
354            configuration.push(ConfigurationDefect {
355                mem: w
356                    .get("details")
357                    .and_then(|d| d.get("mem"))
358                    .and_then(|m| m.as_str())
359                    .map(str::to_string),
360                code,
361                detail: w,
362            });
363        }
364    }
365    // One row per configuration defect: the anchors axis and the integrity
366    // findings both carry an unreadable sidecar.
367    configuration.dedup_by(|a, b| a.code == b.code && a.mem == b.mem);
368
369    // Standing acknowledgements: the newest record per (entity, condition)
370    // that carries a health-condition finding, standing while its verdict
371    // is `failed` — a later `ok` on the same condition withdraws it.
372    let mut standing: BTreeMap<(String, String), Acknowledgement> = BTreeMap::new();
373    let mut withdrawn: BTreeMap<(String, String), ()> = BTreeMap::new();
374    if let Some(ledger) = ledger {
375        for rec in ledger.all() {
376            let Some(f) = &rec.finding else { continue };
377            if !is_health_condition(&f.code) {
378                continue;
379            }
380            let key = (rec.entity.clone(), f.code.clone());
381            if rec.verdict == "failed" {
382                withdrawn.remove(&key);
383                standing.insert(key, Acknowledgement::from_record(&rec));
384            } else {
385                standing.remove(&key);
386                withdrawn.insert(key, ());
387            }
388        }
389    }
390
391    for f in &mut findings {
392        if let Some(ack) = standing.get(&(f.entity.clone(), f.code.clone())) {
393            f.acknowledged = true;
394            f.acknowledgement = Some(ack.clone());
395        }
396    }
397    let present: std::collections::BTreeSet<(String, String)> = findings
398        .iter()
399        .map(|f| (f.entity.clone(), f.code.clone()))
400        .collect();
401    let mut stale_acknowledgements: Vec<StaleAcknowledgement> = standing
402        .into_iter()
403        .filter(|(key, _)| !present.contains(key))
404        .filter(|((entity, _), _)| mem_filter.is_none_or(|m| mem_of(entity) == m))
405        .map(|((entity, condition), ack)| StaleAcknowledgement {
406            code: STALE_ACKNOWLEDGEMENT_CODE,
407            entity,
408            condition,
409            acknowledgement: ack,
410        })
411        .collect();
412    stale_acknowledgements
413        .sort_by(|a, b| (&a.entity, &a.condition).cmp(&(&b.entity, &b.condition)));
414    findings.sort_by(|a, b| (&a.entity, &a.code).cmp(&(&b.entity, &b.code)));
415    configuration.sort_by(|a, b| (&a.code, &a.mem).cmp(&(&b.code, &b.mem)));
416
417    let mut violations_by_code: BTreeMap<String, usize> = BTreeMap::new();
418    for f in findings.iter().filter(|f| !f.acknowledged) {
419        *violations_by_code.entry(f.code.clone()).or_default() += 1;
420    }
421    for c in &configuration {
422        *violations_by_code.entry(c.code.clone()).or_default() += 1;
423    }
424    if !stale_acknowledgements.is_empty() {
425        violations_by_code.insert(
426            STALE_ACKNOWLEDGEMENT_CODE.to_string(),
427            stale_acknowledgements.len(),
428        );
429    }
430    let violations = violations_by_code.values().sum();
431    let acknowledged = findings.iter().filter(|f| f.acknowledged).count();
432
433    StrictAxis {
434        evaluated: STRICT_INCLUDES.to_vec(),
435        conditions: HEALTH_CONDITIONS.to_vec(),
436        findings,
437        configuration,
438        stale_acknowledgements,
439        violations_by_code,
440        violations,
441        acknowledged,
442    }
443}
444
445#[cfg(test)]
446mod tests {
447    use super::*;
448    use crate::check::{CheckFinding, CheckRecord};
449    use tempfile::TempDir;
450
451    fn record(entity: &str, verdict: &str, code: &str, ts: u64) -> CheckRecord {
452        CheckRecord {
453            ts,
454            entity: entity.to_string(),
455            verdict: verdict.to_string(),
456            method: Some("owner: the work-down lane; plan: repairs".to_string()),
457            entity_hash: "h".to_string(),
458            actor: "cli".to_string(),
459            client: None,
460            role: "checker".to_string(),
461            identity: Some("checker-1".to_string()),
462            kind: None,
463            schema_ref: None,
464            finding: Some(CheckFinding {
465                code: code.to_string(),
466                section: None,
467                message: "known open".to_string(),
468                evidence: None,
469            }),
470            renamed_from: None,
471            carried_from: None,
472        }
473    }
474
475    fn report_with(findings: serde_json::Value) -> serde_json::Map<String, serde_json::Value> {
476        let v = serde_json::json!({
477            "findings": findings,
478            "missing_required_outgoing": [{"id": "m--needs-edge", "mem": "m", "missing": [{"cardinality": "at_least_one"}]}],
479            "constraints": [],
480            "signals": {"counts": {"warn": 1}, "entities": [{"id": "m--loud", "signals": [{"name": "attack_load", "value": 3, "level": "warn", "contributors": []}]}]},
481            "anchors": {"m": {"condition": null}},
482            "warnings": [{"code": "MOUNT_UNBACKED", "details": {"mem": "ghost", "reason": "missing_ref"}}],
483        });
484        v.as_object().cloned().unwrap()
485    }
486
487    /// The namespace rule: upper-snake claims an engine condition, any other
488    /// spelling is the checker's own.
489    #[test]
490    fn engine_code_shape_and_conditions() {
491        assert!(is_engine_code_shape("MISSING_REQUIRED_OUTGOING"));
492        assert!(is_engine_code_shape("NOT_A_CONDITION"));
493        assert!(!is_engine_code_shape("hidden-premise"));
494        assert!(!is_engine_code_shape("Ab"));
495        assert!(is_health_condition("DANGLING_LINK_NOT_RELATED"));
496        assert!(!is_health_condition("STALE_ACKNOWLEDGEMENT"));
497        for code in crate::ops::DanglingLinkKind::ALL_CODES {
498            assert!(is_health_condition(code), "{code}");
499        }
500    }
501
502    /// Unacknowledged findings, a configuration defect and a stale
503    /// acknowledgement each count; an acknowledged finding does not; a
504    /// later `ok` withdraws an acknowledgement.
505    #[test]
506    fn axis_counts_unacknowledged_configuration_and_stale() {
507        let tmp = TempDir::new().unwrap();
508        let ledger = CheckLedger::for_workspace(tmp.path());
509        // Acknowledges the missing edge (stands), acknowledges a dangling
510        // link on an entity that has since been repaired (stale), and
511        // acknowledged then withdrew a signal warning (counts again).
512        ledger
513            .record(&record(
514                "m--needs-edge",
515                "failed",
516                "MISSING_REQUIRED_OUTGOING",
517                1,
518            ))
519            .unwrap();
520        ledger
521            .record(&record(
522                "m--repaired",
523                "failed",
524                "DANGLING_LINK_TARGET_MISSING",
525                2,
526            ))
527            .unwrap();
528        ledger
529            .record(&record("m--loud", "failed", "SIGNAL_WARN", 3))
530            .unwrap();
531        ledger
532            .record(&record("m--loud", "ok", "SIGNAL_WARN", 4))
533            .unwrap();
534
535        let report = report_with(serde_json::json!([
536            {"id": "m--linker", "axis": "consistency", "code": "DANGLING_LINK_TARGET_MISSING", "detail": {"target_id": "m--nowhere"}},
537            {"id": "m--linker", "axis": "conformance", "code": "UNKNOWN_SECTION", "detail": {}},
538        ]));
539        let axis = compose_strict_axis(&report, Some(&ledger), None);
540
541        assert_eq!(axis.evaluated, STRICT_INCLUDES.to_vec());
542        assert_eq!(axis.findings.len(), 3, "{:?}", axis.findings);
543        let by_entity: BTreeMap<&str, &StrictFinding> = axis
544            .findings
545            .iter()
546            .map(|f| (f.entity.as_str(), f))
547            .collect();
548        assert!(by_entity["m--needs-edge"].acknowledged);
549        assert_eq!(
550            by_entity["m--needs-edge"]
551                .acknowledgement
552                .as_ref()
553                .unwrap()
554                .identity
555                .as_deref(),
556            Some("checker-1")
557        );
558        assert!(!by_entity["m--linker"].acknowledged);
559        assert!(!by_entity["m--loud"].acknowledged, "a later ok withdraws");
560        assert_eq!(axis.stale_acknowledgements.len(), 1);
561        assert_eq!(axis.stale_acknowledgements[0].entity, "m--repaired");
562        assert_eq!(
563            axis.stale_acknowledgements[0].condition,
564            "DANGLING_LINK_TARGET_MISSING"
565        );
566        assert_eq!(axis.configuration.len(), 1);
567        assert_eq!(axis.configuration[0].code, "MOUNT_UNBACKED");
568        assert_eq!(axis.acknowledged, 1);
569        let expect: BTreeMap<String, usize> = [
570            ("DANGLING_LINK_TARGET_MISSING", 1),
571            ("MOUNT_UNBACKED", 1),
572            ("SIGNAL_WARN", 1),
573            ("STALE_ACKNOWLEDGEMENT", 1),
574        ]
575        .into_iter()
576        .map(|(k, v)| (k.to_string(), v))
577        .collect();
578        assert_eq!(axis.violations_by_code, expect);
579        assert_eq!(axis.violations, 4);
580        assert!(axis.summary().contains("STALE_ACKNOWLEDGEMENT: 1"));
581
582        // A mem filter drops stale acknowledgements of other mems.
583        let scoped = compose_strict_axis(&report, Some(&ledger), Some("other"));
584        assert!(scoped.stale_acknowledgements.is_empty());
585    }
586
587    /// No ledger, no findings: a clean axis with zero violations.
588    #[test]
589    fn clean_axis_is_empty() {
590        let report = serde_json::json!({"findings": [], "warnings": []});
591        let axis = compose_strict_axis(report.as_object().unwrap(), None, None);
592        assert_eq!(axis.violations, 0);
593        assert!(axis.findings.is_empty());
594        assert!(axis.summary().is_empty());
595    }
596}