use std::collections::BTreeMap;
use serde::Serialize;
use crate::check::{CheckLedger, CheckRecord};
pub const STRICT_INCLUDES: &[&str] = &[
"integrity",
"anchors",
"stale",
"missing_required_outgoing",
"constraints",
"signals",
];
pub const STALE_ACKNOWLEDGEMENT_CODE: &str = "STALE_ACKNOWLEDGEMENT";
pub const HEALTH_CONDITIONS: &[&str] = &[
"DANGLING_LINK_TARGET_MISSING",
"DANGLING_LINK_NOT_RELATED",
"DANGLING_RELATION_TARGET_MISSING",
"UNRESOLVED_STUB",
"CROSS_MEM_EDGE_UNGRANTED",
"MISSING_REQUIRED_OUTGOING",
"CONSTRAINT_UNSATISFIED",
"SECTION_FORMAT_VIOLATION",
"SIGNAL_WARN",
];
pub const CONFIGURATION_CONDITIONS: &[&str] = &[
"SCHEMA_AUTHORING_SOURCE_MISSING",
"SCHEMA_AUTHORING_SOURCE_DIVERGED",
"SCHEMA_PIN_MISMATCH",
"SCHEMA_UNSTAMPED_SOURCE_ROT",
"MOUNT_UNBACKED",
"ANCHORS_SIDECAR_UNREADABLE",
"SCHEMA_FORMAT_DEFECT",
];
pub fn is_health_condition(code: &str) -> bool {
HEALTH_CONDITIONS.contains(&code)
}
pub fn is_engine_code_shape(code: &str) -> bool {
code.len() >= 3
&& code.chars().next().is_some_and(|c| c.is_ascii_uppercase())
&& code
.chars()
.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Acknowledgement {
pub ts: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub observed_at: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub identity: Option<String>,
pub actor: String,
pub role: String,
pub method: String,
pub message: String,
}
impl Acknowledgement {
fn from_record(r: &CheckRecord) -> Self {
Self {
ts: r.ts,
observed_at: r.observed_at,
identity: r.identity.clone(),
actor: r.actor.clone(),
role: r.role.clone(),
method: r.method.clone().unwrap_or_default(),
message: r
.finding
.as_ref()
.map(|f| f.message.clone())
.unwrap_or_default(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct StrictFinding {
pub code: String,
pub entity: String,
pub mem: String,
pub detail: serde_json::Value,
pub acknowledged: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub acknowledgement: Option<Acknowledgement>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ConfigurationDefect {
pub code: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub mem: Option<String>,
pub detail: serde_json::Value,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct StaleAcknowledgement {
pub code: &'static str,
pub entity: String,
pub condition: String,
pub acknowledgement: Acknowledgement,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct StrictAxis {
pub evaluated: Vec<&'static str>,
pub conditions: Vec<&'static str>,
pub findings: Vec<StrictFinding>,
pub configuration: Vec<ConfigurationDefect>,
pub stale_acknowledgements: Vec<StaleAcknowledgement>,
pub violations_by_code: BTreeMap<String, usize>,
pub violations: usize,
pub acknowledged: usize,
}
impl StrictAxis {
pub fn summary(&self) -> String {
self.violations_by_code
.iter()
.map(|(code, n)| format!("{code}: {n}"))
.collect::<Vec<_>>()
.join(", ")
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("strict mode: {violations} violation(s) ({summary})")]
pub struct StrictViolations {
pub violations: usize,
pub violations_by_code: BTreeMap<String, usize>,
pub acknowledged: usize,
pub stale_acknowledgements: usize,
summary: String,
}
impl StrictViolations {
pub fn code(&self) -> &'static str {
"HEALTH_STRICT_VIOLATIONS"
}
pub fn details(&self) -> serde_json::Value {
serde_json::json!({
"violations": self.violations,
"violations_by_code": self.violations_by_code,
"acknowledged": self.acknowledged,
"stale_acknowledgements": self.stale_acknowledgements,
})
}
pub fn from_axis_json(axis: &serde_json::Value) -> Option<Self> {
let violations = axis["violations"].as_u64().unwrap_or(0) as usize;
if violations == 0 {
return None;
}
let violations_by_code: BTreeMap<String, usize> = axis["violations_by_code"]
.as_object()
.map(|m| {
m.iter()
.map(|(k, v)| (k.clone(), v.as_u64().unwrap_or(0) as usize))
.collect()
})
.unwrap_or_default();
let summary = violations_by_code
.iter()
.map(|(code, n)| format!("{code}: {n}"))
.collect::<Vec<_>>()
.join(", ");
Some(StrictViolations {
violations,
violations_by_code,
acknowledged: axis["acknowledged"].as_u64().unwrap_or(0) as usize,
stale_acknowledgements: axis["stale_acknowledgements"]
.as_array()
.map_or(0, |a| a.len()),
summary,
})
}
}
fn mem_of(entity_id: &str) -> &str {
entity_id.split_once("--").map_or(entity_id, |(m, _)| m)
}
pub fn compose_strict_axis(
report: &serde_json::Map<String, serde_json::Value>,
ledger: Option<&CheckLedger>,
mem_filter: Option<&str>,
) -> StrictAxis {
let mut findings: Vec<StrictFinding> = Vec::new();
let mut configuration: Vec<ConfigurationDefect> = Vec::new();
let arr = |key: &str| -> Vec<serde_json::Value> {
report
.get(key)
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default()
};
let s = |v: &serde_json::Value, key: &str| -> String {
v.get(key)
.and_then(|x| x.as_str())
.unwrap_or_default()
.to_string()
};
for f in arr("findings") {
let code = s(&f, "code");
if is_health_condition(&code) {
let id = s(&f, "id");
findings.push(StrictFinding {
mem: mem_of(&id).to_string(),
code,
entity: id,
detail: f.get("detail").cloned().unwrap_or(serde_json::Value::Null),
acknowledged: false,
acknowledgement: None,
});
} else if code == "ANCHORS_SIDECAR_UNREADABLE" {
configuration.push(ConfigurationDefect {
code,
mem: f
.get("detail")
.and_then(|d| d.get("mem"))
.and_then(|m| m.as_str())
.map(str::to_string),
detail: f,
});
}
}
for m in arr("missing_required_outgoing") {
let id = s(&m, "id");
findings.push(StrictFinding {
code: "MISSING_REQUIRED_OUTGOING".to_string(),
mem: s(&m, "mem"),
entity: id,
detail: m.get("missing").cloned().unwrap_or(serde_json::Value::Null),
acknowledged: false,
acknowledgement: None,
});
}
for c in arr("constraints") {
let id = s(&c, "id");
let mem = s(&c, "mem");
if let Some(v) = c.get("violations").and_then(|x| x.as_array())
&& !v.is_empty()
{
findings.push(StrictFinding {
code: "CONSTRAINT_UNSATISFIED".to_string(),
mem: mem.clone(),
entity: id.clone(),
detail: serde_json::Value::Array(v.clone()),
acknowledged: false,
acknowledgement: None,
});
}
if let Some(fv) = c.get("format_violations").and_then(|x| x.as_array())
&& !fv.is_empty()
{
findings.push(StrictFinding {
code: "SECTION_FORMAT_VIOLATION".to_string(),
mem,
entity: id,
detail: serde_json::Value::Array(fv.clone()),
acknowledged: false,
acknowledgement: None,
});
}
}
for d in arr("schema_format_defects") {
configuration.push(ConfigurationDefect {
code: "SCHEMA_FORMAT_DEFECT".to_string(),
mem: d.get("mem").and_then(|m| m.as_str()).map(str::to_string),
detail: d,
});
}
if let Some(entities) = report
.get("signals")
.and_then(|sg| sg.get("entities"))
.and_then(|e| e.as_array())
{
for e in entities {
let warn: Vec<serde_json::Value> = e
.get("signals")
.and_then(|x| x.as_array())
.into_iter()
.flatten()
.filter(|sg| s(sg, "level") == "warn")
.cloned()
.collect();
if !warn.is_empty() {
let id = s(e, "id");
findings.push(StrictFinding {
code: "SIGNAL_WARN".to_string(),
mem: mem_of(&id).to_string(),
entity: id,
detail: serde_json::Value::Array(warn),
acknowledged: false,
acknowledgement: None,
});
}
}
}
if let Some(mems) = report.get("anchors").and_then(|a| a.as_object()) {
for (mem, row) in mems {
if let Some(cond) = row.get("condition").filter(|c| !c.is_null()) {
configuration.push(ConfigurationDefect {
code: "ANCHORS_SIDECAR_UNREADABLE".to_string(),
mem: Some(mem.clone()),
detail: cond.clone(),
});
}
}
}
for w in arr("warnings") {
let code = s(&w, "code");
if CONFIGURATION_CONDITIONS.contains(&code.as_str()) {
configuration.push(ConfigurationDefect {
mem: w
.get("details")
.and_then(|d| d.get("mem"))
.and_then(|m| m.as_str())
.map(str::to_string),
code,
detail: w,
});
}
}
configuration.dedup_by(|a, b| a.code == b.code && a.mem == b.mem);
let mut standing: BTreeMap<(String, String), Acknowledgement> = BTreeMap::new();
let mut withdrawn: BTreeMap<(String, String), ()> = BTreeMap::new();
if let Some(ledger) = ledger {
for rec in ledger.in_standing_order() {
let Some(f) = &rec.finding else { continue };
if !is_health_condition(&f.code) {
continue;
}
let key = (rec.entity.clone(), f.code.clone());
if rec.verdict == "failed" {
withdrawn.remove(&key);
standing.insert(key, Acknowledgement::from_record(&rec));
} else {
standing.remove(&key);
withdrawn.insert(key, ());
}
}
}
for f in &mut findings {
if let Some(ack) = standing.get(&(f.entity.clone(), f.code.clone())) {
f.acknowledged = true;
f.acknowledgement = Some(ack.clone());
}
}
let present: std::collections::BTreeSet<(String, String)> = findings
.iter()
.map(|f| (f.entity.clone(), f.code.clone()))
.collect();
let mut stale_acknowledgements: Vec<StaleAcknowledgement> = standing
.into_iter()
.filter(|(key, _)| !present.contains(key))
.filter(|((entity, _), _)| mem_filter.is_none_or(|m| mem_of(entity) == m))
.map(|((entity, condition), ack)| StaleAcknowledgement {
code: STALE_ACKNOWLEDGEMENT_CODE,
entity,
condition,
acknowledgement: ack,
})
.collect();
stale_acknowledgements
.sort_by(|a, b| (&a.entity, &a.condition).cmp(&(&b.entity, &b.condition)));
findings.sort_by(|a, b| (&a.entity, &a.code).cmp(&(&b.entity, &b.code)));
configuration.sort_by(|a, b| (&a.code, &a.mem).cmp(&(&b.code, &b.mem)));
let mut violations_by_code: BTreeMap<String, usize> = BTreeMap::new();
for f in findings.iter().filter(|f| !f.acknowledged) {
*violations_by_code.entry(f.code.clone()).or_default() += 1;
}
for c in &configuration {
*violations_by_code.entry(c.code.clone()).or_default() += 1;
}
if !stale_acknowledgements.is_empty() {
violations_by_code.insert(
STALE_ACKNOWLEDGEMENT_CODE.to_string(),
stale_acknowledgements.len(),
);
}
let violations = violations_by_code.values().sum();
let acknowledged = findings.iter().filter(|f| f.acknowledged).count();
StrictAxis {
evaluated: STRICT_INCLUDES.to_vec(),
conditions: HEALTH_CONDITIONS.to_vec(),
findings,
configuration,
stale_acknowledgements,
violations_by_code,
violations,
acknowledged,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::check::{CheckFinding, CheckRecord};
use tempfile::TempDir;
fn record(entity: &str, verdict: &str, code: &str, ts: u64) -> CheckRecord {
CheckRecord {
ts,
observed_at: None,
entity: entity.to_string(),
verdict: verdict.to_string(),
method: Some("owner: the work-down lane; plan: repairs".to_string()),
entity_hash: "h".to_string(),
actor: "cli".to_string(),
client: None,
role: "checker".to_string(),
identity: Some("checker-1".to_string()),
kind: None,
schema_ref: None,
finding: Some(CheckFinding {
code: code.to_string(),
section: None,
message: "known open".to_string(),
evidence: None,
}),
renamed_from: None,
carried_from: None,
checked_write: None,
}
}
fn report_with(findings: serde_json::Value) -> serde_json::Map<String, serde_json::Value> {
let v = serde_json::json!({
"findings": findings,
"missing_required_outgoing": [{"id": "m--needs-edge", "mem": "m", "missing": [{"cardinality": "at_least_one"}]}],
"constraints": [],
"signals": {"counts": {"warn": 1}, "entities": [{"id": "m--loud", "signals": [{"name": "attack_load", "value": 3, "level": "warn", "contributors": []}]}]},
"anchors": {"m": {"condition": null}},
"warnings": [{"code": "MOUNT_UNBACKED", "details": {"mem": "ghost", "reason": "missing_ref"}}],
});
v.as_object().cloned().unwrap()
}
#[test]
fn engine_code_shape_and_conditions() {
assert!(is_engine_code_shape("MISSING_REQUIRED_OUTGOING"));
assert!(is_engine_code_shape("NOT_A_CONDITION"));
assert!(!is_engine_code_shape("hidden-premise"));
assert!(!is_engine_code_shape("Ab"));
assert!(is_health_condition("DANGLING_LINK_NOT_RELATED"));
assert!(!is_health_condition("STALE_ACKNOWLEDGEMENT"));
for code in crate::ops::DanglingLinkKind::ALL_CODES {
assert!(is_health_condition(code), "{code}");
}
}
#[test]
fn axis_counts_unacknowledged_configuration_and_stale() {
let tmp = TempDir::new().unwrap();
let ledger = CheckLedger::for_workspace(tmp.path());
ledger
.record(&record(
"m--needs-edge",
"failed",
"MISSING_REQUIRED_OUTGOING",
1,
))
.unwrap();
ledger
.record(&record(
"m--repaired",
"failed",
"DANGLING_LINK_TARGET_MISSING",
2,
))
.unwrap();
ledger
.record(&record("m--loud", "failed", "SIGNAL_WARN", 3))
.unwrap();
ledger
.record(&record("m--loud", "ok", "SIGNAL_WARN", 4))
.unwrap();
let report = report_with(serde_json::json!([
{"id": "m--linker", "axis": "consistency", "code": "DANGLING_LINK_TARGET_MISSING", "detail": {"target_id": "m--nowhere"}},
{"id": "m--linker", "axis": "conformance", "code": "UNKNOWN_SECTION", "detail": {}},
]));
let axis = compose_strict_axis(&report, Some(&ledger), None);
assert_eq!(axis.evaluated, STRICT_INCLUDES.to_vec());
assert_eq!(axis.findings.len(), 3, "{:?}", axis.findings);
let by_entity: BTreeMap<&str, &StrictFinding> = axis
.findings
.iter()
.map(|f| (f.entity.as_str(), f))
.collect();
assert!(by_entity["m--needs-edge"].acknowledged);
assert_eq!(
by_entity["m--needs-edge"]
.acknowledgement
.as_ref()
.unwrap()
.identity
.as_deref(),
Some("checker-1")
);
assert!(!by_entity["m--linker"].acknowledged);
assert!(!by_entity["m--loud"].acknowledged, "a later ok withdraws");
assert_eq!(axis.stale_acknowledgements.len(), 1);
assert_eq!(axis.stale_acknowledgements[0].entity, "m--repaired");
assert_eq!(
axis.stale_acknowledgements[0].condition,
"DANGLING_LINK_TARGET_MISSING"
);
assert_eq!(axis.configuration.len(), 1);
assert_eq!(axis.configuration[0].code, "MOUNT_UNBACKED");
assert_eq!(axis.acknowledged, 1);
let expect: BTreeMap<String, usize> = [
("DANGLING_LINK_TARGET_MISSING", 1),
("MOUNT_UNBACKED", 1),
("SIGNAL_WARN", 1),
("STALE_ACKNOWLEDGEMENT", 1),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect();
assert_eq!(axis.violations_by_code, expect);
assert_eq!(axis.violations, 4);
assert!(axis.summary().contains("STALE_ACKNOWLEDGEMENT: 1"));
let scoped = compose_strict_axis(&report, Some(&ledger), Some("other"));
assert!(scoped.stale_acknowledgements.is_empty());
}
#[test]
fn withdrawal_follows_the_time_of_the_act_not_the_line() {
let tmp = TempDir::new().unwrap();
let ledger = CheckLedger::for_workspace(tmp.path());
ledger
.record(&record("m--loud", "ok", "SIGNAL_WARN", 4))
.unwrap();
ledger
.record(&record("m--loud", "failed", "SIGNAL_WARN", 3))
.unwrap();
ledger
.record(&record("m--quiet", "ok", "SIGNAL_WARN", 1))
.unwrap();
ledger
.record(&record("m--quiet", "failed", "SIGNAL_WARN", 2))
.unwrap();
let report = report_with(serde_json::json!([
{"id": "m--loud", "axis": "signals", "code": "SIGNAL_WARN", "detail": {}},
{"id": "m--quiet", "axis": "signals", "code": "SIGNAL_WARN", "detail": {}},
]));
let axis = compose_strict_axis(&report, Some(&ledger), None);
let by: BTreeMap<&str, bool> = axis
.findings
.iter()
.map(|f| (f.entity.as_str(), f.acknowledged))
.collect();
assert_eq!(by.get("m--loud"), Some(&false), "{:?}", axis.findings);
assert_eq!(by.get("m--quiet"), Some(&true), "{:?}", axis.findings);
}
#[test]
fn clean_axis_is_empty() {
let report = serde_json::json!({"findings": [], "warnings": []});
let axis = compose_strict_axis(report.as_object().unwrap(), None, None);
assert_eq!(axis.violations, 0);
assert!(axis.findings.is_empty());
assert!(axis.summary().is_empty());
}
}