use std::collections::{BTreeMap, BTreeSet, HashMap};
use serde::Serialize;
use crate::evidence_diff::derive_status_provenance;
use crate::project::Project;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum EdgeKind {
Supports,
Contradicts,
DependsOn,
DerivedFrom,
Improves,
Generalizes,
Specializes,
Supersedes,
Extends,
Replicates,
Discharges,
}
impl EdgeKind {
#[must_use]
pub fn from_link_type(link_type: &str) -> Option<Self> {
Some(match link_type {
"supports" => Self::Supports,
"contradicts" => Self::Contradicts,
"depends" => Self::DependsOn,
"synthesized_from" | "derived_from" => Self::DerivedFrom,
"improves" => Self::Improves,
"generalizes" => Self::Generalizes,
"specializes" => Self::Specializes,
"supersedes" => Self::Supersedes,
"extends" => Self::Extends,
"replicates" => Self::Replicates,
"discharges" => Self::Discharges,
"implies" => Self::DependsOn,
_ => return None,
})
}
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Supports => "supports",
Self::Contradicts => "contradicts",
Self::DependsOn => "depends_on",
Self::DerivedFrom => "derived_from",
Self::Improves => "improves",
Self::Generalizes => "generalizes",
Self::Specializes => "specializes",
Self::Supersedes => "supersedes",
Self::Extends => "extends",
Self::Replicates => "replicates",
Self::Discharges => "discharges",
}
}
pub const ALL: [EdgeKind; 11] = [
Self::Supports,
Self::Contradicts,
Self::DependsOn,
Self::DerivedFrom,
Self::Improves,
Self::Generalizes,
Self::Specializes,
Self::Supersedes,
Self::Extends,
Self::Replicates,
Self::Discharges,
];
#[must_use]
pub fn parse(s: &str) -> Option<Self> {
Self::ALL
.iter()
.copied()
.find(|k| k.as_str() == s)
.or_else(|| Self::from_link_type(s))
}
}
#[derive(Debug, Clone, Serialize)]
pub struct Edge {
pub source: String,
pub target: String,
pub kind: EdgeKind,
pub note: String,
pub target_in_frontier: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FindingState {
Open,
Established,
Refuted,
Contested,
Fragile,
}
impl FindingState {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Open => "open",
Self::Established => "established",
Self::Refuted => "refuted",
Self::Contested => "contested",
Self::Fragile => "fragile",
}
}
#[must_use]
pub fn derive(
flags: &crate::bundle::Flags,
confidence: f64,
gate: Option<crate::verifier_attachment::GateStatus>,
) -> Self {
use crate::bundle::ReviewState;
use crate::verifier_attachment::GateStatus;
if gate == Some(GateStatus::Refuted) {
return Self::Refuted;
}
match flags.review_state {
Some(ReviewState::Rejected) => return Self::Refuted,
Some(ReviewState::Contested) | Some(ReviewState::NeedsRevision) => {
return Self::Contested;
}
None if flags.contested => return Self::Contested,
_ => {}
}
if gate == Some(GateStatus::Verified) {
return Self::Established;
}
if flags.review_state == Some(ReviewState::Accepted) {
if confidence < FRAGILE_CONFIDENCE {
Self::Fragile
} else {
Self::Established
}
} else {
Self::Open
}
}
#[must_use]
pub fn of(flags: &crate::bundle::Flags, confidence: f64) -> Self {
Self::derive(flags, confidence, None)
}
}
pub const FRAGILE_CONFIDENCE: f64 = 0.6;
#[derive(Debug, Clone, Serialize)]
pub struct Node {
pub id: String,
pub label: String,
pub contested: bool,
pub gap: bool,
pub confidence: f64,
pub state: FindingState,
}
#[derive(Debug, Clone, Serialize)]
pub struct Dominator {
pub node: String,
pub label: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<FindingState>,
pub weight: usize,
pub single_point_of_failure: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BlastDirection {
Upstream,
Downstream,
Both,
}
#[derive(Debug, Clone, Serialize)]
pub struct ReachNode {
pub id: String,
pub label: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<FindingState>,
pub distance: usize,
}
#[derive(Debug, Clone, Serialize)]
pub struct BlastRadius {
pub center: String,
pub center_label: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub center_state: Option<FindingState>,
pub kinds: Vec<&'static str>,
pub summary: BlastSummary,
pub single_points_of_failure: Vec<Dominator>,
pub upstream: Vec<ReachNode>,
pub downstream: Vec<ReachNode>,
}
#[derive(Debug, Clone, Serialize)]
pub struct BlastSummary {
pub upstream: usize,
pub downstream: usize,
pub max_downstream_distance: usize,
pub single_points_of_failure: usize,
}
impl BlastRadius {
#[must_use]
pub fn to_json(&self) -> serde_json::Value {
let mut v = serde_json::to_value(self).unwrap_or(serde_json::Value::Null);
if let serde_json::Value::Object(ref mut m) = v {
m.insert("schema".into(), serde_json::json!("vela.blast_radius.v0.1"));
m.insert(
"claim_boundary".into(),
serde_json::json!({
"graph_is_derived": true,
"edges_are_declared_links": true,
"relations_are_candidates_not_adjudicated": true,
"impact_is_structural_not_a_truth_claim": true,
}),
);
}
v
}
}
fn coord_string(present: bool) -> String {
if present {
"1/1".to_string()
} else {
"0/1".to_string()
}
}
fn corner_letter(support: bool, refute: bool) -> char {
use crate::status_provenance::BelnapStatus;
match (support, refute) {
(true, true) => BelnapStatus::Both,
(true, false) => BelnapStatus::True,
(false, true) => BelnapStatus::False,
(false, false) => BelnapStatus::None,
}
.letter()
}
#[derive(Debug, Clone, Serialize)]
pub struct GradedStatus {
pub support_kappa: String,
pub refute_kappa: String,
pub conflict: String,
pub belnap: char,
}
#[derive(Debug, Clone, Serialize)]
pub struct GradedImpact {
pub id: String,
pub label: String,
pub kappa_before: String,
pub kappa_after: String,
pub delta_kappa: String,
pub support_killed: bool,
}
#[derive(Debug, Clone, Serialize)]
pub struct GradedBlastSummary {
pub downstream_candidates: usize,
pub weakened: usize,
pub killed: usize,
pub semiring: &'static str,
}
#[derive(Debug, Clone, Serialize)]
pub struct GradedBlast {
pub structural: BlastRadius,
pub center_status: GradedStatus,
pub impacted: Vec<GradedImpact>,
pub summary: GradedBlastSummary,
}
impl GradedBlast {
#[must_use]
pub fn to_json(&self) -> serde_json::Value {
let mut v = self.structural.to_json();
if let serde_json::Value::Object(ref mut m) = v {
m.insert(
"schema".into(),
serde_json::json!("vela.blast_radius.graded.v0.1"),
);
m.insert(
"center_status".into(),
serde_json::to_value(&self.center_status).unwrap_or_default(),
);
m.insert(
"graded_impact".into(),
serde_json::to_value(&self.impacted).unwrap_or_default(),
);
m.insert(
"graded_summary".into(),
serde_json::to_value(&self.summary).unwrap_or_default(),
);
m.insert(
"graded_boundary".into(),
serde_json::json!({
"support_kappa": "per-finding canonical support degree — kappa of the support polynomial (derive_status_provenance + the bilattice)",
"propagation": "Bottleneck semiring (max, min): a chain is as strong as its weakest premise — the kernel's licensed reading for dependency support",
"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",
"pruning": "a structurally-reachable dependent with delta_kappa = 0 has alternative support and is NOT listed",
}),
);
}
v
}
}
struct PropCtx<'a> {
graph: &'a FrontierGraph,
project: &'a Project,
kinds: &'a [EdgeKind],
zeroed: &'a str,
own: HashMap<String, bool>,
memo: HashMap<String, bool>,
}
impl<'a> PropCtx<'a> {
fn new(
graph: &'a FrontierGraph,
project: &'a Project,
kinds: &'a [EdgeKind],
zeroed: &'a str,
) -> Self {
PropCtx {
graph,
project,
kinds,
zeroed,
own: HashMap::new(),
memo: HashMap::new(),
}
}
fn own_support(&mut self, d: &str) -> bool {
if d == self.zeroed {
return false;
}
if let Some(v) = self.own.get(d) {
return *v;
}
let k = !derive_status_provenance(&self.project.events, d)
.support
.is_empty();
self.own.insert(d.to_string(), k);
k
}
fn prop(&mut self, d: &str, on_path: &mut BTreeSet<String>) -> bool {
if let Some(v) = self.memo.get(d) {
return *v;
}
let own = self.own_support(d);
if !on_path.insert(d.to_string()) {
return own; }
let premises: Vec<String> = self
.graph
.edges
.iter()
.filter(|e| e.source == d && self.kinds.contains(&e.kind))
.map(|e| e.target.clone())
.collect();
let mut k = own;
for p in premises {
k = k && self.prop(&p, on_path);
}
on_path.remove(d);
self.memo.insert(d.to_string(), k);
k
}
}
#[derive(Debug, Clone, Default)]
pub struct FrontierGraph {
nodes: BTreeMap<String, Node>,
edges: Vec<Edge>,
}
impl FrontierGraph {
#[must_use]
pub fn from_project(project: &Project) -> Self {
let mut attachments_by_target: HashMap<
&str,
Vec<crate::verifier_attachment::VerifierAttachment>,
> = HashMap::new();
for a in &project.verifier_attachments {
attachments_by_target
.entry(a.target.as_str())
.or_default()
.push(a.clone());
}
let mut nodes = BTreeMap::new();
for f in &project.findings {
let label = f.assertion.text.chars().take(120).collect::<String>();
let gate = attachments_by_target.get(f.id.as_str()).map(|atts| {
crate::verifier_attachment::derive_gate_status(
&crate::verifier_attachment::claim_digest(&f.assertion.text),
atts,
)
.status
});
nodes.insert(
f.id.clone(),
Node {
id: f.id.clone(),
label,
contested: f.flags.contested,
gap: f.flags.gap,
confidence: f.confidence.score,
state: FindingState::derive(&f.flags, f.confidence.score, gate),
},
);
}
let mut edges = Vec::new();
for f in &project.findings {
for link in &f.links {
let Some(kind) = EdgeKind::from_link_type(&link.link_type) else {
continue;
};
let bare = crate::bundle::bare_finding_id(&link.target);
let (target, target_in_frontier) = if nodes.contains_key(bare) {
(bare.to_string(), true)
} else {
(link.target.clone(), false)
};
edges.push(Edge {
source: f.id.clone(),
target,
kind,
note: link.note.clone(),
target_in_frontier,
});
}
}
Self { nodes, edges }
}
#[must_use]
pub fn from_edges<I>(raw: I) -> Self
where
I: IntoIterator<Item = (String, String, EdgeKind)>,
{
let mut nodes: BTreeMap<String, Node> = BTreeMap::new();
let mut edges = Vec::new();
for (source, target, kind) in raw {
for id in [&source, &target] {
nodes.entry(id.clone()).or_insert_with(|| Node {
id: id.clone(),
label: id.clone(),
contested: false,
gap: false,
confidence: 1.0,
state: FindingState::Open,
});
}
edges.push(Edge {
source,
target,
kind,
note: String::new(),
target_in_frontier: true,
});
}
Self { nodes, edges }
}
#[must_use]
pub fn in_degree_ranked(&self, kinds: &[EdgeKind]) -> Vec<(String, usize)> {
let mut deg: BTreeMap<String, usize> = BTreeMap::new();
for e in &self.edges {
if kinds.is_empty() || kinds.contains(&e.kind) {
*deg.entry(e.target.clone()).or_default() += 1;
}
}
let mut v: Vec<(String, usize)> = deg.into_iter().collect();
v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
v
}
#[must_use]
pub fn node_count(&self) -> usize {
self.nodes.len()
}
#[must_use]
pub fn edge_count(&self) -> usize {
self.edges.len()
}
#[must_use]
pub fn contains(&self, id: &str) -> bool {
self.nodes.contains_key(id)
}
pub fn edges_of_kind(&self, kind: EdgeKind) -> impl Iterator<Item = &Edge> {
self.edges.iter().filter(move |e| e.kind == kind)
}
#[must_use]
pub fn all_edges(&self) -> &[Edge] {
&self.edges
}
#[must_use]
pub fn node(&self, id: &str) -> Option<&Node> {
self.nodes.get(id)
}
pub fn nodes(&self) -> impl Iterator<Item = &Node> {
self.nodes.values()
}
#[must_use]
pub fn edge_kind_counts(&self) -> BTreeMap<&'static str, usize> {
let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
for e in &self.edges {
*counts.entry(e.kind.as_str()).or_default() += 1;
}
counts
}
#[must_use]
pub fn contradiction_pairs(&self) -> Vec<(String, String)> {
let mut pairs = BTreeSet::new();
for e in self.edges_of_kind(EdgeKind::Contradicts) {
let (a, b) = if e.source <= e.target {
(e.source.clone(), e.target.clone())
} else {
(e.target.clone(), e.source.clone())
};
pairs.insert((a, b));
}
pairs.into_iter().collect()
}
#[must_use]
pub fn closure_of_kind(&self, start: &str, kind: EdgeKind) -> BTreeSet<String> {
let mut seen = BTreeSet::new();
let mut stack = vec![start.to_string()];
while let Some(node) = stack.pop() {
for e in self
.edges
.iter()
.filter(|e| e.kind == kind && e.source == node)
{
if seen.insert(e.target.clone()) {
stack.push(e.target.clone());
}
}
}
seen
}
#[must_use]
pub fn explore(&self, start: &str, max_hops: usize) -> Exploration {
if !self.nodes.contains_key(start) {
return Exploration::default();
}
let mut adj: HashMap<&str, Vec<&str>> = HashMap::new();
for e in &self.edges {
adj.entry(e.source.as_str()).or_default().push(&e.target);
adj.entry(e.target.as_str()).or_default().push(&e.source);
}
let mut node_hops: BTreeMap<String, usize> = BTreeMap::new();
node_hops.insert(start.to_string(), 0);
let mut frontier = vec![start.to_string()];
for hop in 1..=max_hops {
let mut next = Vec::new();
for n in &frontier {
for &neighbor in adj.get(n.as_str()).into_iter().flatten() {
if !node_hops.contains_key(neighbor) {
node_hops.insert(neighbor.to_string(), hop);
next.push(neighbor.to_string());
}
}
}
if next.is_empty() {
break;
}
frontier = next;
}
let edges = self
.edges
.iter()
.filter(|e| node_hops.contains_key(&e.source) && node_hops.contains_key(&e.target))
.cloned()
.collect();
Exploration { node_hops, edges }
}
#[must_use]
pub fn label_of(&self, id: &str) -> Option<&str> {
self.nodes.get(id).map(|n| n.label.as_str())
}
fn support_reach(
&self,
start: &str,
kinds: &[EdgeKind],
remove: Option<&str>,
) -> BTreeSet<String> {
let mut seen = BTreeSet::new();
let mut stack = vec![start.to_string()];
while let Some(node) = stack.pop() {
for e in &self.edges {
if e.source != node || !kinds.contains(&e.kind) {
continue;
}
if remove == Some(e.target.as_str()) {
continue;
}
if e.target.as_str() == start {
continue;
}
if seen.insert(e.target.clone()) {
stack.push(e.target.clone());
}
}
}
seen
}
#[must_use]
pub fn support_dominators(&self, z: &str, kinds: &[EdgeKind]) -> Vec<Dominator> {
let full = self.support_reach(z, kinds, None);
if full.is_empty() {
return vec![];
}
let total = full.len();
let mut doms: Vec<Dominator> = full
.iter()
.map(|d| {
let without = self.support_reach(z, kinds, Some(d));
let weight = full.iter().filter(|n| !without.contains(*n)).count();
Dominator {
node: d.clone(),
label: self.label_of(d).unwrap_or("").to_string(),
state: self.nodes.get(d).map(|n| n.state),
weight,
single_point_of_failure: weight == total && total >= 2,
}
})
.collect();
doms.sort_by(|a, b| b.weight.cmp(&a.weight).then(a.node.cmp(&b.node)));
doms
}
pub const DEPENDENCY_KINDS: [EdgeKind; 4] = [
EdgeKind::Supports,
EdgeKind::DependsOn,
EdgeKind::DerivedFrom,
EdgeKind::Discharges,
];
pub const REQUIRED_PREMISE_KINDS: [EdgeKind; 3] = [
EdgeKind::DependsOn,
EdgeKind::DerivedFrom,
EdgeKind::Discharges,
];
#[must_use]
pub fn find_node(&self, query: &str) -> Option<String> {
if self.nodes.contains_key(query) {
return Some(query.to_string());
}
if let Some(n) = self.nodes.values().find(|n| n.id.starts_with(query)) {
return Some(n.id.clone());
}
let q = query.to_lowercase();
self.nodes
.values()
.find(|n| n.label.to_lowercase().contains(&q))
.map(|n| n.id.clone())
}
fn reach_directed(
&self,
start: &str,
kinds: &[EdgeKind],
reverse: bool,
) -> BTreeMap<String, usize> {
let mut dist: BTreeMap<String, usize> = BTreeMap::new();
dist.insert(start.to_string(), 0);
let mut frontier = vec![start.to_string()];
let mut hop = 0usize;
while !frontier.is_empty() {
hop += 1;
let mut next = Vec::new();
for node in &frontier {
for e in &self.edges {
if !kinds.contains(&e.kind) {
continue;
}
let (from, to) = if reverse {
(&e.target, &e.source)
} else {
(&e.source, &e.target)
};
if from != node {
continue;
}
if !dist.contains_key(to) {
dist.insert(to.clone(), hop);
next.push(to.clone());
}
}
}
frontier = next;
}
dist.remove(start);
dist
}
fn reach_nodes(&self, dist: &BTreeMap<String, usize>) -> Vec<ReachNode> {
let mut v: Vec<ReachNode> = dist
.iter()
.map(|(id, &distance)| ReachNode {
id: id.clone(),
label: self.label_of(id).unwrap_or("").to_string(),
state: self.nodes.get(id).map(|n| n.state),
distance,
})
.collect();
v.sort_by(|a, b| a.distance.cmp(&b.distance).then(a.id.cmp(&b.id)));
v
}
#[must_use]
pub fn blast_radius(
&self,
start: &str,
kinds: &[EdgeKind],
direction: BlastDirection,
) -> BlastRadius {
let kinds: Vec<EdgeKind> = if kinds.is_empty() {
Self::DEPENDENCY_KINDS.to_vec()
} else {
kinds.to_vec()
};
let want_up = matches!(direction, BlastDirection::Upstream | BlastDirection::Both);
let want_down = matches!(direction, BlastDirection::Downstream | BlastDirection::Both);
let upstream = if want_up {
self.reach_nodes(&self.reach_directed(start, &kinds, false))
} else {
Vec::new()
};
let downstream = if want_down {
self.reach_nodes(&self.reach_directed(start, &kinds, true))
} else {
Vec::new()
};
let single_points_of_failure: Vec<Dominator> = if want_up {
self.support_dominators(start, &kinds)
.into_iter()
.filter(|d| d.single_point_of_failure)
.collect()
} else {
Vec::new()
};
let max_downstream_distance = downstream.iter().map(|n| n.distance).max().unwrap_or(0);
BlastRadius {
center: start.to_string(),
center_label: self.label_of(start).unwrap_or("").to_string(),
center_state: self.nodes.get(start).map(|n| n.state),
kinds: kinds.iter().map(|k| k.as_str()).collect(),
summary: BlastSummary {
upstream: upstream.len(),
downstream: downstream.len(),
max_downstream_distance,
single_points_of_failure: single_points_of_failure.len(),
},
single_points_of_failure,
upstream,
downstream,
}
}
#[must_use]
pub fn blast_radius_graded(
&self,
project: &Project,
start: &str,
kinds: &[EdgeKind],
direction: BlastDirection,
) -> GradedBlast {
let structural = self.blast_radius(start, kinds, direction);
let center_sp = derive_status_provenance(&project.events, start);
let center_support = !center_sp.support.is_empty();
let center_refute = !center_sp.refute.is_empty();
let center_status = GradedStatus {
support_kappa: coord_string(center_support),
refute_kappa: coord_string(center_refute),
conflict: coord_string(center_support && center_refute),
belnap: corner_letter(center_support, center_refute),
};
let mut before = PropCtx::new(self, project, &Self::REQUIRED_PREMISE_KINDS, "");
let mut after = PropCtx::new(self, project, &Self::REQUIRED_PREMISE_KINDS, start);
let mut scored: Vec<(bool, GradedImpact)> = Vec::new();
for node in &structural.downstream {
let b = before.prop(&node.id, &mut BTreeSet::new());
let a = after.prop(&node.id, &mut BTreeSet::new());
if b && !a {
scored.push((
true,
GradedImpact {
id: node.id.clone(),
label: node.label.clone(),
kappa_before: coord_string(b),
kappa_after: coord_string(a),
delta_kappa: coord_string(b && !a),
support_killed: !a,
},
));
}
}
scored.sort_by(|x, y| y.0.cmp(&x.0).then(x.1.id.cmp(&y.1.id)));
let killed = scored.iter().filter(|(_, g)| g.support_killed).count();
let weakened = scored.len();
let impacted: Vec<GradedImpact> = scored.into_iter().map(|(_, g)| g).collect();
let summary = GradedBlastSummary {
downstream_candidates: structural.downstream.len(),
weakened,
killed,
semiring: "bottleneck",
};
GradedBlast {
structural,
center_status,
impacted,
summary,
}
}
#[must_use]
pub fn to_json(&self) -> serde_json::Value {
let nodes: Vec<&Node> = self.nodes.values().collect();
serde_json::json!({
"schema": "vela.frontier_graph.claims.v0.1",
"summary": {
"nodes": self.node_count(),
"edges": self.edge_count(),
"edge_kinds": self.edge_kind_counts(),
"contradiction_pairs": self.contradiction_pairs().len(),
},
"nodes": nodes,
"edges": self.edges,
"claim_boundary": {
"graph_is_derived": true,
"edges_are_declared_links": true,
"relations_are_candidates_not_adjudicated": true,
},
})
}
}
#[derive(Debug, Clone, Default)]
pub struct Exploration {
node_hops: BTreeMap<String, usize>,
pub edges: Vec<Edge>,
}
impl Exploration {
#[must_use]
pub fn node_count(&self) -> usize {
self.node_hops.len()
}
#[must_use]
pub fn max_hop(&self) -> usize {
self.node_hops.values().copied().max().unwrap_or(0)
}
#[must_use]
pub fn nodes_at(&self, hop: usize) -> Vec<&str> {
self.node_hops
.iter()
.filter(|(_, h)| **h == hop)
.map(|(id, _)| id.as_str())
.collect()
}
#[must_use]
pub fn edge_kind_counts(&self) -> BTreeMap<&'static str, usize> {
let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
for e in &self.edges {
*counts.entry(e.kind.as_str()).or_default() += 1;
}
counts
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::project::assemble;
use crate::project::reverse_dep_index_tests::{link_to, synth_finding};
fn link_typed(target: &str, link_type: &str) -> crate::bundle::Link {
let mut link = link_to(target);
link.link_type = link_type.into();
link
}
#[test]
fn gate_verified_establishes_regardless_of_confidence() {
use crate::bundle::{Flags, ReviewState};
use crate::verifier_attachment::GateStatus;
let flags = Flags::default();
assert_eq!(
FindingState::derive(&flags, 0.3, Some(GateStatus::Verified)),
FindingState::Established,
"gate=Verified at confidence 0.3 must be Established"
);
let accepted = Flags {
review_state: Some(ReviewState::Accepted),
..Default::default()
};
assert_eq!(
FindingState::derive(&accepted, 0.3, None),
FindingState::Fragile
);
assert_eq!(
FindingState::derive(&accepted, 0.9, None),
FindingState::Established
);
}
#[test]
fn from_edges_builds_a_premise_graph_and_blasts_downstream() {
let edges = vec![
("thm1".to_string(), "lemma".to_string(), EdgeKind::DependsOn),
("thm2".to_string(), "lemma".to_string(), EdgeKind::DependsOn),
("lemma".to_string(), "prim".to_string(), EdgeKind::DependsOn),
];
let g = FrontierGraph::from_edges(edges);
assert_eq!(g.node_count(), 4);
assert_eq!(g.edge_count(), 3);
let ranked = g.in_degree_ranked(&[EdgeKind::DependsOn]);
assert_eq!(ranked[0], ("lemma".to_string(), 2));
let blast = g.blast_radius("prim", &[EdgeKind::DependsOn], BlastDirection::Downstream);
assert_eq!(
blast.summary.downstream, 3,
"all transitive dependents impacted"
);
assert_eq!(blast.summary.max_downstream_distance, 2);
let ids: Vec<&str> = blast.downstream.iter().map(|n| n.id.as_str()).collect();
assert!(ids.contains(&"lemma") && ids.contains(&"thm1") && ids.contains(&"thm2"));
let leaf = g.blast_radius("thm1", &[EdgeKind::DependsOn], BlastDirection::Downstream);
assert_eq!(leaf.summary.downstream, 0);
}
#[test]
fn every_valid_link_type_maps_to_an_edge_kind() {
for lt in crate::bundle::VALID_LINK_TYPES {
assert!(
EdgeKind::from_link_type(lt).is_some(),
"VALID_LINK_TYPES has '{lt}' with no EdgeKind mapping"
);
}
}
#[test]
fn maps_all_t7_link_types_to_edge_kinds() {
for (s, k) in [
("supports", EdgeKind::Supports),
("contradicts", EdgeKind::Contradicts),
("depends", EdgeKind::DependsOn),
("synthesized_from", EdgeKind::DerivedFrom),
("derived_from", EdgeKind::DerivedFrom),
("improves", EdgeKind::Improves),
("generalizes", EdgeKind::Generalizes),
("specializes", EdgeKind::Specializes),
("supersedes", EdgeKind::Supersedes),
("extends", EdgeKind::Extends),
("replicates", EdgeKind::Replicates),
] {
assert_eq!(EdgeKind::from_link_type(s), Some(k));
}
assert_eq!(EdgeKind::from_link_type("nonsense"), None);
}
#[test]
fn builds_typed_nodes_and_edges_from_project() {
let base = synth_finding(0, vec![]);
let a = synth_finding(1, vec![link_typed(&base.id, "improves")]);
let b = synth_finding(2, vec![link_typed(&a.id, "supersedes")]);
let (base_id, a_id, b_id) = (base.id.clone(), a.id.clone(), b.id.clone());
let mut project = assemble("fg", vec![], 0, 0, "test");
project.findings = vec![base, a, b];
let g = FrontierGraph::from_project(&project);
assert_eq!(g.node_count(), 3);
assert_eq!(g.edge_count(), 2);
assert!(g.contains(&base_id));
let improves: Vec<&Edge> = g.edges_of_kind(EdgeKind::Improves).collect();
assert_eq!(improves.len(), 1);
assert_eq!(improves[0].source, a_id);
assert_eq!(improves[0].target, base_id);
assert!(improves[0].target_in_frontier);
assert!(
g.closure_of_kind(&a_id, EdgeKind::Improves)
.contains(&base_id)
);
assert!(
g.closure_of_kind(&b_id, EdgeKind::Supersedes)
.contains(&a_id)
);
}
#[test]
fn explore_walks_multiple_hops_with_distances() {
let base = synth_finding(0, vec![]);
let a = synth_finding(1, vec![link_typed(&base.id, "improves")]);
let b = synth_finding(2, vec![link_typed(&a.id, "supersedes")]);
let (base_id, a_id, b_id) = (base.id.clone(), a.id.clone(), b.id.clone());
let mut project = assemble("explore", vec![], 0, 0, "test");
project.findings = vec![base, a, b];
let g = FrontierGraph::from_project(&project);
let ex = g.explore(&base_id, 2);
assert_eq!(ex.node_count(), 3);
assert_eq!(ex.node_hops[&base_id], 0);
assert_eq!(ex.node_hops[&a_id], 1);
assert_eq!(ex.node_hops[&b_id], 2);
assert_eq!(ex.max_hop(), 2);
assert_eq!(ex.nodes_at(1), vec![a_id.as_str()]);
assert_eq!(g.explore(&base_id, 1).node_count(), 2);
}
#[test]
fn support_dominators_find_the_single_point_of_failure() {
let b = synth_finding(0, vec![]);
let a = synth_finding(1, vec![link_typed(&b.id, "depends")]);
let z = synth_finding(2, vec![link_typed(&a.id, "depends")]);
let (a_id, b_id, z_id) = (a.id.clone(), b.id.clone(), z.id.clone());
let mut project = assemble("dom", vec![], 0, 0, "test");
project.findings = vec![b, a, z];
let g = FrontierGraph::from_project(&project);
let doms = g.support_dominators(&z_id, &[EdgeKind::DependsOn]);
let a_dom = doms.iter().find(|d| d.node == a_id).unwrap();
let b_dom = doms.iter().find(|d| d.node == b_id).unwrap();
assert_eq!(a_dom.weight, 2);
assert!(a_dom.single_point_of_failure);
assert_eq!(b_dom.weight, 1);
assert!(!b_dom.single_point_of_failure);
assert_eq!(doms.first().unwrap().node, a_id);
}
#[test]
fn support_dominators_empty_for_unsupported_claim() {
let z = synth_finding(0, vec![]);
let z_id = z.id.clone();
let mut project = assemble("dom2", vec![], 0, 0, "test");
project.findings = vec![z];
let g = FrontierGraph::from_project(&project);
assert!(
g.support_dominators(&z_id, &[EdgeKind::DependsOn])
.is_empty()
);
}
#[test]
fn blast_radius_splits_upstream_and_downstream() {
let b = synth_finding(0, vec![]);
let a = synth_finding(1, vec![link_typed(&b.id, "depends")]);
let z = synth_finding(2, vec![link_typed(&a.id, "depends")]);
let (a_id, b_id, z_id) = (a.id.clone(), b.id.clone(), z.id.clone());
let mut project = assemble("blast", vec![], 0, 0, "test");
project.findings = vec![b, a, z];
let g = FrontierGraph::from_project(&project);
let from_z = g.blast_radius(&z_id, &[EdgeKind::DependsOn], BlastDirection::Both);
assert_eq!(from_z.summary.upstream, 2);
assert_eq!(from_z.summary.downstream, 0);
let up_ids: Vec<&str> = from_z.upstream.iter().map(|n| n.id.as_str()).collect();
assert_eq!(up_ids, vec![a_id.as_str(), b_id.as_str()]); assert_eq!(from_z.upstream[0].distance, 1);
assert_eq!(from_z.upstream[1].distance, 2);
assert_eq!(from_z.single_points_of_failure.len(), 1);
assert_eq!(from_z.single_points_of_failure[0].node, a_id);
let from_b = g.blast_radius(&b_id, &[EdgeKind::DependsOn], BlastDirection::Both);
assert_eq!(from_b.summary.upstream, 0);
assert_eq!(from_b.summary.downstream, 2);
assert_eq!(from_b.summary.max_downstream_distance, 2);
let down_ids: Vec<&str> = from_b.downstream.iter().map(|n| n.id.as_str()).collect();
assert_eq!(down_ids, vec![a_id.as_str(), z_id.as_str()]);
let down_only = g.blast_radius(&b_id, &[EdgeKind::DependsOn], BlastDirection::Downstream);
assert!(down_only.upstream.is_empty());
assert_eq!(down_only.downstream.len(), 2);
}
#[test]
fn blast_radius_graded_prunes_unweakened_dependents() {
use crate::events::{EVENT_SCHEMA, NULL_HASH, StateActor, StateEvent, StateTarget};
let asserted = |idx: usize, target: &str| StateEvent {
schema: EVENT_SCHEMA.to_string(),
id: format!("vev_g_{idx:04}"),
kind: "finding.asserted".into(),
target: StateTarget {
r#type: "finding".to_string(),
id: target.to_string(),
},
actor: StateActor {
id: "reviewer:test".to_string(),
r#type: "human".to_string(),
},
timestamp: format!("2026-06-17T00:00:{:02}Z", idx % 60),
reason: "graded blast test".to_string(),
before_hash: NULL_HASH.to_string(),
after_hash: NULL_HASH.to_string(),
payload: serde_json::json!({}),
caveats: vec![],
signature: None,
};
let b = synth_finding(0, vec![]);
let a = synth_finding(1, vec![link_typed(&b.id, "depends")]);
let z = synth_finding(2, vec![link_typed(&a.id, "depends")]);
let s = synth_finding(3, vec![link_typed(&b.id, "supports")]);
let (a_id, z_id, s_id, b_id) = (a.id.clone(), z.id.clone(), s.id.clone(), b.id.clone());
let mut project = assemble("graded", vec![], 0, 0, "test");
project.events = vec![
asserted(0, &b_id),
asserted(1, &a_id),
asserted(2, &z_id),
asserted(3, &s_id),
];
project.findings = vec![b, a, z, s];
let g = FrontierGraph::from_project(&project);
let gb = g.blast_radius_graded(&project, &b_id, &[], BlastDirection::Downstream);
assert_eq!(gb.center_status.belnap, 'T');
assert_eq!(gb.center_status.support_kappa, "1/1");
let ids: Vec<&str> = gb.impacted.iter().map(|i| i.id.as_str()).collect();
assert!(ids.contains(&a_id.as_str()) && ids.contains(&z_id.as_str()));
assert!(
!ids.contains(&s_id.as_str()),
"a supports-only corroborator must be pruned from the graded impact"
);
assert_eq!(gb.summary.downstream_candidates, 3);
assert_eq!(gb.summary.weakened, 2);
assert_eq!(gb.summary.killed, 2);
for imp in &gb.impacted {
assert_eq!(imp.kappa_before, "1/1");
assert_eq!(imp.kappa_after, "0/1");
assert_eq!(imp.delta_kappa, "1/1");
assert!(imp.support_killed);
}
}
#[test]
fn contradiction_pairs_dedupe_symmetrically() {
let x = synth_finding(0, vec![]);
let y = synth_finding(1, vec![link_typed(&x.id, "contradicts")]);
let mut x = x;
x.links.push(link_typed(&y.id, "contradicts"));
let (x_id, y_id) = (x.id.clone(), y.id.clone());
let mut project = assemble("fg-contra", vec![], 0, 0, "test");
project.findings = vec![x, y];
let g = FrontierGraph::from_project(&project);
let pairs = g.contradiction_pairs();
assert_eq!(pairs.len(), 1);
let expected = if x_id <= y_id {
(x_id, y_id)
} else {
(y_id, x_id)
};
assert_eq!(pairs[0], expected);
}
#[test]
fn cross_frontier_target_is_flagged_out_of_frontier() {
let f = synth_finding(
0,
vec![link_typed("vf_abcdef0123456789@vfr_remote", "supports")],
);
let mut project = assemble("fg-xf", vec![], 0, 0, "test");
project.findings = vec![f];
let g = FrontierGraph::from_project(&project);
let edge = g.edges_of_kind(EdgeKind::Supports).next().unwrap();
assert!(!edge.target_in_frontier);
}
#[test]
fn cross_frontier_link_resolves_in_merged_project() {
let remote = synth_finding(0, vec![]);
let cross_target = format!("{}@vfr_remote", remote.id);
let local = synth_finding(1, vec![link_typed(&cross_target, "depends")]);
let (remote_id, local_id) = (remote.id.clone(), local.id.clone());
let mut project = assemble("fg-merge", vec![], 0, 0, "test");
project.findings = vec![remote, local];
let g = FrontierGraph::from_project(&project);
let edge = g.edges_of_kind(EdgeKind::DependsOn).next().unwrap();
assert!(edge.target_in_frontier, "bare id present → resolves");
assert_eq!(edge.target, remote_id, "target rewritten to bare id");
assert!(
g.closure_of_kind(&local_id, EdgeKind::DependsOn)
.contains(&remote_id)
);
}
#[test]
fn to_json_is_marked_derived_with_claim_boundary() {
let project = assemble("fg-json", vec![], 0, 0, "test");
let g = FrontierGraph::from_project(&project);
let v = g.to_json();
assert_eq!(v["schema"], "vela.frontier_graph.claims.v0.1");
assert_eq!(v["claim_boundary"]["graph_is_derived"], true);
assert_eq!(
v["claim_boundary"]["relations_are_candidates_not_adjudicated"],
true
);
}
}