Skip to main content

vela_protocol/analysis/
frontier_graph.rs

1//! T7: the typed claim-level edge layer — the FrontierGraph substrate.
2//!
3//! The full `.vela/graph/frontier-graph.v1.json` export is a broad
4//! provenance graph (findings, sources, events, proposals, evidence
5//! atoms — tens of thousands of nodes) built by the Python tooling.
6//! This module is the *claim-level* view T7 reasons over: findings as
7//! nodes (Claim nodes), and the typed relations between them
8//! (`SUPPORTS / CONTRADICTS / DEPENDS_ON / DERIVED_FROM / IMPROVES /
9//! GENERALIZES / SPECIALIZES / SUPERSEDES`, plus the legacy `EXTENDS`
10//! and `REPLICATES`) as typed edges.
11//!
12//! It is a derived view, like [`crate::project::ReverseDepIndex`]: built
13//! from the canonical findings + links, never an authority. Where a causal
14//! closure keeps only the `depends`/`supports` subset, the FrontierGraph
15//! keeps *every* typed relation so queries like "which contradictions are
16//! open" and "what improves this result" are first-class.
17//!
18//! Cross-frontier (`vf_…@vfr_…`) targets are recorded as edges to an
19//! external node id but are not resolved here — cross-frontier
20//! traversal is a separate step (P2). Within a single merged Project,
21//! though, every endpoint that exists is linked.
22
23use std::collections::{BTreeMap, BTreeSet, HashMap};
24
25use serde::Serialize;
26
27use crate::evidence_diff::derive_status_provenance;
28use crate::project::Project;
29
30/// The canonical T7 relation vocabulary. Each variant maps to one or
31/// more `link_type` strings from [`crate::bundle::VALID_LINK_TYPES`].
32#[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    /// A cross-domain transfer (`vtr_`): the source claim discharges a premise
46    /// of the target claim via a kernel-verified verifier-homomorphism.
47    Discharges,
48}
49
50impl EdgeKind {
51    /// Map a stored `link_type` string to its canonical edge kind.
52    /// `depends` is DEPENDS_ON and `synthesized_from` is DERIVED_FROM;
53    /// unknown strings return `None` (the link is skipped from the
54    /// typed graph rather than silently mis-categorized).
55    #[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            // A cross-problem reduction "A implies B" means B's resolution rests
70            // on A (solving A solves B), so it participates in the dependency
71            // blast-radius exactly as `depends`. Mapped onto the existing
72            // `DependsOn` kind (no new variant, so no wire-format change), which
73            // is what makes the `implies` links the ingest already mints become
74            // real typed graph edges instead of being silently dropped.
75            "implies" => Self::DependsOn,
76            _ => return None,
77        })
78    }
79
80    /// Lowercase canonical string for this edge kind.
81    #[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    /// Every edge kind, for enumeration and parsing.
99    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    /// Parse from either the canonical string ([`Self::as_str`]) or a
114    /// raw `link_type` ([`Self::from_link_type`]).
115    #[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/// A typed, directed edge between two claim nodes. `target` may be a
126/// cross-frontier id (`vf_…@vfr_…`); `target_in_frontier` records
127/// whether the endpoint resolves to a node present in this graph.
128#[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/// The product-facing state of a finding (memo §6) — **Plane 2** of the four
138/// status planes (see `docs/THEORY.md` Part II §24): distinct from the cross-source
139/// resolution words (Plane 1), the Belnap/bilattice epistemic status (Plane 3),
140/// and the review-lifecycle signals (Plane 4). A pure, derived classification
141/// of a finding's review verdict + confidence into the five words the platform
142/// speaks — never persisted, recomputed on read.
143/// `Refuted`/`Contested` are live disagreement; `Fragile` is established
144/// but thin; `Established` is accepted with real support; `Open` is the
145/// default working state. State is orthogonal to the verifier gate: it
146/// reads the *review* verdict, not the trust gate, and never collapses
147/// to green/red (§8).
148#[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    /// Lowercase canonical string.
160    #[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    /// Derive a finding's state from its review flags and confidence.
172    /// Pure and total. Precedence, strongest disqualifier first:
173    /// 1. a rejected review verdict → `Refuted`;
174    /// 2. a contested/needs-revision verdict or the legacy `contested` flag →
175    ///    `Contested`;
176    /// 3. an accepted review verdict → `Established`, or `Fragile` when
177    ///    confidence sits below `FRAGILE_CONFIDENCE` (accepted but thin);
178    /// 4. everything else → `Open`.
179    ///
180    /// Verifier-gate status is deliberately excluded. Verification and review
181    /// authority are orthogonal planes: a frozen verifier can establish that
182    /// its method accepted the claim, but only a review verdict can change this
183    /// product-facing review state.
184    #[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    /// Explicit verdict-only alias retained for callers that use the review
207    /// plane directly.
208    #[must_use]
209    pub fn of(flags: &crate::bundle::Flags, confidence: f64) -> Self {
210        Self::derive(flags, confidence)
211    }
212}
213
214/// A review-accepted finding below this confidence is
215/// `Fragile` rather than `Established` — accepted, but resting on thin ground.
216pub const FRAGILE_CONFIDENCE: f64 = 0.6;
217
218/// A claim node: a finding plus the small slice of state the graph
219/// queries report.
220#[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    /// The product-facing finding state (§6), derived from the verdict +
228    /// confidence at build time so the graph is self-describing for the
229    /// map's state lens and the boundary query.
230    pub state: FindingState,
231}
232
233/// A load-bearing dependency of a claim (GPT §11): a node every (or much) of
234/// the claim's support funnels through. `weight` is how many support nodes
235/// vanish if it is removed; `single_point_of_failure` is true when that is the
236/// claim's entire support.
237#[derive(Debug, Clone, Serialize)]
238pub struct Dominator {
239    pub node: String,
240    pub label: String,
241    /// The dominator's own finding state, when it is a finding in this graph.
242    #[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/// Direction of a [`FrontierGraph::blast_radius`] query.
249#[derive(Debug, Clone, Copy, PartialEq, Eq)]
250pub enum BlastDirection {
251    /// What the start rests on: its support, forward over `source → target`.
252    Upstream,
253    /// What rests on the start: its dependents, the impact if it moved.
254    Downstream,
255    /// Both sides.
256    Both,
257}
258
259/// One node reached by a blast-radius traversal, with its hop distance.
260#[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/// The dependency-impact neighborhood of a claim (memo §7.3, §18.8 — the
270/// dependency-impact "blast radius"): what it rests on (`upstream`) and what
271/// rests on it (`downstream`, the impact if it moved), plus the load-bearing
272/// single points of failure on its support (the minimal-evidence-cut of §13).
273/// A derived view over declared links: relations are candidates, not
274/// adjudicated truth, and the impact is STRUCTURAL — that a result is in the
275/// blast radius is not a claim that it is wrong.
276#[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/// Headline counts for a [`BlastRadius`].
290#[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    /// A stable JSON view, marked derived and structural.
300    #[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
319/// `"num/den"` string for a `{0,1}` support coordinate (`"1/1"` present, `"0/1"`
320/// absent) — matches the atlas's coordinate serialization so the two reads are
321/// comparable byte-for-byte. The status layer is corner-valued (support is just
322/// "the support set is non-empty"), so these are the only two coordinates.
323fn coord_string(present: bool) -> String {
324    if present {
325        "1/1".to_string()
326    } else {
327        "0/1".to_string()
328    }
329}
330
331/// The Belnap corner letter of a `(support, refutation)` `{0,1}` pair.
332fn 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/// The graded status of the center finding: the canonical bilattice point
344/// `(support kappa, refute kappa)` from `derive_status_provenance`, its conflict
345/// degree `min(x, y)`, and the v1 Belnap corner it thresholds to.
346#[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/// One dependent whose support kappa genuinely drops when the center's support
355/// is retracted (the retraction theorem applied at the kappa level). A
356/// structurally-reachable dependent with `delta_kappa = 0` has alternative
357/// support and is omitted — the calculus prunes what reachability overcounts.
358#[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    /// The center is a single point of failure for this dependent: retracting it
366    /// leaves the dependent with no support (`kappa_after = 0`).
367    pub support_killed: bool,
368}
369
370/// Headline counts for the graded cascade.
371#[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/// The calculus reading of a blast radius (memo §7.3, project_true_math_atlas
380/// roadmap #4 — the licensed propagation). Wraps the structural [`BlastRadius`]
381/// with the center's canonical graded status and the genuine downstream impact:
382/// each dependent's support kappa is min-propagated along the dependency edges
383/// (the Bottleneck semiring — "a chain is as strong as its weakest premise"),
384/// computed before and after the center's support is retracted. `delta_kappa`
385/// is the real impact.
386#[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    /// JSON: the structural view, extended with the graded reading and an honest
396    /// boundary on what the calculus does and does not claim here.
397    #[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
431/// Memoized Bottleneck-semiring propagation of canonical support along the
432/// dependency edges. On the corner-valued status layer support is `{0,1}`
433/// ("the support set is non-empty"), so the Bottleneck `min` along a chain is
434/// boolean AND — a dependent has propagated support iff itself and every
435/// required premise do. `zeroed` is the retracted center (its support is `false`,
436/// the retraction theorem's effect); pass `""` for the unperturbed pass.
437struct 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    /// The finding's OWN support (canonical, per-finding): `true` iff its support
464    /// set is non-empty, or `false` if it is the retracted center. Memoized.
465    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    /// `prop(d) = own(d) AND (AND over d's dependency premises p of prop(p))`.
480    /// The Bottleneck `min` on `{0,1}` support. Cycle-safe: a node already on the
481    /// path contributes only its own support (no infinite descent).
482    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; // d is already on the current path: a cycle
489        }
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/// The typed claim-level graph for one frontier (or one merged
508/// multi-frontier Project).
509#[derive(Debug, Clone, Default)]
510pub struct FrontierGraph {
511    nodes: BTreeMap<String, Node>,
512    edges: Vec<Edge>,
513}
514
515impl FrontierGraph {
516    /// Build the typed graph from a project's findings and links.
517    /// Every finding becomes a node; every link whose type maps to a
518    /// known [`EdgeKind`] becomes a typed edge.
519    #[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                // P2 cross-frontier resolution: a `vf_X@vfr_Y` target
544                // resolves to the bare `vf_X` node when that node is
545                // present — which it is under `serve --frontiers <dir>`,
546                // since the merge pulls every frontier's findings into
547                // one Project. Content-addressed ids are globally unique
548                // by content, so collapsing to the bare id is sound and
549                // lets typed traversal compose across frontiers. A
550                // target whose bare id is absent keeps its raw form and
551                // is flagged out-of-frontier.
552                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    /// Build a typed graph directly from an `(source, target, kind)` edge list,
572    /// for a premise graph that is NOT a findings frontier — e.g. a Mathlib
573    /// declaration-dependency graph (`from --uses--> to`, mapped to
574    /// `DependsOn`). Every endpoint becomes a minimal node (label = id, neutral
575    /// `Open` state, confidence 1.0). The κ-from-events graded cascade
576    /// (`blast_radius_graded`) is NOT meaningful here (no verifier status and no
577    /// events); use the structural `blast_radius` — over a CONJUNCTIVE premise
578    /// graph (every used premise is required) that is also exact, since every
579    /// transitive dependent is genuinely impacted with no alternative route.
580    #[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    /// In-degree of every node (count of edges of `kinds` whose target is the
610    /// node), sorted descending — the most-depended-on premises first. The
611    /// highest-in-degree node is the highest-leverage retraction target.
612    #[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    /// Number of claim nodes.
626    #[must_use]
627    pub fn node_count(&self) -> usize {
628        self.nodes.len()
629    }
630
631    /// Number of typed edges.
632    #[must_use]
633    pub fn edge_count(&self) -> usize {
634        self.edges.len()
635    }
636
637    /// True iff the node exists in the graph.
638    #[must_use]
639    pub fn contains(&self, id: &str) -> bool {
640        self.nodes.contains_key(id)
641    }
642
643    /// All edges of a given kind.
644    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    /// All typed edges, in build order. The read accessor the boundary
649    /// query and the path-finder traverse over (they live in sibling
650    /// modules and cannot see the private field).
651    #[must_use]
652    pub fn all_edges(&self) -> &[Edge] {
653        &self.edges
654    }
655
656    /// One node by id, if present.
657    #[must_use]
658    pub fn node(&self, id: &str) -> Option<&Node> {
659        self.nodes.get(id)
660    }
661
662    /// Every node, in stable id order.
663    pub fn nodes(&self) -> impl Iterator<Item = &Node> {
664        self.nodes.values()
665    }
666
667    /// Per-edge-kind counts, for summaries.
668    #[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    /// Unordered, deduplicated contradiction pairs. Because
678    /// `contradicts` is conceptually symmetric but stored as a directed
679    /// link, an `A→B` and a `B→A` contradiction collapse to one pair.
680    /// Endpoints are sorted so the pair is stable.
681    #[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    /// The transitive closure reachable from `start` following only
696    /// edges of one kind (e.g. the full `improves` or `supersedes`
697    /// lineage downstream of a result). Excludes `start` itself.
698    #[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    /// Breadth-first exploration outward from `start`, treating edges
717    /// as undirected for reach, up to `max_hops`. Returns each reached
718    /// node's hop distance and the edges wholly inside the explored
719    /// subgraph. This is the engine for multi-hop "deep" queries — the
720    /// counterpart to single-hop neighbor lookups.
721    #[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        // Build undirected adjacency once (O(E)) so the BFS costs
727        // O(reached + incident edges), not a full edge rescan per
728        // frontier node per hop.
729        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    /// Look up a node's label (assertion snippet), if present.
762    #[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    /// Support-reachable nodes from `start` following only `kinds`, in stored
768    /// `source → target` direction (the premises `start` rests on), optionally
769    /// removing one node from the graph. Excludes `start` itself.
770    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    /// The support-graph dominators of a claim (GPT §11): the load-bearing
798    /// dependencies its support funnels through. A node `d` (≠ `z`) is a
799    /// dominator with `weight` = how many of `z`'s support-reachable nodes
800    /// vanish if `d` is removed (including `d` itself). A dominator whose
801    /// weight equals the full support size is a single point of failure —
802    /// every support path out of `z` runs through it. Sorted by weight
803    /// descending, then id. Pure; recomputed on read.
804    #[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    /// The default dependency edge kinds for a blast-radius query: the relations
830    /// where the source rests on the target, so removing the target weakens the
831    /// source. Lineage kinds (`Improves`/`Generalizes`/…) are excluded — they
832    /// are not load-bearing dependency.
833    pub const DEPENDENCY_KINDS: [EdgeKind; 4] = [
834        EdgeKind::Supports,
835        EdgeKind::DependsOn,
836        EdgeKind::DerivedFrom,
837        EdgeKind::Discharges,
838    ];
839
840    /// The REQUIRED-premise kinds: a claim's support is *bottlenecked* by these
841    /// (if the premise fails, the claim weakens — the calculus's "weakest
842    /// premise" reading). `Supports` is corroboration (an alternative, not a
843    /// requirement), so it is NOT a bottleneck and is excluded from the graded
844    /// min-propagation: losing one corroboration does not weaken a claim that
845    /// still has another.
846    pub const REQUIRED_PREMISE_KINDS: [EdgeKind; 3] = [
847        EdgeKind::DependsOn,
848        EdgeKind::DerivedFrom,
849        EdgeKind::Discharges,
850    ];
851
852    /// Resolve a query to a node id: an exact id; else an id *prefix* (ids are
853    /// addressed by prefix, like `deep_trace` — a substring match would let a
854    /// bare number like "617" spuriously hit the hex tail of a content-addressed
855    /// id); else the first finding (in id order) whose assertion contains the
856    /// query, case-insensitively, so a problem number or snippet resolves.
857    #[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    /// Directed reachability from `start` with hop distance, following `kinds`
873    /// either forward (`source → target`, the support `start` rests on) or
874    /// reverse (`target → source`, the dependents that rest on `start`).
875    /// Excludes `start`.
876    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    /// Build a sorted [`ReachNode`] list (by distance, then id) from a distance
915    /// map produced by [`Self::reach_directed`].
916    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    /// The dependency-impact neighborhood of `start` (memo §7.3): `upstream`
931    /// (what it rests on), `downstream` (what rests on it — the blast radius if
932    /// it moved), and the single points of failure on its support. An empty
933    /// `kinds` defaults to [`Self::DEPENDENCY_KINDS`]. Pure; recomputed on read.
934    #[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    /// The calculus reading of the blast radius (the licensed propagation,
986    /// project_true_math_atlas roadmap #4): the center's canonical graded status,
987    /// and for each structural downstream dependent the drop in its support kappa
988    /// when the center's support is retracted, min-propagated along the dependency
989    /// edges (the Bottleneck semiring — a chain is as strong as its weakest
990    /// premise). Needs `project` for the per-finding provenance (events).
991    /// Dependents whose kappa does not drop are pruned: they have alternative
992    /// support, so structural reachability overcounted them.
993    #[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 = min(support, refute) on {0,1} = AND.
1009            conflict: coord_string(center_support && center_refute),
1010            belnap: corner_letter(center_support, center_refute),
1011        };
1012
1013        // The cascade min-propagates over REQUIRED premises only (the structural
1014        // `kinds` govern reachability, but corroborating `supports` is not a
1015        // bottleneck). A dependent reachable only via `supports` therefore does
1016        // not lose support and is pruned.
1017        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        // `true` first so the support-losing dependents sort ahead; then id.
1020        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            // Support genuinely drops only when it was present and is now gone.
1025            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        // strongest impact first, then id for stable ordering
1040        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    /// Serialize to a stable claim-level JSON view. This is a focused
1059    /// `vela.frontier_graph.claims.v0.1` artifact — deliberately
1060    /// distinct from the broad provenance `vela.frontier_graph.v0.1`
1061    /// export so the two are never confused. Always marked derived.
1062    #[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/// Result of a multi-hop [`FrontierGraph::explore`]: each reached node
1085/// keyed to its hop distance, plus the edges inside the explored
1086/// subgraph.
1087#[derive(Debug, Clone, Default)]
1088pub struct Exploration {
1089    node_hops: BTreeMap<String, usize>,
1090    pub edges: Vec<Edge>,
1091}
1092
1093impl Exploration {
1094    /// Total nodes reached (including the start node at hop 0).
1095    #[must_use]
1096    pub fn node_count(&self) -> usize {
1097        self.node_hops.len()
1098    }
1099
1100    /// The greatest hop distance reached.
1101    #[must_use]
1102    pub fn max_hop(&self) -> usize {
1103        self.node_hops.values().copied().max().unwrap_or(0)
1104    }
1105
1106    /// Sorted node ids at exactly `hop` distance from the start.
1107    #[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    /// Per-edge-kind counts within the explored subgraph.
1117    #[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        // A tiny conjunctive premise graph: thm1 and thm2 both use lemma; lemma
1215        // uses prim. Retract `prim` -> impacts lemma, thm1, thm2 (all transitive
1216        // dependents), at depths 1, 2, 2.
1217        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        // in-degree: lemma is referenced twice, prim once.
1226        let ranked = g.in_degree_ranked(&[EdgeKind::DependsOn]);
1227        assert_eq!(ranked[0], ("lemma".to_string(), 2));
1228        // downstream of `prim` (the dependents that rest on it) = lemma, thm1, thm2.
1229        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        // a leaf (thm1) has no dependents.
1238        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        // Drift guard: a link type accepted by validation but unmapped
1245        // here would be silently dropped from the typed graph.
1246        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        // a improves base, b supersedes a — closure of `improves` from
1296        // `a` reaches base; supersedes is a different kind.
1297        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        // Bounded by max_hops: depth 1 reaches only the immediate neighbor.
1326        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        // z depends_on a depends_on b: every support path out of z funnels
1332        // through a, so a is a single point of failure (weight = full = 2);
1333        // b is a leaf (weight 1).
1334        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        // a and b are both reachable; a dominates everything.
1344        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        // top dominator is `a`.
1351        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        // z depends_on a depends_on b (the same chain as the dominator test).
1370        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        // z rests on a (hop 1) and b (hop 2); nothing rests on z.
1379        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()]); // sorted by distance
1384        assert_eq!(from_z.upstream[0].distance, 1);
1385        assert_eq!(from_z.upstream[1].distance, 2);
1386        // a is the single point of failure on z's support.
1387        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        // b is rested on BY a (hop 1) and z (hop 2); it rests on nothing.
1391        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        // direction filters: downstream-only yields no upstream work.
1399        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        // z depends_on a depends_on b (a required chain); s corroborates b via
1429        // `supports` only (not a required premise). All four are asserted, so
1430        // each has own support kappa = 1.
1431        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        // b is supported: center reads T with support kappa 1.
1449        assert_eq!(gb.center_status.belnap, 'T');
1450        assert_eq!(gb.center_status.support_kappa, "1/1");
1451
1452        // Structural downstream of b is {a, z, s}; the graded impact is {a, z}
1453        // only — s corroborates via `supports`, not a required premise, so its
1454        // kappa does not drop (Δκ = 0) and it is pruned.
1455        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        // x also contradicts y (the reverse direction): one pair, not two.
1477        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        // Simulates `serve --frontiers <dir>`: the remote target's
1512        // finding is present in the merged Project, so a `@vfr_…` link
1513        // resolves to the bare node and composes for traversal (P2).
1514        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        // Traversal now composes across the former frontier boundary.
1527        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}