1use std::collections::BTreeMap;
35
36use serde::Serialize;
37
38use crate::check::{CheckLedger, CheckRecord};
39
40pub const STRICT_INCLUDES: &[&str] = &[
42 "integrity",
43 "anchors",
44 "stale",
45 "missing_required_outgoing",
46 "constraints",
47 "signals",
48];
49
50pub const STALE_ACKNOWLEDGEMENT_CODE: &str = "STALE_ACKNOWLEDGEMENT";
52
53pub 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
68pub 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
80pub fn is_health_condition(code: &str) -> bool {
82 HEALTH_CONDITIONS.contains(&code)
83}
84
85pub 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#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
98pub struct Acknowledgement {
99 pub ts: u64,
101 #[serde(skip_serializing_if = "Option::is_none")]
103 pub identity: Option<String>,
104 pub actor: String,
106 pub role: String,
108 pub method: String,
110 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#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
133pub struct StrictFinding {
134 pub code: String,
136 pub entity: String,
138 pub mem: String,
140 pub detail: serde_json::Value,
142 pub acknowledged: bool,
144 #[serde(skip_serializing_if = "Option::is_none")]
146 pub acknowledgement: Option<Acknowledgement>,
147}
148
149#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
151pub struct ConfigurationDefect {
152 pub code: String,
154 #[serde(skip_serializing_if = "Option::is_none")]
156 pub mem: Option<String>,
157 pub detail: serde_json::Value,
159}
160
161#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
163pub struct StaleAcknowledgement {
164 pub code: &'static str,
166 pub entity: String,
168 pub condition: String,
170 pub acknowledgement: Acknowledgement,
172}
173
174#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
176pub struct StrictAxis {
177 pub evaluated: Vec<&'static str>,
179 pub conditions: Vec<&'static str>,
181 pub findings: Vec<StrictFinding>,
183 pub configuration: Vec<ConfigurationDefect>,
185 pub stale_acknowledgements: Vec<StaleAcknowledgement>,
187 pub violations_by_code: BTreeMap<String, usize>,
190 pub violations: usize,
192 pub acknowledged: usize,
194}
195
196impl StrictAxis {
197 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
207fn mem_of(entity_id: &str) -> &str {
210 entity_id.split_once("--").map_or(entity_id, |(m, _)| m)
211}
212
213pub 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 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 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 configuration.dedup_by(|a, b| a.code == b.code && a.mem == b.mem);
368
369 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 #[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 #[test]
506 fn axis_counts_unacknowledged_configuration_and_stale() {
507 let tmp = TempDir::new().unwrap();
508 let ledger = CheckLedger::for_workspace(tmp.path());
509 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 let scoped = compose_strict_axis(&report, Some(&ledger), Some("other"));
584 assert!(scoped.stale_acknowledgements.is_empty());
585 }
586
587 #[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}