Skip to main content

vela_protocol/analysis/
pathfind.rs

1//! The golden-thread engine (memo §11.7): the shortest support/reduction
2//! path between two findings over the typed [`FrontierGraph`].
3//!
4//! A "golden thread" is the chain of reasoning that connects one result to
5//! another — the sequence of supports, dependencies, and verifier-homomorphism
6//! discharges that carries trust from a premise to a conclusion. This module
7//! is a pure breadth-first search over the typed claim graph: it follows only
8//! the support-bearing edge kinds (in their stored `source → target`
9//! direction, i.e. "this rests on that"), so the first path it finds is a
10//! shortest one. It is a derived view — it reports the declared links, it does
11//! not adjudicate them.
12
13use serde::Serialize;
14use std::collections::{HashMap, VecDeque};
15
16use crate::frontier_graph::{Edge, EdgeKind, FrontierGraph};
17
18/// The edge kinds that carry support or reduction. Following these from a
19/// finding walks toward the premises it rests on (`A depends_on B`,
20/// `A derived_from B`, `A discharges B`'s premise, `A improves/supports B`).
21/// This is the default thread vocabulary; callers may pass a narrower set.
22pub const SUPPORT_KINDS: [EdgeKind; 5] = [
23    EdgeKind::Supports,
24    EdgeKind::DependsOn,
25    EdgeKind::DerivedFrom,
26    EdgeKind::Discharges,
27    EdgeKind::Improves,
28];
29
30/// One edge traversed on a path.
31#[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/// A shortest support/reduction path from `from` to `to`.
40#[derive(Debug, Clone, Serialize)]
41pub struct Path {
42    pub from: String,
43    pub to: String,
44    /// Node ids in order, `from` first and `to` last.
45    pub nodes: Vec<String>,
46    /// The edges traversed, one per hop.
47    pub steps: Vec<PathStep>,
48    /// Number of edges (= `nodes.len() - 1`).
49    pub hops: usize,
50}
51
52impl Path {
53    /// Stable JSON for the web golden-thread surface and the CLI.
54    #[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/// Shortest directed path from `from` to `to` following only edges whose
69/// kind is in `kinds`, in their stored `source → target` direction. BFS, so
70/// the first path discovered is a shortest one (fewest hops). Returns `None`
71/// when either endpoint is absent or no such path exists.
72#[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    // Directed adjacency restricted to the requested kinds, built once.
93    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    // BFS, recording the edge that first reached each node so the path can
101    // be reconstructed backward from `to`.
102    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
124/// Walk the predecessor map backward from `to` to `from`, then reverse.
125fn 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        // c depends_on b depends_on a — the thread from c reaches a in 2 hops.
166        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        // b depends_on a, so a → b is against the edge direction: no path.
191        assert!(shortest_path(&g, &a_id, &b_id, &SUPPORT_KINDS).is_none());
192        // Absent endpoint.
193        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        // c contradicts b depends_on a — a contradicts edge is not a support
211        // edge, so no support thread from c to a.
212        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}