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    /// When the check was made, as the caller stated it; absent when
102    /// nobody did.
103    #[serde(skip_serializing_if = "Option::is_none")]
104    pub observed_at: Option<u64>,
105    /// The caller-declared identity, when one was declared.
106    #[serde(skip_serializing_if = "Option::is_none")]
107    pub identity: Option<String>,
108    /// The recorded actor (the transport).
109    pub actor: String,
110    /// The declared role, or `unspecified`.
111    pub role: String,
112    /// The owner and the closing plan, as the checker wrote them.
113    pub method: String,
114    /// The finding message the checker attached.
115    pub message: String,
116}
117
118impl Acknowledgement {
119    fn from_record(r: &CheckRecord) -> Self {
120        Self {
121            ts: r.ts,
122            observed_at: r.observed_at,
123            identity: r.identity.clone(),
124            actor: r.actor.clone(),
125            role: r.role.clone(),
126            method: r.method.clone().unwrap_or_default(),
127            message: r
128                .finding
129                .as_ref()
130                .map(|f| f.message.clone())
131                .unwrap_or_default(),
132        }
133    }
134}
135
136/// One entity finding on the strict axis.
137#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
138pub struct StrictFinding {
139    /// One of [`HEALTH_CONDITIONS`].
140    pub code: String,
141    /// The mem-qualified entity id.
142    pub entity: String,
143    /// The mem the entity lives in.
144    pub mem: String,
145    /// What the report said about it, verbatim from the section it came from.
146    pub detail: serde_json::Value,
147    /// Whether a standing acknowledgement covers it.
148    pub acknowledged: bool,
149    /// The acknowledgement, when one stands.
150    #[serde(skip_serializing_if = "Option::is_none")]
151    pub acknowledgement: Option<Acknowledgement>,
152}
153
154/// One configuration defect on the strict axis.
155#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
156pub struct ConfigurationDefect {
157    /// One of [`CONFIGURATION_CONDITIONS`].
158    pub code: String,
159    /// The mem it concerns, when one.
160    #[serde(skip_serializing_if = "Option::is_none")]
161    pub mem: Option<String>,
162    /// The report's own row for it.
163    pub detail: serde_json::Value,
164}
165
166/// A standing acknowledgement whose finding no longer occurs.
167#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
168pub struct StaleAcknowledgement {
169    /// Always [`STALE_ACKNOWLEDGEMENT_CODE`].
170    pub code: &'static str,
171    /// The entity the acknowledgement names.
172    pub entity: String,
173    /// The condition it acknowledged.
174    pub condition: String,
175    /// The record itself, so the reader can find and withdraw it.
176    pub acknowledgement: Acknowledgement,
177}
178
179/// The strict axis, as `health --strict` serves it under `strict`.
180#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
181pub struct StrictAxis {
182    /// The includes strict evaluated ([`STRICT_INCLUDES`]).
183    pub evaluated: Vec<&'static str>,
184    /// The condition vocabulary an acknowledgement may name.
185    pub conditions: Vec<&'static str>,
186    /// Every entity finding, acknowledged or not.
187    pub findings: Vec<StrictFinding>,
188    /// Configuration defects, never acknowledgeable.
189    pub configuration: Vec<ConfigurationDefect>,
190    /// Acknowledgements whose finding no longer occurs.
191    pub stale_acknowledgements: Vec<StaleAcknowledgement>,
192    /// Violations by code, in code order: unacknowledged findings,
193    /// configuration defects, stale acknowledgements.
194    pub violations_by_code: BTreeMap<String, usize>,
195    /// The total the exit code turns on.
196    pub violations: usize,
197    /// Acknowledged findings, for the reader.
198    pub acknowledged: usize,
199}
200
201impl StrictAxis {
202    /// One line naming every violating code with its count, for the refusal.
203    pub fn summary(&self) -> String {
204        self.violations_by_code
205            .iter()
206            .map(|(code, n)| format!("{code}: {n}"))
207            .collect::<Vec<_>>()
208            .join(", ")
209    }
210}
211
212/// A strict health run that found violations: the refusal a caller gating
213/// on `--strict` raises, after the report.
214#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
215#[error("strict mode: {violations} violation(s) ({summary})")]
216pub struct StrictViolations {
217    pub violations: usize,
218    pub violations_by_code: BTreeMap<String, usize>,
219    pub acknowledged: usize,
220    pub stale_acknowledgements: usize,
221    summary: String,
222}
223
224impl StrictViolations {
225    pub fn code(&self) -> &'static str {
226        "HEALTH_STRICT_VIOLATIONS"
227    }
228
229    pub fn details(&self) -> serde_json::Value {
230        serde_json::json!({
231            "violations": self.violations,
232            "violations_by_code": self.violations_by_code,
233            "acknowledged": self.acknowledged,
234            "stale_acknowledgements": self.stale_acknowledgements,
235        })
236    }
237
238    /// The refusal for a strict axis as the health report serves it
239    /// (`strict` in the report JSON), when it counts any violation.
240    pub fn from_axis_json(axis: &serde_json::Value) -> Option<Self> {
241        let violations = axis["violations"].as_u64().unwrap_or(0) as usize;
242        if violations == 0 {
243            return None;
244        }
245        let violations_by_code: BTreeMap<String, usize> = axis["violations_by_code"]
246            .as_object()
247            .map(|m| {
248                m.iter()
249                    .map(|(k, v)| (k.clone(), v.as_u64().unwrap_or(0) as usize))
250                    .collect()
251            })
252            .unwrap_or_default();
253        let summary = violations_by_code
254            .iter()
255            .map(|(code, n)| format!("{code}: {n}"))
256            .collect::<Vec<_>>()
257            .join(", ");
258        Some(StrictViolations {
259            violations,
260            violations_by_code,
261            acknowledged: axis["acknowledged"].as_u64().unwrap_or(0) as usize,
262            stale_acknowledgements: axis["stale_acknowledgements"]
263                .as_array()
264                .map_or(0, |a| a.len()),
265            summary,
266        })
267    }
268}
269
270/// The mem half of a mem-qualified entity id (`mem--slug`, where the mem
271/// may carry slashes but never a double dash).
272fn mem_of(entity_id: &str) -> &str {
273    entity_id.split_once("--").map_or(entity_id, |(m, _)| m)
274}
275
276/// Read the strict axis off a composed health report (every include in
277/// [`STRICT_INCLUDES`] already rendered into `report`) and the workspace
278/// check ledger. `mem_filter` scopes the stale-acknowledgement walk the
279/// way the report itself was scoped.
280pub fn compose_strict_axis(
281    report: &serde_json::Map<String, serde_json::Value>,
282    ledger: Option<&CheckLedger>,
283    mem_filter: Option<&str>,
284) -> StrictAxis {
285    let mut findings: Vec<StrictFinding> = Vec::new();
286    let mut configuration: Vec<ConfigurationDefect> = Vec::new();
287
288    let arr = |key: &str| -> Vec<serde_json::Value> {
289        report
290            .get(key)
291            .and_then(|v| v.as_array())
292            .cloned()
293            .unwrap_or_default()
294    };
295    let s = |v: &serde_json::Value, key: &str| -> String {
296        v.get(key)
297            .and_then(|x| x.as_str())
298            .unwrap_or_default()
299            .to_string()
300    };
301
302    // Integrity findings: the consistency codes only; the conformance
303    // axis reports beside them and stays advisory here, as it always was.
304    for f in arr("findings") {
305        let code = s(&f, "code");
306        if is_health_condition(&code) {
307            let id = s(&f, "id");
308            findings.push(StrictFinding {
309                mem: mem_of(&id).to_string(),
310                code,
311                entity: id,
312                detail: f.get("detail").cloned().unwrap_or(serde_json::Value::Null),
313                acknowledged: false,
314                acknowledgement: None,
315            });
316        } else if code == "ANCHORS_SIDECAR_UNREADABLE" {
317            configuration.push(ConfigurationDefect {
318                code,
319                mem: f
320                    .get("detail")
321                    .and_then(|d| d.get("mem"))
322                    .and_then(|m| m.as_str())
323                    .map(str::to_string),
324                detail: f,
325            });
326        }
327    }
328    for m in arr("missing_required_outgoing") {
329        let id = s(&m, "id");
330        findings.push(StrictFinding {
331            code: "MISSING_REQUIRED_OUTGOING".to_string(),
332            mem: s(&m, "mem"),
333            entity: id,
334            detail: m.get("missing").cloned().unwrap_or(serde_json::Value::Null),
335            acknowledged: false,
336            acknowledgement: None,
337        });
338    }
339    for c in arr("constraints") {
340        let id = s(&c, "id");
341        let mem = s(&c, "mem");
342        if let Some(v) = c.get("violations").and_then(|x| x.as_array())
343            && !v.is_empty()
344        {
345            findings.push(StrictFinding {
346                code: "CONSTRAINT_UNSATISFIED".to_string(),
347                mem: mem.clone(),
348                entity: id.clone(),
349                detail: serde_json::Value::Array(v.clone()),
350                acknowledged: false,
351                acknowledgement: None,
352            });
353        }
354        if let Some(fv) = c.get("format_violations").and_then(|x| x.as_array())
355            && !fv.is_empty()
356        {
357            findings.push(StrictFinding {
358                code: "SECTION_FORMAT_VIOLATION".to_string(),
359                mem,
360                entity: id,
361                detail: serde_json::Value::Array(fv.clone()),
362                acknowledged: false,
363                acknowledgement: None,
364            });
365        }
366    }
367    for d in arr("schema_format_defects") {
368        configuration.push(ConfigurationDefect {
369            code: "SCHEMA_FORMAT_DEFECT".to_string(),
370            mem: d.get("mem").and_then(|m| m.as_str()).map(str::to_string),
371            detail: d,
372        });
373    }
374    if let Some(entities) = report
375        .get("signals")
376        .and_then(|sg| sg.get("entities"))
377        .and_then(|e| e.as_array())
378    {
379        for e in entities {
380            // A row lists every signal above `none`; the entity is a
381            // warn-level finding when any of them sits at `warn`.
382            let warn: Vec<serde_json::Value> = e
383                .get("signals")
384                .and_then(|x| x.as_array())
385                .into_iter()
386                .flatten()
387                .filter(|sg| s(sg, "level") == "warn")
388                .cloned()
389                .collect();
390            if !warn.is_empty() {
391                let id = s(e, "id");
392                findings.push(StrictFinding {
393                    code: "SIGNAL_WARN".to_string(),
394                    mem: mem_of(&id).to_string(),
395                    entity: id,
396                    detail: serde_json::Value::Array(warn),
397                    acknowledged: false,
398                    acknowledgement: None,
399                });
400            }
401        }
402    }
403    if let Some(mems) = report.get("anchors").and_then(|a| a.as_object()) {
404        for (mem, row) in mems {
405            if let Some(cond) = row.get("condition").filter(|c| !c.is_null()) {
406                configuration.push(ConfigurationDefect {
407                    code: "ANCHORS_SIDECAR_UNREADABLE".to_string(),
408                    mem: Some(mem.clone()),
409                    detail: cond.clone(),
410                });
411            }
412        }
413    }
414    for w in arr("warnings") {
415        let code = s(&w, "code");
416        if CONFIGURATION_CONDITIONS.contains(&code.as_str()) {
417            configuration.push(ConfigurationDefect {
418                mem: w
419                    .get("details")
420                    .and_then(|d| d.get("mem"))
421                    .and_then(|m| m.as_str())
422                    .map(str::to_string),
423                code,
424                detail: w,
425            });
426        }
427    }
428    // One row per configuration defect: the anchors axis and the integrity
429    // findings both carry an unreadable sidecar.
430    configuration.dedup_by(|a, b| a.code == b.code && a.mem == b.mem);
431
432    // Standing acknowledgements: the newest record per (entity, condition)
433    // that carries a health-condition finding, standing while its verdict
434    // is `failed` — a later `ok` on the same condition withdraws it.
435    let mut standing: BTreeMap<(String, String), Acknowledgement> = BTreeMap::new();
436    let mut withdrawn: BTreeMap<(String, String), ()> = BTreeMap::new();
437    if let Some(ledger) = ledger {
438        for rec in ledger.in_standing_order() {
439            let Some(f) = &rec.finding else { continue };
440            if !is_health_condition(&f.code) {
441                continue;
442            }
443            let key = (rec.entity.clone(), f.code.clone());
444            if rec.verdict == "failed" {
445                withdrawn.remove(&key);
446                standing.insert(key, Acknowledgement::from_record(&rec));
447            } else {
448                standing.remove(&key);
449                withdrawn.insert(key, ());
450            }
451        }
452    }
453
454    for f in &mut findings {
455        if let Some(ack) = standing.get(&(f.entity.clone(), f.code.clone())) {
456            f.acknowledged = true;
457            f.acknowledgement = Some(ack.clone());
458        }
459    }
460    let present: std::collections::BTreeSet<(String, String)> = findings
461        .iter()
462        .map(|f| (f.entity.clone(), f.code.clone()))
463        .collect();
464    let mut stale_acknowledgements: Vec<StaleAcknowledgement> = standing
465        .into_iter()
466        .filter(|(key, _)| !present.contains(key))
467        .filter(|((entity, _), _)| mem_filter.is_none_or(|m| mem_of(entity) == m))
468        .map(|((entity, condition), ack)| StaleAcknowledgement {
469            code: STALE_ACKNOWLEDGEMENT_CODE,
470            entity,
471            condition,
472            acknowledgement: ack,
473        })
474        .collect();
475    stale_acknowledgements
476        .sort_by(|a, b| (&a.entity, &a.condition).cmp(&(&b.entity, &b.condition)));
477    findings.sort_by(|a, b| (&a.entity, &a.code).cmp(&(&b.entity, &b.code)));
478    configuration.sort_by(|a, b| (&a.code, &a.mem).cmp(&(&b.code, &b.mem)));
479
480    let mut violations_by_code: BTreeMap<String, usize> = BTreeMap::new();
481    for f in findings.iter().filter(|f| !f.acknowledged) {
482        *violations_by_code.entry(f.code.clone()).or_default() += 1;
483    }
484    for c in &configuration {
485        *violations_by_code.entry(c.code.clone()).or_default() += 1;
486    }
487    if !stale_acknowledgements.is_empty() {
488        violations_by_code.insert(
489            STALE_ACKNOWLEDGEMENT_CODE.to_string(),
490            stale_acknowledgements.len(),
491        );
492    }
493    let violations = violations_by_code.values().sum();
494    let acknowledged = findings.iter().filter(|f| f.acknowledged).count();
495
496    StrictAxis {
497        evaluated: STRICT_INCLUDES.to_vec(),
498        conditions: HEALTH_CONDITIONS.to_vec(),
499        findings,
500        configuration,
501        stale_acknowledgements,
502        violations_by_code,
503        violations,
504        acknowledged,
505    }
506}
507
508#[cfg(test)]
509mod tests {
510    use super::*;
511    use crate::check::{CheckFinding, CheckRecord};
512    use tempfile::TempDir;
513
514    fn record(entity: &str, verdict: &str, code: &str, ts: u64) -> CheckRecord {
515        CheckRecord {
516            ts,
517            observed_at: None,
518            entity: entity.to_string(),
519            verdict: verdict.to_string(),
520            method: Some("owner: the work-down lane; plan: repairs".to_string()),
521            entity_hash: "h".to_string(),
522            actor: "cli".to_string(),
523            client: None,
524            role: "checker".to_string(),
525            identity: Some("checker-1".to_string()),
526            kind: None,
527            schema_ref: None,
528            finding: Some(CheckFinding {
529                code: code.to_string(),
530                section: None,
531                message: "known open".to_string(),
532                evidence: None,
533            }),
534            renamed_from: None,
535            carried_from: None,
536            checked_write: None,
537        }
538    }
539
540    fn report_with(findings: serde_json::Value) -> serde_json::Map<String, serde_json::Value> {
541        let v = serde_json::json!({
542            "findings": findings,
543            "missing_required_outgoing": [{"id": "m--needs-edge", "mem": "m", "missing": [{"cardinality": "at_least_one"}]}],
544            "constraints": [],
545            "signals": {"counts": {"warn": 1}, "entities": [{"id": "m--loud", "signals": [{"name": "attack_load", "value": 3, "level": "warn", "contributors": []}]}]},
546            "anchors": {"m": {"condition": null}},
547            "warnings": [{"code": "MOUNT_UNBACKED", "details": {"mem": "ghost", "reason": "missing_ref"}}],
548        });
549        v.as_object().cloned().unwrap()
550    }
551
552    /// The namespace rule: upper-snake claims an engine condition, any other
553    /// spelling is the checker's own.
554    #[test]
555    fn engine_code_shape_and_conditions() {
556        assert!(is_engine_code_shape("MISSING_REQUIRED_OUTGOING"));
557        assert!(is_engine_code_shape("NOT_A_CONDITION"));
558        assert!(!is_engine_code_shape("hidden-premise"));
559        assert!(!is_engine_code_shape("Ab"));
560        assert!(is_health_condition("DANGLING_LINK_NOT_RELATED"));
561        assert!(!is_health_condition("STALE_ACKNOWLEDGEMENT"));
562        for code in crate::ops::DanglingLinkKind::ALL_CODES {
563            assert!(is_health_condition(code), "{code}");
564        }
565    }
566
567    /// Unacknowledged findings, a configuration defect and a stale
568    /// acknowledgement each count; an acknowledged finding does not; a
569    /// later `ok` withdraws an acknowledgement.
570    #[test]
571    fn axis_counts_unacknowledged_configuration_and_stale() {
572        let tmp = TempDir::new().unwrap();
573        let ledger = CheckLedger::for_workspace(tmp.path());
574        // Acknowledges the missing edge (stands), acknowledges a dangling
575        // link on an entity that has since been repaired (stale), and
576        // acknowledged then withdrew a signal warning (counts again).
577        ledger
578            .record(&record(
579                "m--needs-edge",
580                "failed",
581                "MISSING_REQUIRED_OUTGOING",
582                1,
583            ))
584            .unwrap();
585        ledger
586            .record(&record(
587                "m--repaired",
588                "failed",
589                "DANGLING_LINK_TARGET_MISSING",
590                2,
591            ))
592            .unwrap();
593        ledger
594            .record(&record("m--loud", "failed", "SIGNAL_WARN", 3))
595            .unwrap();
596        ledger
597            .record(&record("m--loud", "ok", "SIGNAL_WARN", 4))
598            .unwrap();
599
600        let report = report_with(serde_json::json!([
601            {"id": "m--linker", "axis": "consistency", "code": "DANGLING_LINK_TARGET_MISSING", "detail": {"target_id": "m--nowhere"}},
602            {"id": "m--linker", "axis": "conformance", "code": "UNKNOWN_SECTION", "detail": {}},
603        ]));
604        let axis = compose_strict_axis(&report, Some(&ledger), None);
605
606        assert_eq!(axis.evaluated, STRICT_INCLUDES.to_vec());
607        assert_eq!(axis.findings.len(), 3, "{:?}", axis.findings);
608        let by_entity: BTreeMap<&str, &StrictFinding> = axis
609            .findings
610            .iter()
611            .map(|f| (f.entity.as_str(), f))
612            .collect();
613        assert!(by_entity["m--needs-edge"].acknowledged);
614        assert_eq!(
615            by_entity["m--needs-edge"]
616                .acknowledgement
617                .as_ref()
618                .unwrap()
619                .identity
620                .as_deref(),
621            Some("checker-1")
622        );
623        assert!(!by_entity["m--linker"].acknowledged);
624        assert!(!by_entity["m--loud"].acknowledged, "a later ok withdraws");
625        assert_eq!(axis.stale_acknowledgements.len(), 1);
626        assert_eq!(axis.stale_acknowledgements[0].entity, "m--repaired");
627        assert_eq!(
628            axis.stale_acknowledgements[0].condition,
629            "DANGLING_LINK_TARGET_MISSING"
630        );
631        assert_eq!(axis.configuration.len(), 1);
632        assert_eq!(axis.configuration[0].code, "MOUNT_UNBACKED");
633        assert_eq!(axis.acknowledged, 1);
634        let expect: BTreeMap<String, usize> = [
635            ("DANGLING_LINK_TARGET_MISSING", 1),
636            ("MOUNT_UNBACKED", 1),
637            ("SIGNAL_WARN", 1),
638            ("STALE_ACKNOWLEDGEMENT", 1),
639        ]
640        .into_iter()
641        .map(|(k, v)| (k.to_string(), v))
642        .collect();
643        assert_eq!(axis.violations_by_code, expect);
644        assert_eq!(axis.violations, 4);
645        assert!(axis.summary().contains("STALE_ACKNOWLEDGEMENT: 1"));
646
647        // A mem filter drops stale acknowledgements of other mems.
648        let scoped = compose_strict_axis(&report, Some(&ledger), Some("other"));
649        assert!(scoped.stale_acknowledgements.is_empty());
650    }
651
652    /// "A later ok withdraws" means the later act, not the later line:
653    /// an ok made after the acknowledgement but arriving before it (a
654    /// transport merge) still withdraws it, and an ok made before it does
655    /// not.
656    #[test]
657    fn withdrawal_follows_the_time_of_the_act_not_the_line() {
658        let tmp = TempDir::new().unwrap();
659        let ledger = CheckLedger::for_workspace(tmp.path());
660        ledger
661            .record(&record("m--loud", "ok", "SIGNAL_WARN", 4))
662            .unwrap();
663        ledger
664            .record(&record("m--loud", "failed", "SIGNAL_WARN", 3))
665            .unwrap();
666        ledger
667            .record(&record("m--quiet", "ok", "SIGNAL_WARN", 1))
668            .unwrap();
669        ledger
670            .record(&record("m--quiet", "failed", "SIGNAL_WARN", 2))
671            .unwrap();
672        let report = report_with(serde_json::json!([
673            {"id": "m--loud", "axis": "signals", "code": "SIGNAL_WARN", "detail": {}},
674            {"id": "m--quiet", "axis": "signals", "code": "SIGNAL_WARN", "detail": {}},
675        ]));
676        let axis = compose_strict_axis(&report, Some(&ledger), None);
677        let by: BTreeMap<&str, bool> = axis
678            .findings
679            .iter()
680            .map(|f| (f.entity.as_str(), f.acknowledged))
681            .collect();
682        assert_eq!(by.get("m--loud"), Some(&false), "{:?}", axis.findings);
683        assert_eq!(by.get("m--quiet"), Some(&true), "{:?}", axis.findings);
684    }
685
686    /// No ledger, no findings: a clean axis with zero violations.
687    #[test]
688    fn clean_axis_is_empty() {
689        let report = serde_json::json!({"findings": [], "warnings": []});
690        let axis = compose_strict_axis(report.as_object().unwrap(), None, None);
691        assert_eq!(axis.violations, 0);
692        assert!(axis.findings.is_empty());
693        assert!(axis.summary().is_empty());
694    }
695}