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")]
104 pub observed_at: Option<u64>,
105 #[serde(skip_serializing_if = "Option::is_none")]
107 pub identity: Option<String>,
108 pub actor: String,
110 pub role: String,
112 pub method: String,
114 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#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
138pub struct StrictFinding {
139 pub code: String,
141 pub entity: String,
143 pub mem: String,
145 pub detail: serde_json::Value,
147 pub acknowledged: bool,
149 #[serde(skip_serializing_if = "Option::is_none")]
151 pub acknowledgement: Option<Acknowledgement>,
152}
153
154#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
156pub struct ConfigurationDefect {
157 pub code: String,
159 #[serde(skip_serializing_if = "Option::is_none")]
161 pub mem: Option<String>,
162 pub detail: serde_json::Value,
164}
165
166#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
168pub struct StaleAcknowledgement {
169 pub code: &'static str,
171 pub entity: String,
173 pub condition: String,
175 pub acknowledgement: Acknowledgement,
177}
178
179#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
181pub struct StrictAxis {
182 pub evaluated: Vec<&'static str>,
184 pub conditions: Vec<&'static str>,
186 pub findings: Vec<StrictFinding>,
188 pub configuration: Vec<ConfigurationDefect>,
190 pub stale_acknowledgements: Vec<StaleAcknowledgement>,
192 pub violations_by_code: BTreeMap<String, usize>,
195 pub violations: usize,
197 pub acknowledged: usize,
199}
200
201impl StrictAxis {
202 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#[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 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
270fn mem_of(entity_id: &str) -> &str {
273 entity_id.split_once("--").map_or(entity_id, |(m, _)| m)
274}
275
276pub 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 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 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 configuration.dedup_by(|a, b| a.code == b.code && a.mem == b.mem);
431
432 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 #[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 #[test]
571 fn axis_counts_unacknowledged_configuration_and_stale() {
572 let tmp = TempDir::new().unwrap();
573 let ledger = CheckLedger::for_workspace(tmp.path());
574 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 let scoped = compose_strict_axis(&report, Some(&ledger), Some("other"));
649 assert!(scoped.stale_acknowledgements.is_empty());
650 }
651
652 #[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 #[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}