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]
189 pub fn derive(
190 flags: &crate::bundle::Flags,
191 confidence: f64,
192 gate: Option<crate::verifier_attachment::GateStatus>,
193 ) -> Self {
194 use crate::bundle::ReviewState;
195 use crate::verifier_attachment::GateStatus;
196 if gate == Some(GateStatus::Refuted) {
197 return Self::Refuted;
198 }
199 match flags.review_state {
200 Some(ReviewState::Rejected) => return Self::Refuted,
201 Some(ReviewState::Contested) | Some(ReviewState::NeedsRevision) => {
202 return Self::Contested;
203 }
204 None if flags.contested => return Self::Contested,
205 _ => {}
206 }
207 if gate == Some(GateStatus::Verified) {
210 return Self::Established;
211 }
212 if flags.review_state == Some(ReviewState::Accepted) {
215 if confidence < FRAGILE_CONFIDENCE {
216 Self::Fragile
217 } else {
218 Self::Established
219 }
220 } else {
221 Self::Open
222 }
223 }
224
225 #[must_use]
228 pub fn of(flags: &crate::bundle::Flags, confidence: f64) -> Self {
229 Self::derive(flags, confidence, None)
230 }
231}
232
233pub const FRAGILE_CONFIDENCE: f64 = 0.6;
238
239#[derive(Debug, Clone, Serialize)]
242pub struct Node {
243 pub id: String,
244 pub label: String,
245 pub contested: bool,
246 pub gap: bool,
247 pub confidence: f64,
248 pub state: FindingState,
252}
253
254#[derive(Debug, Clone, Serialize)]
259pub struct Dominator {
260 pub node: String,
261 pub label: String,
262 #[serde(skip_serializing_if = "Option::is_none")]
264 pub state: Option<FindingState>,
265 pub weight: usize,
266 pub single_point_of_failure: bool,
267}
268
269#[derive(Debug, Clone, Copy, PartialEq, Eq)]
271pub enum BlastDirection {
272 Upstream,
274 Downstream,
276 Both,
278}
279
280#[derive(Debug, Clone, Serialize)]
282pub struct ReachNode {
283 pub id: String,
284 pub label: String,
285 #[serde(skip_serializing_if = "Option::is_none")]
286 pub state: Option<FindingState>,
287 pub distance: usize,
288}
289
290#[derive(Debug, Clone, Serialize)]
298pub struct BlastRadius {
299 pub center: String,
300 pub center_label: String,
301 #[serde(skip_serializing_if = "Option::is_none")]
302 pub center_state: Option<FindingState>,
303 pub kinds: Vec<&'static str>,
304 pub summary: BlastSummary,
305 pub single_points_of_failure: Vec<Dominator>,
306 pub upstream: Vec<ReachNode>,
307 pub downstream: Vec<ReachNode>,
308}
309
310#[derive(Debug, Clone, Serialize)]
312pub struct BlastSummary {
313 pub upstream: usize,
314 pub downstream: usize,
315 pub max_downstream_distance: usize,
316 pub single_points_of_failure: usize,
317}
318
319impl BlastRadius {
320 #[must_use]
322 pub fn to_json(&self) -> serde_json::Value {
323 let mut v = serde_json::to_value(self).unwrap_or(serde_json::Value::Null);
324 if let serde_json::Value::Object(ref mut m) = v {
325 m.insert("schema".into(), serde_json::json!("vela.blast_radius.v0.1"));
326 m.insert(
327 "claim_boundary".into(),
328 serde_json::json!({
329 "graph_is_derived": true,
330 "edges_are_declared_links": true,
331 "relations_are_candidates_not_adjudicated": true,
332 "impact_is_structural_not_a_truth_claim": true,
333 }),
334 );
335 }
336 v
337 }
338}
339
340fn coord_string(present: bool) -> String {
345 if present {
346 "1/1".to_string()
347 } else {
348 "0/1".to_string()
349 }
350}
351
352fn corner_letter(support: bool, refute: bool) -> char {
354 use crate::status_provenance::BelnapStatus;
355 match (support, refute) {
356 (true, true) => BelnapStatus::Both,
357 (true, false) => BelnapStatus::True,
358 (false, true) => BelnapStatus::False,
359 (false, false) => BelnapStatus::None,
360 }
361 .letter()
362}
363
364#[derive(Debug, Clone, Serialize)]
368pub struct GradedStatus {
369 pub support_kappa: String,
370 pub refute_kappa: String,
371 pub conflict: String,
372 pub belnap: char,
373}
374
375#[derive(Debug, Clone, Serialize)]
380pub struct GradedImpact {
381 pub id: String,
382 pub label: String,
383 pub kappa_before: String,
384 pub kappa_after: String,
385 pub delta_kappa: String,
386 pub support_killed: bool,
389}
390
391#[derive(Debug, Clone, Serialize)]
393pub struct GradedBlastSummary {
394 pub downstream_candidates: usize,
395 pub weakened: usize,
396 pub killed: usize,
397 pub semiring: &'static str,
398}
399
400#[derive(Debug, Clone, Serialize)]
408pub struct GradedBlast {
409 pub structural: BlastRadius,
410 pub center_status: GradedStatus,
411 pub impacted: Vec<GradedImpact>,
412 pub summary: GradedBlastSummary,
413}
414
415impl GradedBlast {
416 #[must_use]
419 pub fn to_json(&self) -> serde_json::Value {
420 let mut v = self.structural.to_json();
421 if let serde_json::Value::Object(ref mut m) = v {
422 m.insert(
423 "schema".into(),
424 serde_json::json!("vela.blast_radius.graded.v0.1"),
425 );
426 m.insert(
427 "center_status".into(),
428 serde_json::to_value(&self.center_status).unwrap_or_default(),
429 );
430 m.insert(
431 "graded_impact".into(),
432 serde_json::to_value(&self.impacted).unwrap_or_default(),
433 );
434 m.insert(
435 "graded_summary".into(),
436 serde_json::to_value(&self.summary).unwrap_or_default(),
437 );
438 m.insert(
439 "graded_boundary".into(),
440 serde_json::json!({
441 "support_kappa": "per-finding canonical support degree — kappa of the support polynomial (derive_status_provenance + the bilattice)",
442 "propagation": "Bottleneck semiring (max, min): a chain is as strong as its weakest premise — the kernel's licensed reading for dependency support",
443 "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",
444 "pruning": "a structurally-reachable dependent with delta_kappa = 0 has alternative support and is NOT listed",
445 }),
446 );
447 }
448 v
449 }
450}
451
452struct PropCtx<'a> {
459 graph: &'a FrontierGraph,
460 project: &'a Project,
461 kinds: &'a [EdgeKind],
462 zeroed: &'a str,
463 own: HashMap<String, bool>,
464 memo: HashMap<String, bool>,
465}
466
467impl<'a> PropCtx<'a> {
468 fn new(
469 graph: &'a FrontierGraph,
470 project: &'a Project,
471 kinds: &'a [EdgeKind],
472 zeroed: &'a str,
473 ) -> Self {
474 PropCtx {
475 graph,
476 project,
477 kinds,
478 zeroed,
479 own: HashMap::new(),
480 memo: HashMap::new(),
481 }
482 }
483
484 fn own_support(&mut self, d: &str) -> bool {
487 if d == self.zeroed {
488 return false;
489 }
490 if let Some(v) = self.own.get(d) {
491 return *v;
492 }
493 let k = !derive_status_provenance(&self.project.events, d)
494 .support
495 .is_empty();
496 self.own.insert(d.to_string(), k);
497 k
498 }
499
500 fn prop(&mut self, d: &str, on_path: &mut BTreeSet<String>) -> bool {
504 if let Some(v) = self.memo.get(d) {
505 return *v;
506 }
507 let own = self.own_support(d);
508 if !on_path.insert(d.to_string()) {
509 return own; }
511 let premises: Vec<String> = self
512 .graph
513 .edges
514 .iter()
515 .filter(|e| e.source == d && self.kinds.contains(&e.kind))
516 .map(|e| e.target.clone())
517 .collect();
518 let mut k = own;
519 for p in premises {
520 k = k && self.prop(&p, on_path);
521 }
522 on_path.remove(d);
523 self.memo.insert(d.to_string(), k);
524 k
525 }
526}
527
528#[derive(Debug, Clone, Default)]
531pub struct FrontierGraph {
532 nodes: BTreeMap<String, Node>,
533 edges: Vec<Edge>,
534}
535
536impl FrontierGraph {
537 #[must_use]
541 pub fn from_project(project: &Project) -> Self {
542 let mut attachments_by_target: HashMap<
547 &str,
548 Vec<crate::verifier_attachment::VerifierAttachment>,
549 > = HashMap::new();
550 for a in &project.verifier_attachments {
551 attachments_by_target
552 .entry(a.target.as_str())
553 .or_default()
554 .push(a.clone());
555 }
556
557 let mut nodes = BTreeMap::new();
558 for f in &project.findings {
559 let label = f.assertion.text.chars().take(120).collect::<String>();
560 let gate = attachments_by_target.get(f.id.as_str()).map(|atts| {
561 crate::verifier_attachment::derive_gate_status(
562 &crate::verifier_attachment::claim_digest(&f.assertion.text),
563 atts,
564 )
565 .status
566 });
567 nodes.insert(
568 f.id.clone(),
569 Node {
570 id: f.id.clone(),
571 label,
572 contested: f.flags.contested,
573 gap: f.flags.gap,
574 confidence: f.confidence.score,
575 state: FindingState::derive(&f.flags, f.confidence.score, gate),
576 },
577 );
578 }
579
580 let mut edges = Vec::new();
581 for f in &project.findings {
582 for link in &f.links {
583 let Some(kind) = EdgeKind::from_link_type(&link.link_type) else {
584 continue;
585 };
586 let bare = crate::bundle::bare_finding_id(&link.target);
596 let (target, target_in_frontier) = if nodes.contains_key(bare) {
597 (bare.to_string(), true)
598 } else {
599 (link.target.clone(), false)
600 };
601 edges.push(Edge {
602 source: f.id.clone(),
603 target,
604 kind,
605 note: link.note.clone(),
606 target_in_frontier,
607 });
608 }
609 }
610
611 Self { nodes, edges }
612 }
613
614 #[must_use]
624 pub fn from_edges<I>(raw: I) -> Self
625 where
626 I: IntoIterator<Item = (String, String, EdgeKind)>,
627 {
628 let mut nodes: BTreeMap<String, Node> = BTreeMap::new();
629 let mut edges = Vec::new();
630 for (source, target, kind) in raw {
631 for id in [&source, &target] {
632 nodes.entry(id.clone()).or_insert_with(|| Node {
633 id: id.clone(),
634 label: id.clone(),
635 contested: false,
636 gap: false,
637 confidence: 1.0,
638 state: FindingState::Open,
639 });
640 }
641 edges.push(Edge {
642 source,
643 target,
644 kind,
645 note: String::new(),
646 target_in_frontier: true,
647 });
648 }
649 Self { nodes, edges }
650 }
651
652 #[must_use]
656 pub fn in_degree_ranked(&self, kinds: &[EdgeKind]) -> Vec<(String, usize)> {
657 let mut deg: BTreeMap<String, usize> = BTreeMap::new();
658 for e in &self.edges {
659 if kinds.is_empty() || kinds.contains(&e.kind) {
660 *deg.entry(e.target.clone()).or_default() += 1;
661 }
662 }
663 let mut v: Vec<(String, usize)> = deg.into_iter().collect();
664 v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
665 v
666 }
667
668 #[must_use]
670 pub fn node_count(&self) -> usize {
671 self.nodes.len()
672 }
673
674 #[must_use]
676 pub fn edge_count(&self) -> usize {
677 self.edges.len()
678 }
679
680 #[must_use]
682 pub fn contains(&self, id: &str) -> bool {
683 self.nodes.contains_key(id)
684 }
685
686 pub fn edges_of_kind(&self, kind: EdgeKind) -> impl Iterator<Item = &Edge> {
688 self.edges.iter().filter(move |e| e.kind == kind)
689 }
690
691 #[must_use]
695 pub fn all_edges(&self) -> &[Edge] {
696 &self.edges
697 }
698
699 #[must_use]
701 pub fn node(&self, id: &str) -> Option<&Node> {
702 self.nodes.get(id)
703 }
704
705 pub fn nodes(&self) -> impl Iterator<Item = &Node> {
707 self.nodes.values()
708 }
709
710 #[must_use]
712 pub fn edge_kind_counts(&self) -> BTreeMap<&'static str, usize> {
713 let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
714 for e in &self.edges {
715 *counts.entry(e.kind.as_str()).or_default() += 1;
716 }
717 counts
718 }
719
720 #[must_use]
725 pub fn contradiction_pairs(&self) -> Vec<(String, String)> {
726 let mut pairs = BTreeSet::new();
727 for e in self.edges_of_kind(EdgeKind::Contradicts) {
728 let (a, b) = if e.source <= e.target {
729 (e.source.clone(), e.target.clone())
730 } else {
731 (e.target.clone(), e.source.clone())
732 };
733 pairs.insert((a, b));
734 }
735 pairs.into_iter().collect()
736 }
737
738 #[must_use]
742 pub fn closure_of_kind(&self, start: &str, kind: EdgeKind) -> BTreeSet<String> {
743 let mut seen = BTreeSet::new();
744 let mut stack = vec![start.to_string()];
745 while let Some(node) = stack.pop() {
746 for e in self
747 .edges
748 .iter()
749 .filter(|e| e.kind == kind && e.source == node)
750 {
751 if seen.insert(e.target.clone()) {
752 stack.push(e.target.clone());
753 }
754 }
755 }
756 seen
757 }
758
759 #[must_use]
765 pub fn explore(&self, start: &str, max_hops: usize) -> Exploration {
766 if !self.nodes.contains_key(start) {
767 return Exploration::default();
768 }
769 let mut adj: HashMap<&str, Vec<&str>> = HashMap::new();
773 for e in &self.edges {
774 adj.entry(e.source.as_str()).or_default().push(&e.target);
775 adj.entry(e.target.as_str()).or_default().push(&e.source);
776 }
777 let mut node_hops: BTreeMap<String, usize> = BTreeMap::new();
778 node_hops.insert(start.to_string(), 0);
779 let mut frontier = vec![start.to_string()];
780 for hop in 1..=max_hops {
781 let mut next = Vec::new();
782 for n in &frontier {
783 for &neighbor in adj.get(n.as_str()).into_iter().flatten() {
784 if !node_hops.contains_key(neighbor) {
785 node_hops.insert(neighbor.to_string(), hop);
786 next.push(neighbor.to_string());
787 }
788 }
789 }
790 if next.is_empty() {
791 break;
792 }
793 frontier = next;
794 }
795 let edges = self
796 .edges
797 .iter()
798 .filter(|e| node_hops.contains_key(&e.source) && node_hops.contains_key(&e.target))
799 .cloned()
800 .collect();
801 Exploration { node_hops, edges }
802 }
803
804 #[must_use]
806 pub fn label_of(&self, id: &str) -> Option<&str> {
807 self.nodes.get(id).map(|n| n.label.as_str())
808 }
809
810 fn support_reach(
814 &self,
815 start: &str,
816 kinds: &[EdgeKind],
817 remove: Option<&str>,
818 ) -> BTreeSet<String> {
819 let mut seen = BTreeSet::new();
820 let mut stack = vec![start.to_string()];
821 while let Some(node) = stack.pop() {
822 for e in &self.edges {
823 if e.source != node || !kinds.contains(&e.kind) {
824 continue;
825 }
826 if remove == Some(e.target.as_str()) {
827 continue;
828 }
829 if e.target.as_str() == start {
830 continue;
831 }
832 if seen.insert(e.target.clone()) {
833 stack.push(e.target.clone());
834 }
835 }
836 }
837 seen
838 }
839
840 #[must_use]
848 pub fn support_dominators(&self, z: &str, kinds: &[EdgeKind]) -> Vec<Dominator> {
849 let full = self.support_reach(z, kinds, None);
850 if full.is_empty() {
851 return vec![];
852 }
853 let total = full.len();
854 let mut doms: Vec<Dominator> = full
855 .iter()
856 .map(|d| {
857 let without = self.support_reach(z, kinds, Some(d));
858 let weight = full.iter().filter(|n| !without.contains(*n)).count();
859 Dominator {
860 node: d.clone(),
861 label: self.label_of(d).unwrap_or("").to_string(),
862 state: self.nodes.get(d).map(|n| n.state),
863 weight,
864 single_point_of_failure: weight == total && total >= 2,
865 }
866 })
867 .collect();
868 doms.sort_by(|a, b| b.weight.cmp(&a.weight).then(a.node.cmp(&b.node)));
869 doms
870 }
871
872 pub const DEPENDENCY_KINDS: [EdgeKind; 4] = [
877 EdgeKind::Supports,
878 EdgeKind::DependsOn,
879 EdgeKind::DerivedFrom,
880 EdgeKind::Discharges,
881 ];
882
883 pub const REQUIRED_PREMISE_KINDS: [EdgeKind; 3] = [
890 EdgeKind::DependsOn,
891 EdgeKind::DerivedFrom,
892 EdgeKind::Discharges,
893 ];
894
895 #[must_use]
901 pub fn find_node(&self, query: &str) -> Option<String> {
902 if self.nodes.contains_key(query) {
903 return Some(query.to_string());
904 }
905 if let Some(n) = self.nodes.values().find(|n| n.id.starts_with(query)) {
906 return Some(n.id.clone());
907 }
908 let q = query.to_lowercase();
909 self.nodes
910 .values()
911 .find(|n| n.label.to_lowercase().contains(&q))
912 .map(|n| n.id.clone())
913 }
914
915 fn reach_directed(
920 &self,
921 start: &str,
922 kinds: &[EdgeKind],
923 reverse: bool,
924 ) -> BTreeMap<String, usize> {
925 let mut dist: BTreeMap<String, usize> = BTreeMap::new();
926 dist.insert(start.to_string(), 0);
927 let mut frontier = vec![start.to_string()];
928 let mut hop = 0usize;
929 while !frontier.is_empty() {
930 hop += 1;
931 let mut next = Vec::new();
932 for node in &frontier {
933 for e in &self.edges {
934 if !kinds.contains(&e.kind) {
935 continue;
936 }
937 let (from, to) = if reverse {
938 (&e.target, &e.source)
939 } else {
940 (&e.source, &e.target)
941 };
942 if from != node {
943 continue;
944 }
945 if !dist.contains_key(to) {
946 dist.insert(to.clone(), hop);
947 next.push(to.clone());
948 }
949 }
950 }
951 frontier = next;
952 }
953 dist.remove(start);
954 dist
955 }
956
957 fn reach_nodes(&self, dist: &BTreeMap<String, usize>) -> Vec<ReachNode> {
960 let mut v: Vec<ReachNode> = dist
961 .iter()
962 .map(|(id, &distance)| ReachNode {
963 id: id.clone(),
964 label: self.label_of(id).unwrap_or("").to_string(),
965 state: self.nodes.get(id).map(|n| n.state),
966 distance,
967 })
968 .collect();
969 v.sort_by(|a, b| a.distance.cmp(&b.distance).then(a.id.cmp(&b.id)));
970 v
971 }
972
973 #[must_use]
978 pub fn blast_radius(
979 &self,
980 start: &str,
981 kinds: &[EdgeKind],
982 direction: BlastDirection,
983 ) -> BlastRadius {
984 let kinds: Vec<EdgeKind> = if kinds.is_empty() {
985 Self::DEPENDENCY_KINDS.to_vec()
986 } else {
987 kinds.to_vec()
988 };
989 let want_up = matches!(direction, BlastDirection::Upstream | BlastDirection::Both);
990 let want_down = matches!(direction, BlastDirection::Downstream | BlastDirection::Both);
991
992 let upstream = if want_up {
993 self.reach_nodes(&self.reach_directed(start, &kinds, false))
994 } else {
995 Vec::new()
996 };
997 let downstream = if want_down {
998 self.reach_nodes(&self.reach_directed(start, &kinds, true))
999 } else {
1000 Vec::new()
1001 };
1002 let single_points_of_failure: Vec<Dominator> = if want_up {
1003 self.support_dominators(start, &kinds)
1004 .into_iter()
1005 .filter(|d| d.single_point_of_failure)
1006 .collect()
1007 } else {
1008 Vec::new()
1009 };
1010 let max_downstream_distance = downstream.iter().map(|n| n.distance).max().unwrap_or(0);
1011 BlastRadius {
1012 center: start.to_string(),
1013 center_label: self.label_of(start).unwrap_or("").to_string(),
1014 center_state: self.nodes.get(start).map(|n| n.state),
1015 kinds: kinds.iter().map(|k| k.as_str()).collect(),
1016 summary: BlastSummary {
1017 upstream: upstream.len(),
1018 downstream: downstream.len(),
1019 max_downstream_distance,
1020 single_points_of_failure: single_points_of_failure.len(),
1021 },
1022 single_points_of_failure,
1023 upstream,
1024 downstream,
1025 }
1026 }
1027
1028 #[must_use]
1037 pub fn blast_radius_graded(
1038 &self,
1039 project: &Project,
1040 start: &str,
1041 kinds: &[EdgeKind],
1042 direction: BlastDirection,
1043 ) -> GradedBlast {
1044 let structural = self.blast_radius(start, kinds, direction);
1045 let center_sp = derive_status_provenance(&project.events, start);
1046 let center_support = !center_sp.support.is_empty();
1047 let center_refute = !center_sp.refute.is_empty();
1048 let center_status = GradedStatus {
1049 support_kappa: coord_string(center_support),
1050 refute_kappa: coord_string(center_refute),
1051 conflict: coord_string(center_support && center_refute),
1053 belnap: corner_letter(center_support, center_refute),
1054 };
1055
1056 let mut before = PropCtx::new(self, project, &Self::REQUIRED_PREMISE_KINDS, "");
1061 let mut after = PropCtx::new(self, project, &Self::REQUIRED_PREMISE_KINDS, start);
1062 let mut scored: Vec<(bool, GradedImpact)> = Vec::new();
1064 for node in &structural.downstream {
1065 let b = before.prop(&node.id, &mut BTreeSet::new());
1066 let a = after.prop(&node.id, &mut BTreeSet::new());
1067 if b && !a {
1069 scored.push((
1070 true,
1071 GradedImpact {
1072 id: node.id.clone(),
1073 label: node.label.clone(),
1074 kappa_before: coord_string(b),
1075 kappa_after: coord_string(a),
1076 delta_kappa: coord_string(b && !a),
1077 support_killed: !a,
1078 },
1079 ));
1080 }
1081 }
1082 scored.sort_by(|x, y| y.0.cmp(&x.0).then(x.1.id.cmp(&y.1.id)));
1084 let killed = scored.iter().filter(|(_, g)| g.support_killed).count();
1085 let weakened = scored.len();
1086 let impacted: Vec<GradedImpact> = scored.into_iter().map(|(_, g)| g).collect();
1087 let summary = GradedBlastSummary {
1088 downstream_candidates: structural.downstream.len(),
1089 weakened,
1090 killed,
1091 semiring: "bottleneck",
1092 };
1093 GradedBlast {
1094 structural,
1095 center_status,
1096 impacted,
1097 summary,
1098 }
1099 }
1100
1101 #[must_use]
1106 pub fn to_json(&self) -> serde_json::Value {
1107 let nodes: Vec<&Node> = self.nodes.values().collect();
1108 serde_json::json!({
1109 "schema": "vela.frontier_graph.claims.v0.1",
1110 "summary": {
1111 "nodes": self.node_count(),
1112 "edges": self.edge_count(),
1113 "edge_kinds": self.edge_kind_counts(),
1114 "contradiction_pairs": self.contradiction_pairs().len(),
1115 },
1116 "nodes": nodes,
1117 "edges": self.edges,
1118 "claim_boundary": {
1119 "graph_is_derived": true,
1120 "edges_are_declared_links": true,
1121 "relations_are_candidates_not_adjudicated": true,
1122 },
1123 })
1124 }
1125}
1126
1127#[derive(Debug, Clone, Default)]
1131pub struct Exploration {
1132 node_hops: BTreeMap<String, usize>,
1133 pub edges: Vec<Edge>,
1134}
1135
1136impl Exploration {
1137 #[must_use]
1139 pub fn node_count(&self) -> usize {
1140 self.node_hops.len()
1141 }
1142
1143 #[must_use]
1145 pub fn max_hop(&self) -> usize {
1146 self.node_hops.values().copied().max().unwrap_or(0)
1147 }
1148
1149 #[must_use]
1151 pub fn nodes_at(&self, hop: usize) -> Vec<&str> {
1152 self.node_hops
1153 .iter()
1154 .filter(|(_, h)| **h == hop)
1155 .map(|(id, _)| id.as_str())
1156 .collect()
1157 }
1158
1159 #[must_use]
1161 pub fn edge_kind_counts(&self) -> BTreeMap<&'static str, usize> {
1162 let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
1163 for e in &self.edges {
1164 *counts.entry(e.kind.as_str()).or_default() += 1;
1165 }
1166 counts
1167 }
1168}
1169
1170#[cfg(test)]
1171mod tests {
1172 use super::*;
1173 use crate::project::assemble;
1174 use crate::project::reverse_dep_index_tests::{link_to, synth_finding};
1175
1176 fn link_typed(target: &str, link_type: &str) -> crate::bundle::Link {
1177 let mut link = link_to(target);
1178 link.link_type = link_type.into();
1179 link
1180 }
1181
1182 #[test]
1183 fn gate_verified_establishes_regardless_of_confidence() {
1184 use crate::bundle::{Flags, ReviewState};
1185 use crate::verifier_attachment::GateStatus;
1186 let flags = Flags::default();
1189 assert_eq!(
1190 FindingState::derive(&flags, 0.3, Some(GateStatus::Verified)),
1191 FindingState::Established,
1192 "gate=Verified at confidence 0.3 must be Established"
1193 );
1194 let accepted = Flags {
1197 review_state: Some(ReviewState::Accepted),
1198 ..Default::default()
1199 };
1200 assert_eq!(
1201 FindingState::derive(&accepted, 0.3, None),
1202 FindingState::Fragile
1203 );
1204 assert_eq!(
1206 FindingState::derive(&accepted, 0.9, None),
1207 FindingState::Established
1208 );
1209 }
1210
1211 #[test]
1212 fn from_edges_builds_a_premise_graph_and_blasts_downstream() {
1213 let edges = vec![
1217 ("thm1".to_string(), "lemma".to_string(), EdgeKind::DependsOn),
1218 ("thm2".to_string(), "lemma".to_string(), EdgeKind::DependsOn),
1219 ("lemma".to_string(), "prim".to_string(), EdgeKind::DependsOn),
1220 ];
1221 let g = FrontierGraph::from_edges(edges);
1222 assert_eq!(g.node_count(), 4);
1223 assert_eq!(g.edge_count(), 3);
1224 let ranked = g.in_degree_ranked(&[EdgeKind::DependsOn]);
1226 assert_eq!(ranked[0], ("lemma".to_string(), 2));
1227 let blast = g.blast_radius("prim", &[EdgeKind::DependsOn], BlastDirection::Downstream);
1229 assert_eq!(
1230 blast.summary.downstream, 3,
1231 "all transitive dependents impacted"
1232 );
1233 assert_eq!(blast.summary.max_downstream_distance, 2);
1234 let ids: Vec<&str> = blast.downstream.iter().map(|n| n.id.as_str()).collect();
1235 assert!(ids.contains(&"lemma") && ids.contains(&"thm1") && ids.contains(&"thm2"));
1236 let leaf = g.blast_radius("thm1", &[EdgeKind::DependsOn], BlastDirection::Downstream);
1238 assert_eq!(leaf.summary.downstream, 0);
1239 }
1240
1241 #[test]
1242 fn every_valid_link_type_maps_to_an_edge_kind() {
1243 for lt in crate::bundle::VALID_LINK_TYPES {
1246 assert!(
1247 EdgeKind::from_link_type(lt).is_some(),
1248 "VALID_LINK_TYPES has '{lt}' with no EdgeKind mapping"
1249 );
1250 }
1251 }
1252
1253 #[test]
1254 fn maps_all_t7_link_types_to_edge_kinds() {
1255 for (s, k) in [
1256 ("supports", EdgeKind::Supports),
1257 ("contradicts", EdgeKind::Contradicts),
1258 ("depends", EdgeKind::DependsOn),
1259 ("synthesized_from", EdgeKind::DerivedFrom),
1260 ("derived_from", EdgeKind::DerivedFrom),
1261 ("improves", EdgeKind::Improves),
1262 ("generalizes", EdgeKind::Generalizes),
1263 ("specializes", EdgeKind::Specializes),
1264 ("supersedes", EdgeKind::Supersedes),
1265 ("extends", EdgeKind::Extends),
1266 ("replicates", EdgeKind::Replicates),
1267 ] {
1268 assert_eq!(EdgeKind::from_link_type(s), Some(k));
1269 }
1270 assert_eq!(EdgeKind::from_link_type("nonsense"), None);
1271 }
1272
1273 #[test]
1274 fn builds_typed_nodes_and_edges_from_project() {
1275 let base = synth_finding(0, vec![]);
1276 let a = synth_finding(1, vec![link_typed(&base.id, "improves")]);
1277 let b = synth_finding(2, vec![link_typed(&a.id, "supersedes")]);
1278 let (base_id, a_id, b_id) = (base.id.clone(), a.id.clone(), b.id.clone());
1279
1280 let mut project = assemble("fg", vec![], 0, 0, "test");
1281 project.findings = vec![base, a, b];
1282
1283 let g = FrontierGraph::from_project(&project);
1284 assert_eq!(g.node_count(), 3);
1285 assert_eq!(g.edge_count(), 2);
1286 assert!(g.contains(&base_id));
1287
1288 let improves: Vec<&Edge> = g.edges_of_kind(EdgeKind::Improves).collect();
1289 assert_eq!(improves.len(), 1);
1290 assert_eq!(improves[0].source, a_id);
1291 assert_eq!(improves[0].target, base_id);
1292 assert!(improves[0].target_in_frontier);
1293
1294 assert!(
1297 g.closure_of_kind(&a_id, EdgeKind::Improves)
1298 .contains(&base_id)
1299 );
1300 assert!(
1301 g.closure_of_kind(&b_id, EdgeKind::Supersedes)
1302 .contains(&a_id)
1303 );
1304 }
1305
1306 #[test]
1307 fn explore_walks_multiple_hops_with_distances() {
1308 let base = synth_finding(0, vec![]);
1309 let a = synth_finding(1, vec![link_typed(&base.id, "improves")]);
1310 let b = synth_finding(2, vec![link_typed(&a.id, "supersedes")]);
1311 let (base_id, a_id, b_id) = (base.id.clone(), a.id.clone(), b.id.clone());
1312 let mut project = assemble("explore", vec![], 0, 0, "test");
1313 project.findings = vec![base, a, b];
1314
1315 let g = FrontierGraph::from_project(&project);
1316 let ex = g.explore(&base_id, 2);
1317 assert_eq!(ex.node_count(), 3);
1318 assert_eq!(ex.node_hops[&base_id], 0);
1319 assert_eq!(ex.node_hops[&a_id], 1);
1320 assert_eq!(ex.node_hops[&b_id], 2);
1321 assert_eq!(ex.max_hop(), 2);
1322 assert_eq!(ex.nodes_at(1), vec![a_id.as_str()]);
1323
1324 assert_eq!(g.explore(&base_id, 1).node_count(), 2);
1326 }
1327
1328 #[test]
1329 fn support_dominators_find_the_single_point_of_failure() {
1330 let b = synth_finding(0, vec![]);
1334 let a = synth_finding(1, vec![link_typed(&b.id, "depends")]);
1335 let z = synth_finding(2, vec![link_typed(&a.id, "depends")]);
1336 let (a_id, b_id, z_id) = (a.id.clone(), b.id.clone(), z.id.clone());
1337 let mut project = assemble("dom", vec![], 0, 0, "test");
1338 project.findings = vec![b, a, z];
1339
1340 let g = FrontierGraph::from_project(&project);
1341 let doms = g.support_dominators(&z_id, &[EdgeKind::DependsOn]);
1342 let a_dom = doms.iter().find(|d| d.node == a_id).unwrap();
1344 let b_dom = doms.iter().find(|d| d.node == b_id).unwrap();
1345 assert_eq!(a_dom.weight, 2);
1346 assert!(a_dom.single_point_of_failure);
1347 assert_eq!(b_dom.weight, 1);
1348 assert!(!b_dom.single_point_of_failure);
1349 assert_eq!(doms.first().unwrap().node, a_id);
1351 }
1352
1353 #[test]
1354 fn support_dominators_empty_for_unsupported_claim() {
1355 let z = synth_finding(0, vec![]);
1356 let z_id = z.id.clone();
1357 let mut project = assemble("dom2", vec![], 0, 0, "test");
1358 project.findings = vec![z];
1359 let g = FrontierGraph::from_project(&project);
1360 assert!(
1361 g.support_dominators(&z_id, &[EdgeKind::DependsOn])
1362 .is_empty()
1363 );
1364 }
1365
1366 #[test]
1367 fn blast_radius_splits_upstream_and_downstream() {
1368 let b = synth_finding(0, vec![]);
1370 let a = synth_finding(1, vec![link_typed(&b.id, "depends")]);
1371 let z = synth_finding(2, vec![link_typed(&a.id, "depends")]);
1372 let (a_id, b_id, z_id) = (a.id.clone(), b.id.clone(), z.id.clone());
1373 let mut project = assemble("blast", vec![], 0, 0, "test");
1374 project.findings = vec![b, a, z];
1375 let g = FrontierGraph::from_project(&project);
1376
1377 let from_z = g.blast_radius(&z_id, &[EdgeKind::DependsOn], BlastDirection::Both);
1379 assert_eq!(from_z.summary.upstream, 2);
1380 assert_eq!(from_z.summary.downstream, 0);
1381 let up_ids: Vec<&str> = from_z.upstream.iter().map(|n| n.id.as_str()).collect();
1382 assert_eq!(up_ids, vec![a_id.as_str(), b_id.as_str()]); assert_eq!(from_z.upstream[0].distance, 1);
1384 assert_eq!(from_z.upstream[1].distance, 2);
1385 assert_eq!(from_z.single_points_of_failure.len(), 1);
1387 assert_eq!(from_z.single_points_of_failure[0].node, a_id);
1388
1389 let from_b = g.blast_radius(&b_id, &[EdgeKind::DependsOn], BlastDirection::Both);
1391 assert_eq!(from_b.summary.upstream, 0);
1392 assert_eq!(from_b.summary.downstream, 2);
1393 assert_eq!(from_b.summary.max_downstream_distance, 2);
1394 let down_ids: Vec<&str> = from_b.downstream.iter().map(|n| n.id.as_str()).collect();
1395 assert_eq!(down_ids, vec![a_id.as_str(), z_id.as_str()]);
1396
1397 let down_only = g.blast_radius(&b_id, &[EdgeKind::DependsOn], BlastDirection::Downstream);
1399 assert!(down_only.upstream.is_empty());
1400 assert_eq!(down_only.downstream.len(), 2);
1401 }
1402
1403 #[test]
1404 fn blast_radius_graded_prunes_unweakened_dependents() {
1405 use crate::events::{EVENT_SCHEMA, NULL_HASH, StateActor, StateEvent, StateTarget};
1406 let asserted = |idx: usize, target: &str| StateEvent {
1407 schema: EVENT_SCHEMA.to_string(),
1408 id: format!("vev_g_{idx:04}"),
1409 kind: "finding.asserted".into(),
1410 target: StateTarget {
1411 r#type: "finding".to_string(),
1412 id: target.to_string(),
1413 },
1414 actor: StateActor {
1415 id: "reviewer:test".to_string(),
1416 r#type: "human".to_string(),
1417 },
1418 timestamp: format!("2026-06-17T00:00:{:02}Z", idx % 60),
1419 reason: "graded blast test".to_string(),
1420 before_hash: NULL_HASH.to_string(),
1421 after_hash: NULL_HASH.to_string(),
1422 payload: serde_json::json!({}),
1423 caveats: vec![],
1424 signature: None,
1425 };
1426
1427 let b = synth_finding(0, vec![]);
1431 let a = synth_finding(1, vec![link_typed(&b.id, "depends")]);
1432 let z = synth_finding(2, vec![link_typed(&a.id, "depends")]);
1433 let s = synth_finding(3, vec![link_typed(&b.id, "supports")]);
1434 let (a_id, z_id, s_id, b_id) = (a.id.clone(), z.id.clone(), s.id.clone(), b.id.clone());
1435 let mut project = assemble("graded", vec![], 0, 0, "test");
1436 project.events = vec![
1437 asserted(0, &b_id),
1438 asserted(1, &a_id),
1439 asserted(2, &z_id),
1440 asserted(3, &s_id),
1441 ];
1442 project.findings = vec![b, a, z, s];
1443 let g = FrontierGraph::from_project(&project);
1444
1445 let gb = g.blast_radius_graded(&project, &b_id, &[], BlastDirection::Downstream);
1446
1447 assert_eq!(gb.center_status.belnap, 'T');
1449 assert_eq!(gb.center_status.support_kappa, "1/1");
1450
1451 let ids: Vec<&str> = gb.impacted.iter().map(|i| i.id.as_str()).collect();
1455 assert!(ids.contains(&a_id.as_str()) && ids.contains(&z_id.as_str()));
1456 assert!(
1457 !ids.contains(&s_id.as_str()),
1458 "a supports-only corroborator must be pruned from the graded impact"
1459 );
1460 assert_eq!(gb.summary.downstream_candidates, 3);
1461 assert_eq!(gb.summary.weakened, 2);
1462 assert_eq!(gb.summary.killed, 2);
1463 for imp in &gb.impacted {
1464 assert_eq!(imp.kappa_before, "1/1");
1465 assert_eq!(imp.kappa_after, "0/1");
1466 assert_eq!(imp.delta_kappa, "1/1");
1467 assert!(imp.support_killed);
1468 }
1469 }
1470
1471 #[test]
1472 fn contradiction_pairs_dedupe_symmetrically() {
1473 let x = synth_finding(0, vec![]);
1474 let y = synth_finding(1, vec![link_typed(&x.id, "contradicts")]);
1475 let mut x = x;
1477 x.links.push(link_typed(&y.id, "contradicts"));
1478 let (x_id, y_id) = (x.id.clone(), y.id.clone());
1479
1480 let mut project = assemble("fg-contra", vec![], 0, 0, "test");
1481 project.findings = vec![x, y];
1482
1483 let g = FrontierGraph::from_project(&project);
1484 let pairs = g.contradiction_pairs();
1485 assert_eq!(pairs.len(), 1);
1486 let expected = if x_id <= y_id {
1487 (x_id, y_id)
1488 } else {
1489 (y_id, x_id)
1490 };
1491 assert_eq!(pairs[0], expected);
1492 }
1493
1494 #[test]
1495 fn cross_frontier_target_is_flagged_out_of_frontier() {
1496 let f = synth_finding(
1497 0,
1498 vec![link_typed("vf_abcdef0123456789@vfr_remote", "supports")],
1499 );
1500 let mut project = assemble("fg-xf", vec![], 0, 0, "test");
1501 project.findings = vec![f];
1502
1503 let g = FrontierGraph::from_project(&project);
1504 let edge = g.edges_of_kind(EdgeKind::Supports).next().unwrap();
1505 assert!(!edge.target_in_frontier);
1506 }
1507
1508 #[test]
1509 fn cross_frontier_link_resolves_in_merged_project() {
1510 let remote = synth_finding(0, vec![]);
1514 let cross_target = format!("{}@vfr_remote", remote.id);
1515 let local = synth_finding(1, vec![link_typed(&cross_target, "depends")]);
1516 let (remote_id, local_id) = (remote.id.clone(), local.id.clone());
1517
1518 let mut project = assemble("fg-merge", vec![], 0, 0, "test");
1519 project.findings = vec![remote, local];
1520
1521 let g = FrontierGraph::from_project(&project);
1522 let edge = g.edges_of_kind(EdgeKind::DependsOn).next().unwrap();
1523 assert!(edge.target_in_frontier, "bare id present → resolves");
1524 assert_eq!(edge.target, remote_id, "target rewritten to bare id");
1525 assert!(
1527 g.closure_of_kind(&local_id, EdgeKind::DependsOn)
1528 .contains(&remote_id)
1529 );
1530 }
1531
1532 #[test]
1533 fn to_json_is_marked_derived_with_claim_boundary() {
1534 let project = assemble("fg-json", vec![], 0, 0, "test");
1535 let g = FrontierGraph::from_project(&project);
1536 let v = g.to_json();
1537 assert_eq!(v["schema"], "vela.frontier_graph.claims.v0.1");
1538 assert_eq!(v["claim_boundary"]["graph_is_derived"], true);
1539 assert_eq!(
1540 v["claim_boundary"]["relations_are_candidates_not_adjudicated"],
1541 true
1542 );
1543 }
1544}