1use serde::Serialize;
14use std::collections::{HashMap, VecDeque};
15
16use crate::frontier_graph::{Edge, EdgeKind, FrontierGraph};
17
18pub const SUPPORT_KINDS: [EdgeKind; 5] = [
23 EdgeKind::Supports,
24 EdgeKind::DependsOn,
25 EdgeKind::DerivedFrom,
26 EdgeKind::Discharges,
27 EdgeKind::Improves,
28];
29
30#[derive(Debug, Clone, Serialize)]
32pub struct PathStep {
33 pub from: String,
34 pub to: String,
35 pub kind: &'static str,
36 pub note: String,
37}
38
39#[derive(Debug, Clone, Serialize)]
41pub struct Path {
42 pub from: String,
43 pub to: String,
44 pub nodes: Vec<String>,
46 pub steps: Vec<PathStep>,
48 pub hops: usize,
50}
51
52impl Path {
53 #[must_use]
55 pub fn to_json(&self) -> serde_json::Value {
56 serde_json::json!({
57 "schema": "vela.golden_thread.v0.1",
58 "from": self.from,
59 "to": self.to,
60 "hops": self.hops,
61 "nodes": self.nodes,
62 "steps": self.steps,
63 "derived": true,
64 })
65 }
66}
67
68#[must_use]
73pub fn shortest_path(
74 graph: &FrontierGraph,
75 from: &str,
76 to: &str,
77 kinds: &[EdgeKind],
78) -> Option<Path> {
79 if !graph.contains(from) || !graph.contains(to) {
80 return None;
81 }
82 if from == to {
83 return Some(Path {
84 from: from.to_string(),
85 to: to.to_string(),
86 nodes: vec![from.to_string()],
87 steps: vec![],
88 hops: 0,
89 });
90 }
91
92 let mut adj: HashMap<&str, Vec<&Edge>> = HashMap::new();
94 for e in graph.all_edges() {
95 if kinds.contains(&e.kind) {
96 adj.entry(e.source.as_str()).or_default().push(e);
97 }
98 }
99
100 let mut prev: HashMap<&str, &Edge> = HashMap::new();
103 let mut queue: VecDeque<&str> = VecDeque::new();
104 let mut seen: HashMap<&str, ()> = HashMap::new();
105 queue.push_back(from);
106 seen.insert(from, ());
107 while let Some(node) = queue.pop_front() {
108 for &e in adj.get(node).into_iter().flatten() {
109 let next = e.target.as_str();
110 if seen.contains_key(next) {
111 continue;
112 }
113 seen.insert(next, ());
114 prev.insert(next, e);
115 if next == to {
116 return Some(reconstruct(from, to, &prev));
117 }
118 queue.push_back(next);
119 }
120 }
121 None
122}
123
124fn reconstruct(from: &str, to: &str, prev: &HashMap<&str, &Edge>) -> Path {
126 let mut steps_rev: Vec<PathStep> = Vec::new();
127 let mut nodes_rev: Vec<String> = vec![to.to_string()];
128 let mut cur = to;
129 while cur != from {
130 let e = prev[cur];
131 steps_rev.push(PathStep {
132 from: e.source.clone(),
133 to: e.target.clone(),
134 kind: e.kind.as_str(),
135 note: e.note.clone(),
136 });
137 nodes_rev.push(e.source.clone());
138 cur = e.source.as_str();
139 }
140 nodes_rev.reverse();
141 steps_rev.reverse();
142 Path {
143 from: from.to_string(),
144 to: to.to_string(),
145 hops: steps_rev.len(),
146 nodes: nodes_rev,
147 steps: steps_rev,
148 }
149}
150
151#[cfg(test)]
152mod tests {
153 use super::*;
154 use crate::project::assemble;
155 use crate::project::reverse_dep_index_tests::{link_to, synth_finding};
156
157 fn link_typed(target: &str, link_type: &str) -> crate::bundle::Link {
158 let mut link = link_to(target);
159 link.link_type = link_type.into();
160 link
161 }
162
163 #[test]
164 fn finds_shortest_support_chain() {
165 let a = synth_finding(0, vec![]);
167 let b = synth_finding(1, vec![link_typed(&a.id, "depends")]);
168 let c = synth_finding(2, vec![link_typed(&b.id, "depends")]);
169 let (a_id, c_id) = (a.id.clone(), c.id.clone());
170 let mut project = assemble("pf", vec![], 0, 0, "test");
171 project.findings = vec![a, b, c];
172
173 let g = FrontierGraph::from_project(&project);
174 let p = shortest_path(&g, &c_id, &a_id, &SUPPORT_KINDS).expect("path exists");
175 assert_eq!(p.hops, 2);
176 assert_eq!(p.nodes.first().unwrap(), &c_id);
177 assert_eq!(p.nodes.last().unwrap(), &a_id);
178 assert_eq!(p.steps.len(), 2);
179 }
180
181 #[test]
182 fn no_path_when_unconnected_or_wrong_direction() {
183 let a = synth_finding(0, vec![]);
184 let b = synth_finding(1, vec![link_typed(&a.id, "depends")]);
185 let (a_id, b_id) = (a.id.clone(), b.id.clone());
186 let mut project = assemble("pf2", vec![], 0, 0, "test");
187 project.findings = vec![a, b];
188
189 let g = FrontierGraph::from_project(&project);
190 assert!(shortest_path(&g, &a_id, &b_id, &SUPPORT_KINDS).is_none());
192 assert!(shortest_path(&g, &a_id, "vf_absent", &SUPPORT_KINDS).is_none());
194 }
195
196 #[test]
197 fn same_node_is_zero_hops() {
198 let a = synth_finding(0, vec![]);
199 let a_id = a.id.clone();
200 let mut project = assemble("pf3", vec![], 0, 0, "test");
201 project.findings = vec![a];
202 let g = FrontierGraph::from_project(&project);
203 let p = shortest_path(&g, &a_id, &a_id, &SUPPORT_KINDS).unwrap();
204 assert_eq!(p.hops, 0);
205 assert_eq!(p.nodes, vec![a_id]);
206 }
207
208 #[test]
209 fn kind_filter_excludes_other_relations() {
210 let a = synth_finding(0, vec![]);
213 let b = synth_finding(1, vec![link_typed(&a.id, "depends")]);
214 let c = synth_finding(2, vec![link_typed(&b.id, "contradicts")]);
215 let (a_id, c_id) = (a.id.clone(), c.id.clone());
216 let mut project = assemble("pf4", vec![], 0, 0, "test");
217 project.findings = vec![a, b, c];
218 let g = FrontierGraph::from_project(&project);
219 assert!(shortest_path(&g, &c_id, &a_id, &SUPPORT_KINDS).is_none());
220 }
221}