1use std::collections::{BTreeMap, BTreeSet, HashMap};
24
25use serde::Serialize;
26
27use crate::evidence_diff::derive_status_provenance;
28use crate::project::Project;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
33#[serde(rename_all = "snake_case")]
34pub enum EdgeKind {
35 Supports,
36 Contradicts,
37 DependsOn,
38 DerivedFrom,
39 Improves,
40 Generalizes,
41 Specializes,
42 Supersedes,
43 Extends,
44 Replicates,
45 Discharges,
48}
49
50impl EdgeKind {
51 #[must_use]
56 pub fn from_link_type(link_type: &str) -> Option<Self> {
57 Some(match link_type {
58 "supports" => Self::Supports,
59 "contradicts" => Self::Contradicts,
60 "depends" => Self::DependsOn,
61 "synthesized_from" | "derived_from" => Self::DerivedFrom,
62 "improves" => Self::Improves,
63 "generalizes" => Self::Generalizes,
64 "specializes" => Self::Specializes,
65 "supersedes" => Self::Supersedes,
66 "extends" => Self::Extends,
67 "replicates" => Self::Replicates,
68 "discharges" => Self::Discharges,
69 "implies" => Self::DependsOn,
76 _ => return None,
77 })
78 }
79
80 #[must_use]
82 pub fn as_str(self) -> &'static str {
83 match self {
84 Self::Supports => "supports",
85 Self::Contradicts => "contradicts",
86 Self::DependsOn => "depends_on",
87 Self::DerivedFrom => "derived_from",
88 Self::Improves => "improves",
89 Self::Generalizes => "generalizes",
90 Self::Specializes => "specializes",
91 Self::Supersedes => "supersedes",
92 Self::Extends => "extends",
93 Self::Replicates => "replicates",
94 Self::Discharges => "discharges",
95 }
96 }
97
98 pub const ALL: [EdgeKind; 11] = [
100 Self::Supports,
101 Self::Contradicts,
102 Self::DependsOn,
103 Self::DerivedFrom,
104 Self::Improves,
105 Self::Generalizes,
106 Self::Specializes,
107 Self::Supersedes,
108 Self::Extends,
109 Self::Replicates,
110 Self::Discharges,
111 ];
112
113 #[must_use]
116 pub fn parse(s: &str) -> Option<Self> {
117 Self::ALL
118 .iter()
119 .copied()
120 .find(|k| k.as_str() == s)
121 .or_else(|| Self::from_link_type(s))
122 }
123}
124
125#[derive(Debug, Clone, Serialize)]
129pub struct Edge {
130 pub source: String,
131 pub target: String,
132 pub kind: EdgeKind,
133 pub note: String,
134 pub target_in_frontier: bool,
135}
136
137#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
149#[serde(rename_all = "snake_case")]
150pub enum FindingState {
151 Open,
152 Established,
153 Refuted,
154 Contested,
155 Fragile,
156}
157
158impl FindingState {
159 #[must_use]
161 pub fn as_str(self) -> &'static str {
162 match self {
163 Self::Open => "open",
164 Self::Established => "established",
165 Self::Refuted => "refuted",
166 Self::Contested => "contested",
167 Self::Fragile => "fragile",
168 }
169 }
170
171 #[must_use]
185 pub fn derive(flags: &crate::bundle::Flags, confidence: f64) -> Self {
186 use crate::bundle::ReviewState;
187 match flags.review_state {
188 Some(ReviewState::Rejected) => return Self::Refuted,
189 Some(ReviewState::Contested) | Some(ReviewState::NeedsRevision) => {
190 return Self::Contested;
191 }
192 None if flags.contested => return Self::Contested,
193 _ => {}
194 }
195 if flags.review_state == Some(ReviewState::Accepted) {
196 if confidence < FRAGILE_CONFIDENCE {
197 Self::Fragile
198 } else {
199 Self::Established
200 }
201 } else {
202 Self::Open
203 }
204 }
205
206 #[must_use]
209 pub fn of(flags: &crate::bundle::Flags, confidence: f64) -> Self {
210 Self::derive(flags, confidence)
211 }
212}
213
214pub const FRAGILE_CONFIDENCE: f64 = 0.6;
217
218#[derive(Debug, Clone, Serialize)]
221pub struct Node {
222 pub id: String,
223 pub label: String,
224 pub contested: bool,
225 pub gap: bool,
226 pub confidence: f64,
227 pub state: FindingState,
231}
232
233#[derive(Debug, Clone, Serialize)]
238pub struct Dominator {
239 pub node: String,
240 pub label: String,
241 #[serde(skip_serializing_if = "Option::is_none")]
243 pub state: Option<FindingState>,
244 pub weight: usize,
245 pub single_point_of_failure: bool,
246}
247
248#[derive(Debug, Clone, Copy, PartialEq, Eq)]
250pub enum BlastDirection {
251 Upstream,
253 Downstream,
255 Both,
257}
258
259#[derive(Debug, Clone, Serialize)]
261pub struct ReachNode {
262 pub id: String,
263 pub label: String,
264 #[serde(skip_serializing_if = "Option::is_none")]
265 pub state: Option<FindingState>,
266 pub distance: usize,
267}
268
269#[derive(Debug, Clone, Serialize)]
277pub struct BlastRadius {
278 pub center: String,
279 pub center_label: String,
280 #[serde(skip_serializing_if = "Option::is_none")]
281 pub center_state: Option<FindingState>,
282 pub kinds: Vec<&'static str>,
283 pub summary: BlastSummary,
284 pub single_points_of_failure: Vec<Dominator>,
285 pub upstream: Vec<ReachNode>,
286 pub downstream: Vec<ReachNode>,
287}
288
289#[derive(Debug, Clone, Serialize)]
291pub struct BlastSummary {
292 pub upstream: usize,
293 pub downstream: usize,
294 pub max_downstream_distance: usize,
295 pub single_points_of_failure: usize,
296}
297
298impl BlastRadius {
299 #[must_use]
301 pub fn to_json(&self) -> serde_json::Value {
302 let mut v = serde_json::to_value(self).unwrap_or(serde_json::Value::Null);
303 if let serde_json::Value::Object(ref mut m) = v {
304 m.insert("schema".into(), serde_json::json!("vela.blast_radius.v0.1"));
305 m.insert(
306 "claim_boundary".into(),
307 serde_json::json!({
308 "graph_is_derived": true,
309 "edges_are_declared_links": true,
310 "relations_are_candidates_not_adjudicated": true,
311 "impact_is_structural_not_a_truth_claim": true,
312 }),
313 );
314 }
315 v
316 }
317}
318
319fn coord_string(present: bool) -> String {
324 if present {
325 "1/1".to_string()
326 } else {
327 "0/1".to_string()
328 }
329}
330
331fn corner_letter(support: bool, refute: bool) -> char {
333 use crate::status_provenance::BelnapStatus;
334 match (support, refute) {
335 (true, true) => BelnapStatus::Both,
336 (true, false) => BelnapStatus::True,
337 (false, true) => BelnapStatus::False,
338 (false, false) => BelnapStatus::None,
339 }
340 .letter()
341}
342
343#[derive(Debug, Clone, Serialize)]
347pub struct GradedStatus {
348 pub support_kappa: String,
349 pub refute_kappa: String,
350 pub conflict: String,
351 pub belnap: char,
352}
353
354#[derive(Debug, Clone, Serialize)]
359pub struct GradedImpact {
360 pub id: String,
361 pub label: String,
362 pub kappa_before: String,
363 pub kappa_after: String,
364 pub delta_kappa: String,
365 pub support_killed: bool,
368}
369
370#[derive(Debug, Clone, Serialize)]
372pub struct GradedBlastSummary {
373 pub downstream_candidates: usize,
374 pub weakened: usize,
375 pub killed: usize,
376 pub semiring: &'static str,
377}
378
379#[derive(Debug, Clone, Serialize)]
387pub struct GradedBlast {
388 pub structural: BlastRadius,
389 pub center_status: GradedStatus,
390 pub impacted: Vec<GradedImpact>,
391 pub summary: GradedBlastSummary,
392}
393
394impl GradedBlast {
395 #[must_use]
398 pub fn to_json(&self) -> serde_json::Value {
399 let mut v = self.structural.to_json();
400 if let serde_json::Value::Object(ref mut m) = v {
401 m.insert(
402 "schema".into(),
403 serde_json::json!("vela.blast_radius.graded.v0.1"),
404 );
405 m.insert(
406 "center_status".into(),
407 serde_json::to_value(&self.center_status).unwrap_or_default(),
408 );
409 m.insert(
410 "graded_impact".into(),
411 serde_json::to_value(&self.impacted).unwrap_or_default(),
412 );
413 m.insert(
414 "graded_summary".into(),
415 serde_json::to_value(&self.summary).unwrap_or_default(),
416 );
417 m.insert(
418 "graded_boundary".into(),
419 serde_json::json!({
420 "support_kappa": "per-finding canonical support degree — kappa of the support polynomial (derive_status_provenance + the bilattice)",
421 "propagation": "Bottleneck semiring (max, min): a chain is as strong as its weakest premise — the kernel's licensed reading for dependency support",
422 "delta_kappa": "the drop in a dependent's support kappa when the center's support is retracted (kappa -> 0); the retraction theorem applied at the kappa level",
423 "pruning": "a structurally-reachable dependent with delta_kappa = 0 has alternative support and is NOT listed",
424 }),
425 );
426 }
427 v
428 }
429}
430
431struct PropCtx<'a> {
438 graph: &'a FrontierGraph,
439 project: &'a Project,
440 kinds: &'a [EdgeKind],
441 zeroed: &'a str,
442 own: HashMap<String, bool>,
443 memo: HashMap<String, bool>,
444}
445
446impl<'a> PropCtx<'a> {
447 fn new(
448 graph: &'a FrontierGraph,
449 project: &'a Project,
450 kinds: &'a [EdgeKind],
451 zeroed: &'a str,
452 ) -> Self {
453 PropCtx {
454 graph,
455 project,
456 kinds,
457 zeroed,
458 own: HashMap::new(),
459 memo: HashMap::new(),
460 }
461 }
462
463 fn own_support(&mut self, d: &str) -> bool {
466 if d == self.zeroed {
467 return false;
468 }
469 if let Some(v) = self.own.get(d) {
470 return *v;
471 }
472 let k = !derive_status_provenance(&self.project.events, d)
473 .support
474 .is_empty();
475 self.own.insert(d.to_string(), k);
476 k
477 }
478
479 fn prop(&mut self, d: &str, on_path: &mut BTreeSet<String>) -> bool {
483 if let Some(v) = self.memo.get(d) {
484 return *v;
485 }
486 let own = self.own_support(d);
487 if !on_path.insert(d.to_string()) {
488 return own; }
490 let premises: Vec<String> = self
491 .graph
492 .edges
493 .iter()
494 .filter(|e| e.source == d && self.kinds.contains(&e.kind))
495 .map(|e| e.target.clone())
496 .collect();
497 let mut k = own;
498 for p in premises {
499 k = k && self.prop(&p, on_path);
500 }
501 on_path.remove(d);
502 self.memo.insert(d.to_string(), k);
503 k
504 }
505}
506
507#[derive(Debug, Clone, Default)]
510pub struct FrontierGraph {
511 nodes: BTreeMap<String, Node>,
512 edges: Vec<Edge>,
513}
514
515impl FrontierGraph {
516 #[must_use]
520 pub fn from_project(project: &Project) -> Self {
521 let mut nodes = BTreeMap::new();
522 for f in &project.findings {
523 let label = f.assertion.text.chars().take(120).collect::<String>();
524 nodes.insert(
525 f.id.clone(),
526 Node {
527 id: f.id.clone(),
528 label,
529 contested: f.flags.contested,
530 gap: f.flags.gap,
531 confidence: f.confidence.score,
532 state: FindingState::derive(&f.flags, f.confidence.score),
533 },
534 );
535 }
536
537 let mut edges = Vec::new();
538 for f in &project.findings {
539 for link in &f.links {
540 let Some(kind) = EdgeKind::from_link_type(&link.link_type) else {
541 continue;
542 };
543 let bare = crate::bundle::bare_finding_id(&link.target);
553 let (target, target_in_frontier) = if nodes.contains_key(bare) {
554 (bare.to_string(), true)
555 } else {
556 (link.target.clone(), false)
557 };
558 edges.push(Edge {
559 source: f.id.clone(),
560 target,
561 kind,
562 note: link.note.clone(),
563 target_in_frontier,
564 });
565 }
566 }
567
568 Self { nodes, edges }
569 }
570
571 #[must_use]
581 pub fn from_edges<I>(raw: I) -> Self
582 where
583 I: IntoIterator<Item = (String, String, EdgeKind)>,
584 {
585 let mut nodes: BTreeMap<String, Node> = BTreeMap::new();
586 let mut edges = Vec::new();
587 for (source, target, kind) in raw {
588 for id in [&source, &target] {
589 nodes.entry(id.clone()).or_insert_with(|| Node {
590 id: id.clone(),
591 label: id.clone(),
592 contested: false,
593 gap: false,
594 confidence: 1.0,
595 state: FindingState::Open,
596 });
597 }
598 edges.push(Edge {
599 source,
600 target,
601 kind,
602 note: String::new(),
603 target_in_frontier: true,
604 });
605 }
606 Self { nodes, edges }
607 }
608
609 #[must_use]
613 pub fn in_degree_ranked(&self, kinds: &[EdgeKind]) -> Vec<(String, usize)> {
614 let mut deg: BTreeMap<String, usize> = BTreeMap::new();
615 for e in &self.edges {
616 if kinds.is_empty() || kinds.contains(&e.kind) {
617 *deg.entry(e.target.clone()).or_default() += 1;
618 }
619 }
620 let mut v: Vec<(String, usize)> = deg.into_iter().collect();
621 v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
622 v
623 }
624
625 #[must_use]
627 pub fn node_count(&self) -> usize {
628 self.nodes.len()
629 }
630
631 #[must_use]
633 pub fn edge_count(&self) -> usize {
634 self.edges.len()
635 }
636
637 #[must_use]
639 pub fn contains(&self, id: &str) -> bool {
640 self.nodes.contains_key(id)
641 }
642
643 pub fn edges_of_kind(&self, kind: EdgeKind) -> impl Iterator<Item = &Edge> {
645 self.edges.iter().filter(move |e| e.kind == kind)
646 }
647
648 #[must_use]
652 pub fn all_edges(&self) -> &[Edge] {
653 &self.edges
654 }
655
656 #[must_use]
658 pub fn node(&self, id: &str) -> Option<&Node> {
659 self.nodes.get(id)
660 }
661
662 pub fn nodes(&self) -> impl Iterator<Item = &Node> {
664 self.nodes.values()
665 }
666
667 #[must_use]
669 pub fn edge_kind_counts(&self) -> BTreeMap<&'static str, usize> {
670 let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
671 for e in &self.edges {
672 *counts.entry(e.kind.as_str()).or_default() += 1;
673 }
674 counts
675 }
676
677 #[must_use]
682 pub fn contradiction_pairs(&self) -> Vec<(String, String)> {
683 let mut pairs = BTreeSet::new();
684 for e in self.edges_of_kind(EdgeKind::Contradicts) {
685 let (a, b) = if e.source <= e.target {
686 (e.source.clone(), e.target.clone())
687 } else {
688 (e.target.clone(), e.source.clone())
689 };
690 pairs.insert((a, b));
691 }
692 pairs.into_iter().collect()
693 }
694
695 #[must_use]
699 pub fn closure_of_kind(&self, start: &str, kind: EdgeKind) -> BTreeSet<String> {
700 let mut seen = BTreeSet::new();
701 let mut stack = vec![start.to_string()];
702 while let Some(node) = stack.pop() {
703 for e in self
704 .edges
705 .iter()
706 .filter(|e| e.kind == kind && e.source == node)
707 {
708 if seen.insert(e.target.clone()) {
709 stack.push(e.target.clone());
710 }
711 }
712 }
713 seen
714 }
715
716 #[must_use]
722 pub fn explore(&self, start: &str, max_hops: usize) -> Exploration {
723 if !self.nodes.contains_key(start) {
724 return Exploration::default();
725 }
726 let mut adj: HashMap<&str, Vec<&str>> = HashMap::new();
730 for e in &self.edges {
731 adj.entry(e.source.as_str()).or_default().push(&e.target);
732 adj.entry(e.target.as_str()).or_default().push(&e.source);
733 }
734 let mut node_hops: BTreeMap<String, usize> = BTreeMap::new();
735 node_hops.insert(start.to_string(), 0);
736 let mut frontier = vec![start.to_string()];
737 for hop in 1..=max_hops {
738 let mut next = Vec::new();
739 for n in &frontier {
740 for &neighbor in adj.get(n.as_str()).into_iter().flatten() {
741 if !node_hops.contains_key(neighbor) {
742 node_hops.insert(neighbor.to_string(), hop);
743 next.push(neighbor.to_string());
744 }
745 }
746 }
747 if next.is_empty() {
748 break;
749 }
750 frontier = next;
751 }
752 let edges = self
753 .edges
754 .iter()
755 .filter(|e| node_hops.contains_key(&e.source) && node_hops.contains_key(&e.target))
756 .cloned()
757 .collect();
758 Exploration { node_hops, edges }
759 }
760
761 #[must_use]
763 pub fn label_of(&self, id: &str) -> Option<&str> {
764 self.nodes.get(id).map(|n| n.label.as_str())
765 }
766
767 fn support_reach(
771 &self,
772 start: &str,
773 kinds: &[EdgeKind],
774 remove: Option<&str>,
775 ) -> BTreeSet<String> {
776 let mut seen = BTreeSet::new();
777 let mut stack = vec![start.to_string()];
778 while let Some(node) = stack.pop() {
779 for e in &self.edges {
780 if e.source != node || !kinds.contains(&e.kind) {
781 continue;
782 }
783 if remove == Some(e.target.as_str()) {
784 continue;
785 }
786 if e.target.as_str() == start {
787 continue;
788 }
789 if seen.insert(e.target.clone()) {
790 stack.push(e.target.clone());
791 }
792 }
793 }
794 seen
795 }
796
797 #[must_use]
805 pub fn support_dominators(&self, z: &str, kinds: &[EdgeKind]) -> Vec<Dominator> {
806 let full = self.support_reach(z, kinds, None);
807 if full.is_empty() {
808 return vec![];
809 }
810 let total = full.len();
811 let mut doms: Vec<Dominator> = full
812 .iter()
813 .map(|d| {
814 let without = self.support_reach(z, kinds, Some(d));
815 let weight = full.iter().filter(|n| !without.contains(*n)).count();
816 Dominator {
817 node: d.clone(),
818 label: self.label_of(d).unwrap_or("").to_string(),
819 state: self.nodes.get(d).map(|n| n.state),
820 weight,
821 single_point_of_failure: weight == total && total >= 2,
822 }
823 })
824 .collect();
825 doms.sort_by(|a, b| b.weight.cmp(&a.weight).then(a.node.cmp(&b.node)));
826 doms
827 }
828
829 pub const DEPENDENCY_KINDS: [EdgeKind; 4] = [
834 EdgeKind::Supports,
835 EdgeKind::DependsOn,
836 EdgeKind::DerivedFrom,
837 EdgeKind::Discharges,
838 ];
839
840 pub const REQUIRED_PREMISE_KINDS: [EdgeKind; 3] = [
847 EdgeKind::DependsOn,
848 EdgeKind::DerivedFrom,
849 EdgeKind::Discharges,
850 ];
851
852 #[must_use]
858 pub fn find_node(&self, query: &str) -> Option<String> {
859 if self.nodes.contains_key(query) {
860 return Some(query.to_string());
861 }
862 if let Some(n) = self.nodes.values().find(|n| n.id.starts_with(query)) {
863 return Some(n.id.clone());
864 }
865 let q = query.to_lowercase();
866 self.nodes
867 .values()
868 .find(|n| n.label.to_lowercase().contains(&q))
869 .map(|n| n.id.clone())
870 }
871
872 fn reach_directed(
877 &self,
878 start: &str,
879 kinds: &[EdgeKind],
880 reverse: bool,
881 ) -> BTreeMap<String, usize> {
882 let mut dist: BTreeMap<String, usize> = BTreeMap::new();
883 dist.insert(start.to_string(), 0);
884 let mut frontier = vec![start.to_string()];
885 let mut hop = 0usize;
886 while !frontier.is_empty() {
887 hop += 1;
888 let mut next = Vec::new();
889 for node in &frontier {
890 for e in &self.edges {
891 if !kinds.contains(&e.kind) {
892 continue;
893 }
894 let (from, to) = if reverse {
895 (&e.target, &e.source)
896 } else {
897 (&e.source, &e.target)
898 };
899 if from != node {
900 continue;
901 }
902 if !dist.contains_key(to) {
903 dist.insert(to.clone(), hop);
904 next.push(to.clone());
905 }
906 }
907 }
908 frontier = next;
909 }
910 dist.remove(start);
911 dist
912 }
913
914 fn reach_nodes(&self, dist: &BTreeMap<String, usize>) -> Vec<ReachNode> {
917 let mut v: Vec<ReachNode> = dist
918 .iter()
919 .map(|(id, &distance)| ReachNode {
920 id: id.clone(),
921 label: self.label_of(id).unwrap_or("").to_string(),
922 state: self.nodes.get(id).map(|n| n.state),
923 distance,
924 })
925 .collect();
926 v.sort_by(|a, b| a.distance.cmp(&b.distance).then(a.id.cmp(&b.id)));
927 v
928 }
929
930 #[must_use]
935 pub fn blast_radius(
936 &self,
937 start: &str,
938 kinds: &[EdgeKind],
939 direction: BlastDirection,
940 ) -> BlastRadius {
941 let kinds: Vec<EdgeKind> = if kinds.is_empty() {
942 Self::DEPENDENCY_KINDS.to_vec()
943 } else {
944 kinds.to_vec()
945 };
946 let want_up = matches!(direction, BlastDirection::Upstream | BlastDirection::Both);
947 let want_down = matches!(direction, BlastDirection::Downstream | BlastDirection::Both);
948
949 let upstream = if want_up {
950 self.reach_nodes(&self.reach_directed(start, &kinds, false))
951 } else {
952 Vec::new()
953 };
954 let downstream = if want_down {
955 self.reach_nodes(&self.reach_directed(start, &kinds, true))
956 } else {
957 Vec::new()
958 };
959 let single_points_of_failure: Vec<Dominator> = if want_up {
960 self.support_dominators(start, &kinds)
961 .into_iter()
962 .filter(|d| d.single_point_of_failure)
963 .collect()
964 } else {
965 Vec::new()
966 };
967 let max_downstream_distance = downstream.iter().map(|n| n.distance).max().unwrap_or(0);
968 BlastRadius {
969 center: start.to_string(),
970 center_label: self.label_of(start).unwrap_or("").to_string(),
971 center_state: self.nodes.get(start).map(|n| n.state),
972 kinds: kinds.iter().map(|k| k.as_str()).collect(),
973 summary: BlastSummary {
974 upstream: upstream.len(),
975 downstream: downstream.len(),
976 max_downstream_distance,
977 single_points_of_failure: single_points_of_failure.len(),
978 },
979 single_points_of_failure,
980 upstream,
981 downstream,
982 }
983 }
984
985 #[must_use]
994 pub fn blast_radius_graded(
995 &self,
996 project: &Project,
997 start: &str,
998 kinds: &[EdgeKind],
999 direction: BlastDirection,
1000 ) -> GradedBlast {
1001 let structural = self.blast_radius(start, kinds, direction);
1002 let center_sp = derive_status_provenance(&project.events, start);
1003 let center_support = !center_sp.support.is_empty();
1004 let center_refute = !center_sp.refute.is_empty();
1005 let center_status = GradedStatus {
1006 support_kappa: coord_string(center_support),
1007 refute_kappa: coord_string(center_refute),
1008 conflict: coord_string(center_support && center_refute),
1010 belnap: corner_letter(center_support, center_refute),
1011 };
1012
1013 let mut before = PropCtx::new(self, project, &Self::REQUIRED_PREMISE_KINDS, "");
1018 let mut after = PropCtx::new(self, project, &Self::REQUIRED_PREMISE_KINDS, start);
1019 let mut scored: Vec<(bool, GradedImpact)> = Vec::new();
1021 for node in &structural.downstream {
1022 let b = before.prop(&node.id, &mut BTreeSet::new());
1023 let a = after.prop(&node.id, &mut BTreeSet::new());
1024 if b && !a {
1026 scored.push((
1027 true,
1028 GradedImpact {
1029 id: node.id.clone(),
1030 label: node.label.clone(),
1031 kappa_before: coord_string(b),
1032 kappa_after: coord_string(a),
1033 delta_kappa: coord_string(b && !a),
1034 support_killed: !a,
1035 },
1036 ));
1037 }
1038 }
1039 scored.sort_by(|x, y| y.0.cmp(&x.0).then(x.1.id.cmp(&y.1.id)));
1041 let killed = scored.iter().filter(|(_, g)| g.support_killed).count();
1042 let weakened = scored.len();
1043 let impacted: Vec<GradedImpact> = scored.into_iter().map(|(_, g)| g).collect();
1044 let summary = GradedBlastSummary {
1045 downstream_candidates: structural.downstream.len(),
1046 weakened,
1047 killed,
1048 semiring: "bottleneck",
1049 };
1050 GradedBlast {
1051 structural,
1052 center_status,
1053 impacted,
1054 summary,
1055 }
1056 }
1057
1058 #[must_use]
1063 pub fn to_json(&self) -> serde_json::Value {
1064 let nodes: Vec<&Node> = self.nodes.values().collect();
1065 serde_json::json!({
1066 "schema": "vela.frontier_graph.claims.v0.1",
1067 "summary": {
1068 "nodes": self.node_count(),
1069 "edges": self.edge_count(),
1070 "edge_kinds": self.edge_kind_counts(),
1071 "contradiction_pairs": self.contradiction_pairs().len(),
1072 },
1073 "nodes": nodes,
1074 "edges": self.edges,
1075 "claim_boundary": {
1076 "graph_is_derived": true,
1077 "edges_are_declared_links": true,
1078 "relations_are_candidates_not_adjudicated": true,
1079 },
1080 })
1081 }
1082}
1083
1084#[derive(Debug, Clone, Default)]
1088pub struct Exploration {
1089 node_hops: BTreeMap<String, usize>,
1090 pub edges: Vec<Edge>,
1091}
1092
1093impl Exploration {
1094 #[must_use]
1096 pub fn node_count(&self) -> usize {
1097 self.node_hops.len()
1098 }
1099
1100 #[must_use]
1102 pub fn max_hop(&self) -> usize {
1103 self.node_hops.values().copied().max().unwrap_or(0)
1104 }
1105
1106 #[must_use]
1108 pub fn nodes_at(&self, hop: usize) -> Vec<&str> {
1109 self.node_hops
1110 .iter()
1111 .filter(|(_, h)| **h == hop)
1112 .map(|(id, _)| id.as_str())
1113 .collect()
1114 }
1115
1116 #[must_use]
1118 pub fn edge_kind_counts(&self) -> BTreeMap<&'static str, usize> {
1119 let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
1120 for e in &self.edges {
1121 *counts.entry(e.kind.as_str()).or_default() += 1;
1122 }
1123 counts
1124 }
1125}
1126
1127#[cfg(test)]
1128mod tests {
1129 use super::*;
1130 use crate::project::assemble;
1131 use crate::project::reverse_dep_index_tests::{link_to, synth_finding};
1132
1133 fn link_typed(target: &str, link_type: &str) -> crate::bundle::Link {
1134 let mut link = link_to(target);
1135 link.link_type = link_type.into();
1136 link
1137 }
1138
1139 #[test]
1140 fn review_verdict_matrix_is_independent_of_verifier_status() {
1141 use crate::bundle::{Flags, ReviewState};
1142 let cases = [
1143 (None, false, 0.9, FindingState::Open),
1144 (
1145 Some(ReviewState::Accepted),
1146 false,
1147 0.3,
1148 FindingState::Fragile,
1149 ),
1150 (
1151 Some(ReviewState::Accepted),
1152 false,
1153 0.9,
1154 FindingState::Established,
1155 ),
1156 (
1157 Some(ReviewState::Rejected),
1158 false,
1159 0.9,
1160 FindingState::Refuted,
1161 ),
1162 (
1163 Some(ReviewState::Contested),
1164 false,
1165 0.9,
1166 FindingState::Contested,
1167 ),
1168 (
1169 Some(ReviewState::NeedsRevision),
1170 false,
1171 0.9,
1172 FindingState::Contested,
1173 ),
1174 (None, true, 0.9, FindingState::Contested),
1175 ];
1176
1177 for (review_state, contested, confidence, expected) in cases {
1178 let flags = Flags {
1179 review_state,
1180 contested,
1181 ..Default::default()
1182 };
1183 assert_eq!(FindingState::derive(&flags, confidence), expected);
1184 }
1185 }
1186
1187 #[test]
1188 fn verified_gate_does_not_establish_an_unreviewed_graph_node() {
1189 use crate::verifier_attachment::{GateStatus, claim_digest, derive_gate_status};
1190
1191 let finding = synth_finding(0, vec![]);
1192 let digest = claim_digest(&finding.assertion.text);
1193 let attachments = crate::test_support::verified_attachment_pair(&finding);
1194 assert_eq!(
1195 derive_gate_status(&digest, &attachments).status,
1196 GateStatus::Verified,
1197 "the direct verifier gate remains fully functional"
1198 );
1199
1200 let finding_id = finding.id.clone();
1201 let mut project = assemble("review-only-state", vec![], 0, 0, "test");
1202 project.findings = vec![finding];
1203 project.verifier_attachments = attachments;
1204 let graph = FrontierGraph::from_project(&project);
1205 assert_eq!(
1206 graph.node(&finding_id).expect("finding node").state,
1207 FindingState::Open,
1208 "verification must not be folded into the review-verdict state"
1209 );
1210 }
1211
1212 #[test]
1213 fn from_edges_builds_a_premise_graph_and_blasts_downstream() {
1214 let edges = vec![
1218 ("thm1".to_string(), "lemma".to_string(), EdgeKind::DependsOn),
1219 ("thm2".to_string(), "lemma".to_string(), EdgeKind::DependsOn),
1220 ("lemma".to_string(), "prim".to_string(), EdgeKind::DependsOn),
1221 ];
1222 let g = FrontierGraph::from_edges(edges);
1223 assert_eq!(g.node_count(), 4);
1224 assert_eq!(g.edge_count(), 3);
1225 let ranked = g.in_degree_ranked(&[EdgeKind::DependsOn]);
1227 assert_eq!(ranked[0], ("lemma".to_string(), 2));
1228 let blast = g.blast_radius("prim", &[EdgeKind::DependsOn], BlastDirection::Downstream);
1230 assert_eq!(
1231 blast.summary.downstream, 3,
1232 "all transitive dependents impacted"
1233 );
1234 assert_eq!(blast.summary.max_downstream_distance, 2);
1235 let ids: Vec<&str> = blast.downstream.iter().map(|n| n.id.as_str()).collect();
1236 assert!(ids.contains(&"lemma") && ids.contains(&"thm1") && ids.contains(&"thm2"));
1237 let leaf = g.blast_radius("thm1", &[EdgeKind::DependsOn], BlastDirection::Downstream);
1239 assert_eq!(leaf.summary.downstream, 0);
1240 }
1241
1242 #[test]
1243 fn every_valid_link_type_maps_to_an_edge_kind() {
1244 for lt in crate::bundle::VALID_LINK_TYPES {
1247 assert!(
1248 EdgeKind::from_link_type(lt).is_some(),
1249 "VALID_LINK_TYPES has '{lt}' with no EdgeKind mapping"
1250 );
1251 }
1252 }
1253
1254 #[test]
1255 fn maps_all_t7_link_types_to_edge_kinds() {
1256 for (s, k) in [
1257 ("supports", EdgeKind::Supports),
1258 ("contradicts", EdgeKind::Contradicts),
1259 ("depends", EdgeKind::DependsOn),
1260 ("synthesized_from", EdgeKind::DerivedFrom),
1261 ("derived_from", EdgeKind::DerivedFrom),
1262 ("improves", EdgeKind::Improves),
1263 ("generalizes", EdgeKind::Generalizes),
1264 ("specializes", EdgeKind::Specializes),
1265 ("supersedes", EdgeKind::Supersedes),
1266 ("extends", EdgeKind::Extends),
1267 ("replicates", EdgeKind::Replicates),
1268 ] {
1269 assert_eq!(EdgeKind::from_link_type(s), Some(k));
1270 }
1271 assert_eq!(EdgeKind::from_link_type("nonsense"), None);
1272 }
1273
1274 #[test]
1275 fn builds_typed_nodes_and_edges_from_project() {
1276 let base = synth_finding(0, vec![]);
1277 let a = synth_finding(1, vec![link_typed(&base.id, "improves")]);
1278 let b = synth_finding(2, vec![link_typed(&a.id, "supersedes")]);
1279 let (base_id, a_id, b_id) = (base.id.clone(), a.id.clone(), b.id.clone());
1280
1281 let mut project = assemble("fg", vec![], 0, 0, "test");
1282 project.findings = vec![base, a, b];
1283
1284 let g = FrontierGraph::from_project(&project);
1285 assert_eq!(g.node_count(), 3);
1286 assert_eq!(g.edge_count(), 2);
1287 assert!(g.contains(&base_id));
1288
1289 let improves: Vec<&Edge> = g.edges_of_kind(EdgeKind::Improves).collect();
1290 assert_eq!(improves.len(), 1);
1291 assert_eq!(improves[0].source, a_id);
1292 assert_eq!(improves[0].target, base_id);
1293 assert!(improves[0].target_in_frontier);
1294
1295 assert!(
1298 g.closure_of_kind(&a_id, EdgeKind::Improves)
1299 .contains(&base_id)
1300 );
1301 assert!(
1302 g.closure_of_kind(&b_id, EdgeKind::Supersedes)
1303 .contains(&a_id)
1304 );
1305 }
1306
1307 #[test]
1308 fn explore_walks_multiple_hops_with_distances() {
1309 let base = synth_finding(0, vec![]);
1310 let a = synth_finding(1, vec![link_typed(&base.id, "improves")]);
1311 let b = synth_finding(2, vec![link_typed(&a.id, "supersedes")]);
1312 let (base_id, a_id, b_id) = (base.id.clone(), a.id.clone(), b.id.clone());
1313 let mut project = assemble("explore", vec![], 0, 0, "test");
1314 project.findings = vec![base, a, b];
1315
1316 let g = FrontierGraph::from_project(&project);
1317 let ex = g.explore(&base_id, 2);
1318 assert_eq!(ex.node_count(), 3);
1319 assert_eq!(ex.node_hops[&base_id], 0);
1320 assert_eq!(ex.node_hops[&a_id], 1);
1321 assert_eq!(ex.node_hops[&b_id], 2);
1322 assert_eq!(ex.max_hop(), 2);
1323 assert_eq!(ex.nodes_at(1), vec![a_id.as_str()]);
1324
1325 assert_eq!(g.explore(&base_id, 1).node_count(), 2);
1327 }
1328
1329 #[test]
1330 fn support_dominators_find_the_single_point_of_failure() {
1331 let b = synth_finding(0, vec![]);
1335 let a = synth_finding(1, vec![link_typed(&b.id, "depends")]);
1336 let z = synth_finding(2, vec![link_typed(&a.id, "depends")]);
1337 let (a_id, b_id, z_id) = (a.id.clone(), b.id.clone(), z.id.clone());
1338 let mut project = assemble("dom", vec![], 0, 0, "test");
1339 project.findings = vec![b, a, z];
1340
1341 let g = FrontierGraph::from_project(&project);
1342 let doms = g.support_dominators(&z_id, &[EdgeKind::DependsOn]);
1343 let a_dom = doms.iter().find(|d| d.node == a_id).unwrap();
1345 let b_dom = doms.iter().find(|d| d.node == b_id).unwrap();
1346 assert_eq!(a_dom.weight, 2);
1347 assert!(a_dom.single_point_of_failure);
1348 assert_eq!(b_dom.weight, 1);
1349 assert!(!b_dom.single_point_of_failure);
1350 assert_eq!(doms.first().unwrap().node, a_id);
1352 }
1353
1354 #[test]
1355 fn support_dominators_empty_for_unsupported_claim() {
1356 let z = synth_finding(0, vec![]);
1357 let z_id = z.id.clone();
1358 let mut project = assemble("dom2", vec![], 0, 0, "test");
1359 project.findings = vec![z];
1360 let g = FrontierGraph::from_project(&project);
1361 assert!(
1362 g.support_dominators(&z_id, &[EdgeKind::DependsOn])
1363 .is_empty()
1364 );
1365 }
1366
1367 #[test]
1368 fn blast_radius_splits_upstream_and_downstream() {
1369 let b = synth_finding(0, vec![]);
1371 let a = synth_finding(1, vec![link_typed(&b.id, "depends")]);
1372 let z = synth_finding(2, vec![link_typed(&a.id, "depends")]);
1373 let (a_id, b_id, z_id) = (a.id.clone(), b.id.clone(), z.id.clone());
1374 let mut project = assemble("blast", vec![], 0, 0, "test");
1375 project.findings = vec![b, a, z];
1376 let g = FrontierGraph::from_project(&project);
1377
1378 let from_z = g.blast_radius(&z_id, &[EdgeKind::DependsOn], BlastDirection::Both);
1380 assert_eq!(from_z.summary.upstream, 2);
1381 assert_eq!(from_z.summary.downstream, 0);
1382 let up_ids: Vec<&str> = from_z.upstream.iter().map(|n| n.id.as_str()).collect();
1383 assert_eq!(up_ids, vec![a_id.as_str(), b_id.as_str()]); assert_eq!(from_z.upstream[0].distance, 1);
1385 assert_eq!(from_z.upstream[1].distance, 2);
1386 assert_eq!(from_z.single_points_of_failure.len(), 1);
1388 assert_eq!(from_z.single_points_of_failure[0].node, a_id);
1389
1390 let from_b = g.blast_radius(&b_id, &[EdgeKind::DependsOn], BlastDirection::Both);
1392 assert_eq!(from_b.summary.upstream, 0);
1393 assert_eq!(from_b.summary.downstream, 2);
1394 assert_eq!(from_b.summary.max_downstream_distance, 2);
1395 let down_ids: Vec<&str> = from_b.downstream.iter().map(|n| n.id.as_str()).collect();
1396 assert_eq!(down_ids, vec![a_id.as_str(), z_id.as_str()]);
1397
1398 let down_only = g.blast_radius(&b_id, &[EdgeKind::DependsOn], BlastDirection::Downstream);
1400 assert!(down_only.upstream.is_empty());
1401 assert_eq!(down_only.downstream.len(), 2);
1402 }
1403
1404 #[test]
1405 fn blast_radius_graded_prunes_unweakened_dependents() {
1406 use crate::events::{EVENT_SCHEMA, NULL_HASH, StateActor, StateEvent, StateTarget};
1407 let asserted = |idx: usize, target: &str| StateEvent {
1408 schema: EVENT_SCHEMA.to_string(),
1409 id: format!("vev_g_{idx:04}"),
1410 kind: "finding.asserted".into(),
1411 target: StateTarget {
1412 r#type: "finding".to_string(),
1413 id: target.to_string(),
1414 },
1415 actor: StateActor {
1416 id: "reviewer:test".to_string(),
1417 r#type: "human".to_string(),
1418 },
1419 timestamp: format!("2026-06-17T00:00:{:02}Z", idx % 60),
1420 reason: "graded blast test".to_string(),
1421 before_hash: NULL_HASH.to_string(),
1422 after_hash: NULL_HASH.to_string(),
1423 payload: serde_json::json!({}),
1424 caveats: vec![],
1425 signature: None,
1426 };
1427
1428 let b = synth_finding(0, vec![]);
1432 let a = synth_finding(1, vec![link_typed(&b.id, "depends")]);
1433 let z = synth_finding(2, vec![link_typed(&a.id, "depends")]);
1434 let s = synth_finding(3, vec![link_typed(&b.id, "supports")]);
1435 let (a_id, z_id, s_id, b_id) = (a.id.clone(), z.id.clone(), s.id.clone(), b.id.clone());
1436 let mut project = assemble("graded", vec![], 0, 0, "test");
1437 project.events = vec![
1438 asserted(0, &b_id),
1439 asserted(1, &a_id),
1440 asserted(2, &z_id),
1441 asserted(3, &s_id),
1442 ];
1443 project.findings = vec![b, a, z, s];
1444 let g = FrontierGraph::from_project(&project);
1445
1446 let gb = g.blast_radius_graded(&project, &b_id, &[], BlastDirection::Downstream);
1447
1448 assert_eq!(gb.center_status.belnap, 'T');
1450 assert_eq!(gb.center_status.support_kappa, "1/1");
1451
1452 let ids: Vec<&str> = gb.impacted.iter().map(|i| i.id.as_str()).collect();
1456 assert!(ids.contains(&a_id.as_str()) && ids.contains(&z_id.as_str()));
1457 assert!(
1458 !ids.contains(&s_id.as_str()),
1459 "a supports-only corroborator must be pruned from the graded impact"
1460 );
1461 assert_eq!(gb.summary.downstream_candidates, 3);
1462 assert_eq!(gb.summary.weakened, 2);
1463 assert_eq!(gb.summary.killed, 2);
1464 for imp in &gb.impacted {
1465 assert_eq!(imp.kappa_before, "1/1");
1466 assert_eq!(imp.kappa_after, "0/1");
1467 assert_eq!(imp.delta_kappa, "1/1");
1468 assert!(imp.support_killed);
1469 }
1470 }
1471
1472 #[test]
1473 fn contradiction_pairs_dedupe_symmetrically() {
1474 let x = synth_finding(0, vec![]);
1475 let y = synth_finding(1, vec![link_typed(&x.id, "contradicts")]);
1476 let mut x = x;
1478 x.links.push(link_typed(&y.id, "contradicts"));
1479 let (x_id, y_id) = (x.id.clone(), y.id.clone());
1480
1481 let mut project = assemble("fg-contra", vec![], 0, 0, "test");
1482 project.findings = vec![x, y];
1483
1484 let g = FrontierGraph::from_project(&project);
1485 let pairs = g.contradiction_pairs();
1486 assert_eq!(pairs.len(), 1);
1487 let expected = if x_id <= y_id {
1488 (x_id, y_id)
1489 } else {
1490 (y_id, x_id)
1491 };
1492 assert_eq!(pairs[0], expected);
1493 }
1494
1495 #[test]
1496 fn cross_frontier_target_is_flagged_out_of_frontier() {
1497 let f = synth_finding(
1498 0,
1499 vec![link_typed("vf_abcdef0123456789@vfr_remote", "supports")],
1500 );
1501 let mut project = assemble("fg-xf", vec![], 0, 0, "test");
1502 project.findings = vec![f];
1503
1504 let g = FrontierGraph::from_project(&project);
1505 let edge = g.edges_of_kind(EdgeKind::Supports).next().unwrap();
1506 assert!(!edge.target_in_frontier);
1507 }
1508
1509 #[test]
1510 fn cross_frontier_link_resolves_in_merged_project() {
1511 let remote = synth_finding(0, vec![]);
1515 let cross_target = format!("{}@vfr_remote", remote.id);
1516 let local = synth_finding(1, vec![link_typed(&cross_target, "depends")]);
1517 let (remote_id, local_id) = (remote.id.clone(), local.id.clone());
1518
1519 let mut project = assemble("fg-merge", vec![], 0, 0, "test");
1520 project.findings = vec![remote, local];
1521
1522 let g = FrontierGraph::from_project(&project);
1523 let edge = g.edges_of_kind(EdgeKind::DependsOn).next().unwrap();
1524 assert!(edge.target_in_frontier, "bare id present → resolves");
1525 assert_eq!(edge.target, remote_id, "target rewritten to bare id");
1526 assert!(
1528 g.closure_of_kind(&local_id, EdgeKind::DependsOn)
1529 .contains(&remote_id)
1530 );
1531 }
1532
1533 #[test]
1534 fn to_json_is_marked_derived_with_claim_boundary() {
1535 let project = assemble("fg-json", vec![], 0, 0, "test");
1536 let g = FrontierGraph::from_project(&project);
1537 let v = g.to_json();
1538 assert_eq!(v["schema"], "vela.frontier_graph.claims.v0.1");
1539 assert_eq!(v["claim_boundary"]["graph_is_derived"], true);
1540 assert_eq!(
1541 v["claim_boundary"]["relations_are_candidates_not_adjudicated"],
1542 true
1543 );
1544 }
1545}