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 flags + confidence + verifier gate.
172    /// Pure and total. The gate is the substrate's establishment signal on a
173    /// verifier-gated frontier (most math findings carry no human "accept" but
174    /// a passing frozen-verifier attachment), so it is folded in alongside the
175    /// review verdict. Precedence, strongest disqualifier first:
176    /// 1. an adversarial probe refuted the claim (`gate == Refuted`) → `Refuted`;
177    /// 2. a rejected review verdict → `Refuted`;
178    /// 3. a contested/needs-revision verdict or the legacy `contested` flag →
179    ///    `Contested`;
180    /// 4. the verifier gate passed → `Established` unconditionally (a verified
181    ///    finding is not "thin ground", so the confidence floor does not apply);
182    /// 5. else an accepted review verdict → `Established`, or `Fragile` when
183    ///    confidence sits below `FRAGILE_CONFIDENCE` (accepted but thin);
184    /// 6. everything else → `Open`.
185    ///
186    /// `gate` is `None` when no gate was computed (e.g. a graph built without
187    /// attachment context); then only the review verdict drives the state.
188    #[must_use]
189    pub fn derive(
190        flags: &crate::bundle::Flags,
191        confidence: f64,
192        gate: Option<crate::verifier_attachment::GateStatus>,
193    ) -> Self {
194        use crate::bundle::ReviewState;
195        use crate::verifier_attachment::GateStatus;
196        if gate == Some(GateStatus::Refuted) {
197            return Self::Refuted;
198        }
199        match flags.review_state {
200            Some(ReviewState::Rejected) => return Self::Refuted,
201            Some(ReviewState::Contested) | Some(ReviewState::NeedsRevision) => {
202                return Self::Contested;
203            }
204            None if flags.contested => return Self::Contested,
205            _ => {}
206        }
207        // A passing frozen-verifier gate IS the verification: the finding is
208        // Established regardless of the confidence prior (verified is not thin).
209        if gate == Some(GateStatus::Verified) {
210            return Self::Established;
211        }
212        // A human accept of an as-yet-unverified claim establishes it, but stays
213        // Fragile below the confidence floor — accepted, resting on thin ground.
214        if flags.review_state == Some(ReviewState::Accepted) {
215            if confidence < FRAGILE_CONFIDENCE {
216                Self::Fragile
217            } else {
218                Self::Established
219            }
220        } else {
221            Self::Open
222        }
223    }
224
225    /// Verdict-only state derivation (no verifier gate). Equivalent to
226    /// [`Self::derive`] with `gate = None`.
227    #[must_use]
228    pub fn of(flags: &crate::bundle::Flags, confidence: f64) -> Self {
229        Self::derive(flags, confidence, None)
230    }
231}
232
233/// A review-accepted (but not verifier-gated) finding below this confidence is
234/// `Fragile` rather than `Established` — accepted, but resting on thin ground.
235/// The floor does NOT apply to a `gate == Verified` finding: a passing frozen
236/// verifier is the verification, so it is Established at any confidence prior.
237pub const FRAGILE_CONFIDENCE: f64 = 0.6;
238
239/// A claim node: a finding plus the small slice of state the graph
240/// queries report.
241#[derive(Debug, Clone, Serialize)]
242pub struct Node {
243    pub id: String,
244    pub label: String,
245    pub contested: bool,
246    pub gap: bool,
247    pub confidence: f64,
248    /// The product-facing finding state (§6), derived from the verdict +
249    /// confidence at build time so the graph is self-describing for the
250    /// map's state lens and the boundary query.
251    pub state: FindingState,
252}
253
254/// A load-bearing dependency of a claim (GPT §11): a node every (or much) of
255/// the claim's support funnels through. `weight` is how many support nodes
256/// vanish if it is removed; `single_point_of_failure` is true when that is the
257/// claim's entire support.
258#[derive(Debug, Clone, Serialize)]
259pub struct Dominator {
260    pub node: String,
261    pub label: String,
262    /// The dominator's own finding state, when it is a finding in this graph.
263    #[serde(skip_serializing_if = "Option::is_none")]
264    pub state: Option<FindingState>,
265    pub weight: usize,
266    pub single_point_of_failure: bool,
267}
268
269/// Direction of a [`FrontierGraph::blast_radius`] query.
270#[derive(Debug, Clone, Copy, PartialEq, Eq)]
271pub enum BlastDirection {
272    /// What the start rests on: its support, forward over `source → target`.
273    Upstream,
274    /// What rests on the start: its dependents, the impact if it moved.
275    Downstream,
276    /// Both sides.
277    Both,
278}
279
280/// One node reached by a blast-radius traversal, with its hop distance.
281#[derive(Debug, Clone, Serialize)]
282pub struct ReachNode {
283    pub id: String,
284    pub label: String,
285    #[serde(skip_serializing_if = "Option::is_none")]
286    pub state: Option<FindingState>,
287    pub distance: usize,
288}
289
290/// The dependency-impact neighborhood of a claim (memo §7.3, §18.8 — the
291/// dependency-impact "blast radius"): what it rests on (`upstream`) and what
292/// rests on it (`downstream`, the impact if it moved), plus the load-bearing
293/// single points of failure on its support (the minimal-evidence-cut of §13).
294/// A derived view over declared links: relations are candidates, not
295/// adjudicated truth, and the impact is STRUCTURAL — that a result is in the
296/// blast radius is not a claim that it is wrong.
297#[derive(Debug, Clone, Serialize)]
298pub struct BlastRadius {
299    pub center: String,
300    pub center_label: String,
301    #[serde(skip_serializing_if = "Option::is_none")]
302    pub center_state: Option<FindingState>,
303    pub kinds: Vec<&'static str>,
304    pub summary: BlastSummary,
305    pub single_points_of_failure: Vec<Dominator>,
306    pub upstream: Vec<ReachNode>,
307    pub downstream: Vec<ReachNode>,
308}
309
310/// Headline counts for a [`BlastRadius`].
311#[derive(Debug, Clone, Serialize)]
312pub struct BlastSummary {
313    pub upstream: usize,
314    pub downstream: usize,
315    pub max_downstream_distance: usize,
316    pub single_points_of_failure: usize,
317}
318
319impl BlastRadius {
320    /// A stable JSON view, marked derived and structural.
321    #[must_use]
322    pub fn to_json(&self) -> serde_json::Value {
323        let mut v = serde_json::to_value(self).unwrap_or(serde_json::Value::Null);
324        if let serde_json::Value::Object(ref mut m) = v {
325            m.insert("schema".into(), serde_json::json!("vela.blast_radius.v0.1"));
326            m.insert(
327                "claim_boundary".into(),
328                serde_json::json!({
329                    "graph_is_derived": true,
330                    "edges_are_declared_links": true,
331                    "relations_are_candidates_not_adjudicated": true,
332                    "impact_is_structural_not_a_truth_claim": true,
333                }),
334            );
335        }
336        v
337    }
338}
339
340/// `"num/den"` string for a `{0,1}` support coordinate (`"1/1"` present, `"0/1"`
341/// absent) — matches the atlas's coordinate serialization so the two reads are
342/// comparable byte-for-byte. The status layer is corner-valued (support is just
343/// "the support set is non-empty"), so these are the only two coordinates.
344fn coord_string(present: bool) -> String {
345    if present {
346        "1/1".to_string()
347    } else {
348        "0/1".to_string()
349    }
350}
351
352/// The Belnap corner letter of a `(support, refutation)` `{0,1}` pair.
353fn corner_letter(support: bool, refute: bool) -> char {
354    use crate::status_provenance::BelnapStatus;
355    match (support, refute) {
356        (true, true) => BelnapStatus::Both,
357        (true, false) => BelnapStatus::True,
358        (false, true) => BelnapStatus::False,
359        (false, false) => BelnapStatus::None,
360    }
361    .letter()
362}
363
364/// The graded status of the center finding: the canonical bilattice point
365/// `(support kappa, refute kappa)` from `derive_status_provenance`, its conflict
366/// degree `min(x, y)`, and the v1 Belnap corner it thresholds to.
367#[derive(Debug, Clone, Serialize)]
368pub struct GradedStatus {
369    pub support_kappa: String,
370    pub refute_kappa: String,
371    pub conflict: String,
372    pub belnap: char,
373}
374
375/// One dependent whose support kappa genuinely drops when the center's support
376/// is retracted (the retraction theorem applied at the kappa level). A
377/// structurally-reachable dependent with `delta_kappa = 0` has alternative
378/// support and is omitted — the calculus prunes what reachability overcounts.
379#[derive(Debug, Clone, Serialize)]
380pub struct GradedImpact {
381    pub id: String,
382    pub label: String,
383    pub kappa_before: String,
384    pub kappa_after: String,
385    pub delta_kappa: String,
386    /// The center is a single point of failure for this dependent: retracting it
387    /// leaves the dependent with no support (`kappa_after = 0`).
388    pub support_killed: bool,
389}
390
391/// Headline counts for the graded cascade.
392#[derive(Debug, Clone, Serialize)]
393pub struct GradedBlastSummary {
394    pub downstream_candidates: usize,
395    pub weakened: usize,
396    pub killed: usize,
397    pub semiring: &'static str,
398}
399
400/// The calculus reading of a blast radius (memo §7.3, project_true_math_atlas
401/// roadmap #4 — the licensed propagation). Wraps the structural [`BlastRadius`]
402/// with the center's canonical graded status and the genuine downstream impact:
403/// each dependent's support kappa is min-propagated along the dependency edges
404/// (the Bottleneck semiring — "a chain is as strong as its weakest premise"),
405/// computed before and after the center's support is retracted. `delta_kappa`
406/// is the real impact.
407#[derive(Debug, Clone, Serialize)]
408pub struct GradedBlast {
409    pub structural: BlastRadius,
410    pub center_status: GradedStatus,
411    pub impacted: Vec<GradedImpact>,
412    pub summary: GradedBlastSummary,
413}
414
415impl GradedBlast {
416    /// JSON: the structural view, extended with the graded reading and an honest
417    /// boundary on what the calculus does and does not claim here.
418    #[must_use]
419    pub fn to_json(&self) -> serde_json::Value {
420        let mut v = self.structural.to_json();
421        if let serde_json::Value::Object(ref mut m) = v {
422            m.insert(
423                "schema".into(),
424                serde_json::json!("vela.blast_radius.graded.v0.1"),
425            );
426            m.insert(
427                "center_status".into(),
428                serde_json::to_value(&self.center_status).unwrap_or_default(),
429            );
430            m.insert(
431                "graded_impact".into(),
432                serde_json::to_value(&self.impacted).unwrap_or_default(),
433            );
434            m.insert(
435                "graded_summary".into(),
436                serde_json::to_value(&self.summary).unwrap_or_default(),
437            );
438            m.insert(
439                "graded_boundary".into(),
440                serde_json::json!({
441                    "support_kappa": "per-finding canonical support degree — kappa of the support polynomial (derive_status_provenance + the bilattice)",
442                    "propagation": "Bottleneck semiring (max, min): a chain is as strong as its weakest premise — the kernel's licensed reading for dependency support",
443                    "delta_kappa": "the drop in a dependent's support kappa when the center's support is retracted (kappa -> 0); the retraction theorem applied at the kappa level",
444                    "pruning": "a structurally-reachable dependent with delta_kappa = 0 has alternative support and is NOT listed",
445                }),
446            );
447        }
448        v
449    }
450}
451
452/// Memoized Bottleneck-semiring propagation of canonical support along the
453/// dependency edges. On the corner-valued status layer support is `{0,1}`
454/// ("the support set is non-empty"), so the Bottleneck `min` along a chain is
455/// boolean AND — a dependent has propagated support iff itself and every
456/// required premise do. `zeroed` is the retracted center (its support is `false`,
457/// the retraction theorem's effect); pass `""` for the unperturbed pass.
458struct PropCtx<'a> {
459    graph: &'a FrontierGraph,
460    project: &'a Project,
461    kinds: &'a [EdgeKind],
462    zeroed: &'a str,
463    own: HashMap<String, bool>,
464    memo: HashMap<String, bool>,
465}
466
467impl<'a> PropCtx<'a> {
468    fn new(
469        graph: &'a FrontierGraph,
470        project: &'a Project,
471        kinds: &'a [EdgeKind],
472        zeroed: &'a str,
473    ) -> Self {
474        PropCtx {
475            graph,
476            project,
477            kinds,
478            zeroed,
479            own: HashMap::new(),
480            memo: HashMap::new(),
481        }
482    }
483
484    /// The finding's OWN support (canonical, per-finding): `true` iff its support
485    /// set is non-empty, or `false` if it is the retracted center. Memoized.
486    fn own_support(&mut self, d: &str) -> bool {
487        if d == self.zeroed {
488            return false;
489        }
490        if let Some(v) = self.own.get(d) {
491            return *v;
492        }
493        let k = !derive_status_provenance(&self.project.events, d)
494            .support
495            .is_empty();
496        self.own.insert(d.to_string(), k);
497        k
498    }
499
500    /// `prop(d) = own(d) AND (AND over d's dependency premises p of prop(p))`.
501    /// The Bottleneck `min` on `{0,1}` support. Cycle-safe: a node already on the
502    /// path contributes only its own support (no infinite descent).
503    fn prop(&mut self, d: &str, on_path: &mut BTreeSet<String>) -> bool {
504        if let Some(v) = self.memo.get(d) {
505            return *v;
506        }
507        let own = self.own_support(d);
508        if !on_path.insert(d.to_string()) {
509            return own; // d is already on the current path: a cycle
510        }
511        let premises: Vec<String> = self
512            .graph
513            .edges
514            .iter()
515            .filter(|e| e.source == d && self.kinds.contains(&e.kind))
516            .map(|e| e.target.clone())
517            .collect();
518        let mut k = own;
519        for p in premises {
520            k = k && self.prop(&p, on_path);
521        }
522        on_path.remove(d);
523        self.memo.insert(d.to_string(), k);
524        k
525    }
526}
527
528/// The typed claim-level graph for one frontier (or one merged
529/// multi-frontier Project).
530#[derive(Debug, Clone, Default)]
531pub struct FrontierGraph {
532    nodes: BTreeMap<String, Node>,
533    edges: Vec<Edge>,
534}
535
536impl FrontierGraph {
537    /// Build the typed graph from a project's findings and links.
538    /// Every finding becomes a node; every link whose type maps to a
539    /// known [`EdgeKind`] becomes a typed edge.
540    #[must_use]
541    pub fn from_project(project: &Project) -> Self {
542        // Index verifier attachments by target so each finding's state can
543        // fold in its derived gate status — the establishment signal on a
544        // verifier-gated frontier. The gate is recomputed (never a stored
545        // flag), so the graph never trusts a persisted "verified" bit.
546        let mut attachments_by_target: HashMap<
547            &str,
548            Vec<crate::verifier_attachment::VerifierAttachment>,
549        > = HashMap::new();
550        for a in &project.verifier_attachments {
551            attachments_by_target
552                .entry(a.target.as_str())
553                .or_default()
554                .push(a.clone());
555        }
556
557        let mut nodes = BTreeMap::new();
558        for f in &project.findings {
559            let label = f.assertion.text.chars().take(120).collect::<String>();
560            let gate = attachments_by_target.get(f.id.as_str()).map(|atts| {
561                crate::verifier_attachment::derive_gate_status(
562                    &crate::verifier_attachment::claim_digest(&f.assertion.text),
563                    atts,
564                )
565                .status
566            });
567            nodes.insert(
568                f.id.clone(),
569                Node {
570                    id: f.id.clone(),
571                    label,
572                    contested: f.flags.contested,
573                    gap: f.flags.gap,
574                    confidence: f.confidence.score,
575                    state: FindingState::derive(&f.flags, f.confidence.score, gate),
576                },
577            );
578        }
579
580        let mut edges = Vec::new();
581        for f in &project.findings {
582            for link in &f.links {
583                let Some(kind) = EdgeKind::from_link_type(&link.link_type) else {
584                    continue;
585                };
586                // P2 cross-frontier resolution: a `vf_X@vfr_Y` target
587                // resolves to the bare `vf_X` node when that node is
588                // present — which it is under `serve --frontiers <dir>`,
589                // since the merge pulls every frontier's findings into
590                // one Project. Content-addressed ids are globally unique
591                // by content, so collapsing to the bare id is sound and
592                // lets typed traversal compose across frontiers. A
593                // target whose bare id is absent keeps its raw form and
594                // is flagged out-of-frontier.
595                let bare = crate::bundle::bare_finding_id(&link.target);
596                let (target, target_in_frontier) = if nodes.contains_key(bare) {
597                    (bare.to_string(), true)
598                } else {
599                    (link.target.clone(), false)
600                };
601                edges.push(Edge {
602                    source: f.id.clone(),
603                    target,
604                    kind,
605                    note: link.note.clone(),
606                    target_in_frontier,
607                });
608            }
609        }
610
611        Self { nodes, edges }
612    }
613
614    /// Build a typed graph directly from an `(source, target, kind)` edge list,
615    /// for a premise graph that is NOT a findings frontier — e.g. a Mathlib
616    /// declaration-dependency graph (`from --uses--> to`, mapped to
617    /// `DependsOn`). Every endpoint becomes a minimal node (label = id, neutral
618    /// `Open` state, confidence 1.0). The κ-from-events graded cascade
619    /// (`blast_radius_graded`) is NOT meaningful here (no verifier status and no
620    /// events); use the structural `blast_radius` — over a CONJUNCTIVE premise
621    /// graph (every used premise is required) that is also exact, since every
622    /// transitive dependent is genuinely impacted with no alternative route.
623    #[must_use]
624    pub fn from_edges<I>(raw: I) -> Self
625    where
626        I: IntoIterator<Item = (String, String, EdgeKind)>,
627    {
628        let mut nodes: BTreeMap<String, Node> = BTreeMap::new();
629        let mut edges = Vec::new();
630        for (source, target, kind) in raw {
631            for id in [&source, &target] {
632                nodes.entry(id.clone()).or_insert_with(|| Node {
633                    id: id.clone(),
634                    label: id.clone(),
635                    contested: false,
636                    gap: false,
637                    confidence: 1.0,
638                    state: FindingState::Open,
639                });
640            }
641            edges.push(Edge {
642                source,
643                target,
644                kind,
645                note: String::new(),
646                target_in_frontier: true,
647            });
648        }
649        Self { nodes, edges }
650    }
651
652    /// In-degree of every node (count of edges of `kinds` whose target is the
653    /// node), sorted descending — the most-depended-on premises first. The
654    /// highest-in-degree node is the highest-leverage retraction target.
655    #[must_use]
656    pub fn in_degree_ranked(&self, kinds: &[EdgeKind]) -> Vec<(String, usize)> {
657        let mut deg: BTreeMap<String, usize> = BTreeMap::new();
658        for e in &self.edges {
659            if kinds.is_empty() || kinds.contains(&e.kind) {
660                *deg.entry(e.target.clone()).or_default() += 1;
661            }
662        }
663        let mut v: Vec<(String, usize)> = deg.into_iter().collect();
664        v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
665        v
666    }
667
668    /// Number of claim nodes.
669    #[must_use]
670    pub fn node_count(&self) -> usize {
671        self.nodes.len()
672    }
673
674    /// Number of typed edges.
675    #[must_use]
676    pub fn edge_count(&self) -> usize {
677        self.edges.len()
678    }
679
680    /// True iff the node exists in the graph.
681    #[must_use]
682    pub fn contains(&self, id: &str) -> bool {
683        self.nodes.contains_key(id)
684    }
685
686    /// All edges of a given kind.
687    pub fn edges_of_kind(&self, kind: EdgeKind) -> impl Iterator<Item = &Edge> {
688        self.edges.iter().filter(move |e| e.kind == kind)
689    }
690
691    /// All typed edges, in build order. The read accessor the boundary
692    /// query and the path-finder traverse over (they live in sibling
693    /// modules and cannot see the private field).
694    #[must_use]
695    pub fn all_edges(&self) -> &[Edge] {
696        &self.edges
697    }
698
699    /// One node by id, if present.
700    #[must_use]
701    pub fn node(&self, id: &str) -> Option<&Node> {
702        self.nodes.get(id)
703    }
704
705    /// Every node, in stable id order.
706    pub fn nodes(&self) -> impl Iterator<Item = &Node> {
707        self.nodes.values()
708    }
709
710    /// Per-edge-kind counts, for summaries.
711    #[must_use]
712    pub fn edge_kind_counts(&self) -> BTreeMap<&'static str, usize> {
713        let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
714        for e in &self.edges {
715            *counts.entry(e.kind.as_str()).or_default() += 1;
716        }
717        counts
718    }
719
720    /// Unordered, deduplicated contradiction pairs. Because
721    /// `contradicts` is conceptually symmetric but stored as a directed
722    /// link, an `A→B` and a `B→A` contradiction collapse to one pair.
723    /// Endpoints are sorted so the pair is stable.
724    #[must_use]
725    pub fn contradiction_pairs(&self) -> Vec<(String, String)> {
726        let mut pairs = BTreeSet::new();
727        for e in self.edges_of_kind(EdgeKind::Contradicts) {
728            let (a, b) = if e.source <= e.target {
729                (e.source.clone(), e.target.clone())
730            } else {
731                (e.target.clone(), e.source.clone())
732            };
733            pairs.insert((a, b));
734        }
735        pairs.into_iter().collect()
736    }
737
738    /// The transitive closure reachable from `start` following only
739    /// edges of one kind (e.g. the full `improves` or `supersedes`
740    /// lineage downstream of a result). Excludes `start` itself.
741    #[must_use]
742    pub fn closure_of_kind(&self, start: &str, kind: EdgeKind) -> BTreeSet<String> {
743        let mut seen = BTreeSet::new();
744        let mut stack = vec![start.to_string()];
745        while let Some(node) = stack.pop() {
746            for e in self
747                .edges
748                .iter()
749                .filter(|e| e.kind == kind && e.source == node)
750            {
751                if seen.insert(e.target.clone()) {
752                    stack.push(e.target.clone());
753                }
754            }
755        }
756        seen
757    }
758
759    /// Breadth-first exploration outward from `start`, treating edges
760    /// as undirected for reach, up to `max_hops`. Returns each reached
761    /// node's hop distance and the edges wholly inside the explored
762    /// subgraph. This is the engine for multi-hop "deep" queries — the
763    /// counterpart to single-hop neighbor lookups.
764    #[must_use]
765    pub fn explore(&self, start: &str, max_hops: usize) -> Exploration {
766        if !self.nodes.contains_key(start) {
767            return Exploration::default();
768        }
769        // Build undirected adjacency once (O(E)) so the BFS costs
770        // O(reached + incident edges), not a full edge rescan per
771        // frontier node per hop.
772        let mut adj: HashMap<&str, Vec<&str>> = HashMap::new();
773        for e in &self.edges {
774            adj.entry(e.source.as_str()).or_default().push(&e.target);
775            adj.entry(e.target.as_str()).or_default().push(&e.source);
776        }
777        let mut node_hops: BTreeMap<String, usize> = BTreeMap::new();
778        node_hops.insert(start.to_string(), 0);
779        let mut frontier = vec![start.to_string()];
780        for hop in 1..=max_hops {
781            let mut next = Vec::new();
782            for n in &frontier {
783                for &neighbor in adj.get(n.as_str()).into_iter().flatten() {
784                    if !node_hops.contains_key(neighbor) {
785                        node_hops.insert(neighbor.to_string(), hop);
786                        next.push(neighbor.to_string());
787                    }
788                }
789            }
790            if next.is_empty() {
791                break;
792            }
793            frontier = next;
794        }
795        let edges = self
796            .edges
797            .iter()
798            .filter(|e| node_hops.contains_key(&e.source) && node_hops.contains_key(&e.target))
799            .cloned()
800            .collect();
801        Exploration { node_hops, edges }
802    }
803
804    /// Look up a node's label (assertion snippet), if present.
805    #[must_use]
806    pub fn label_of(&self, id: &str) -> Option<&str> {
807        self.nodes.get(id).map(|n| n.label.as_str())
808    }
809
810    /// Support-reachable nodes from `start` following only `kinds`, in stored
811    /// `source → target` direction (the premises `start` rests on), optionally
812    /// removing one node from the graph. Excludes `start` itself.
813    fn support_reach(
814        &self,
815        start: &str,
816        kinds: &[EdgeKind],
817        remove: Option<&str>,
818    ) -> BTreeSet<String> {
819        let mut seen = BTreeSet::new();
820        let mut stack = vec![start.to_string()];
821        while let Some(node) = stack.pop() {
822            for e in &self.edges {
823                if e.source != node || !kinds.contains(&e.kind) {
824                    continue;
825                }
826                if remove == Some(e.target.as_str()) {
827                    continue;
828                }
829                if e.target.as_str() == start {
830                    continue;
831                }
832                if seen.insert(e.target.clone()) {
833                    stack.push(e.target.clone());
834                }
835            }
836        }
837        seen
838    }
839
840    /// The support-graph dominators of a claim (GPT §11): the load-bearing
841    /// dependencies its support funnels through. A node `d` (≠ `z`) is a
842    /// dominator with `weight` = how many of `z`'s support-reachable nodes
843    /// vanish if `d` is removed (including `d` itself). A dominator whose
844    /// weight equals the full support size is a single point of failure —
845    /// every support path out of `z` runs through it. Sorted by weight
846    /// descending, then id. Pure; recomputed on read.
847    #[must_use]
848    pub fn support_dominators(&self, z: &str, kinds: &[EdgeKind]) -> Vec<Dominator> {
849        let full = self.support_reach(z, kinds, None);
850        if full.is_empty() {
851            return vec![];
852        }
853        let total = full.len();
854        let mut doms: Vec<Dominator> = full
855            .iter()
856            .map(|d| {
857                let without = self.support_reach(z, kinds, Some(d));
858                let weight = full.iter().filter(|n| !without.contains(*n)).count();
859                Dominator {
860                    node: d.clone(),
861                    label: self.label_of(d).unwrap_or("").to_string(),
862                    state: self.nodes.get(d).map(|n| n.state),
863                    weight,
864                    single_point_of_failure: weight == total && total >= 2,
865                }
866            })
867            .collect();
868        doms.sort_by(|a, b| b.weight.cmp(&a.weight).then(a.node.cmp(&b.node)));
869        doms
870    }
871
872    /// The default dependency edge kinds for a blast-radius query: the relations
873    /// where the source rests on the target, so removing the target weakens the
874    /// source. Lineage kinds (`Improves`/`Generalizes`/…) are excluded — they
875    /// are not load-bearing dependency.
876    pub const DEPENDENCY_KINDS: [EdgeKind; 4] = [
877        EdgeKind::Supports,
878        EdgeKind::DependsOn,
879        EdgeKind::DerivedFrom,
880        EdgeKind::Discharges,
881    ];
882
883    /// The REQUIRED-premise kinds: a claim's support is *bottlenecked* by these
884    /// (if the premise fails, the claim weakens — the calculus's "weakest
885    /// premise" reading). `Supports` is corroboration (an alternative, not a
886    /// requirement), so it is NOT a bottleneck and is excluded from the graded
887    /// min-propagation: losing one corroboration does not weaken a claim that
888    /// still has another.
889    pub const REQUIRED_PREMISE_KINDS: [EdgeKind; 3] = [
890        EdgeKind::DependsOn,
891        EdgeKind::DerivedFrom,
892        EdgeKind::Discharges,
893    ];
894
895    /// Resolve a query to a node id: an exact id; else an id *prefix* (ids are
896    /// addressed by prefix, like `deep_trace` — a substring match would let a
897    /// bare number like "617" spuriously hit the hex tail of a content-addressed
898    /// id); else the first finding (in id order) whose assertion contains the
899    /// query, case-insensitively, so a problem number or snippet resolves.
900    #[must_use]
901    pub fn find_node(&self, query: &str) -> Option<String> {
902        if self.nodes.contains_key(query) {
903            return Some(query.to_string());
904        }
905        if let Some(n) = self.nodes.values().find(|n| n.id.starts_with(query)) {
906            return Some(n.id.clone());
907        }
908        let q = query.to_lowercase();
909        self.nodes
910            .values()
911            .find(|n| n.label.to_lowercase().contains(&q))
912            .map(|n| n.id.clone())
913    }
914
915    /// Directed reachability from `start` with hop distance, following `kinds`
916    /// either forward (`source → target`, the support `start` rests on) or
917    /// reverse (`target → source`, the dependents that rest on `start`).
918    /// Excludes `start`.
919    fn reach_directed(
920        &self,
921        start: &str,
922        kinds: &[EdgeKind],
923        reverse: bool,
924    ) -> BTreeMap<String, usize> {
925        let mut dist: BTreeMap<String, usize> = BTreeMap::new();
926        dist.insert(start.to_string(), 0);
927        let mut frontier = vec![start.to_string()];
928        let mut hop = 0usize;
929        while !frontier.is_empty() {
930            hop += 1;
931            let mut next = Vec::new();
932            for node in &frontier {
933                for e in &self.edges {
934                    if !kinds.contains(&e.kind) {
935                        continue;
936                    }
937                    let (from, to) = if reverse {
938                        (&e.target, &e.source)
939                    } else {
940                        (&e.source, &e.target)
941                    };
942                    if from != node {
943                        continue;
944                    }
945                    if !dist.contains_key(to) {
946                        dist.insert(to.clone(), hop);
947                        next.push(to.clone());
948                    }
949                }
950            }
951            frontier = next;
952        }
953        dist.remove(start);
954        dist
955    }
956
957    /// Build a sorted [`ReachNode`] list (by distance, then id) from a distance
958    /// map produced by [`Self::reach_directed`].
959    fn reach_nodes(&self, dist: &BTreeMap<String, usize>) -> Vec<ReachNode> {
960        let mut v: Vec<ReachNode> = dist
961            .iter()
962            .map(|(id, &distance)| ReachNode {
963                id: id.clone(),
964                label: self.label_of(id).unwrap_or("").to_string(),
965                state: self.nodes.get(id).map(|n| n.state),
966                distance,
967            })
968            .collect();
969        v.sort_by(|a, b| a.distance.cmp(&b.distance).then(a.id.cmp(&b.id)));
970        v
971    }
972
973    /// The dependency-impact neighborhood of `start` (memo §7.3): `upstream`
974    /// (what it rests on), `downstream` (what rests on it — the blast radius if
975    /// it moved), and the single points of failure on its support. An empty
976    /// `kinds` defaults to [`Self::DEPENDENCY_KINDS`]. Pure; recomputed on read.
977    #[must_use]
978    pub fn blast_radius(
979        &self,
980        start: &str,
981        kinds: &[EdgeKind],
982        direction: BlastDirection,
983    ) -> BlastRadius {
984        let kinds: Vec<EdgeKind> = if kinds.is_empty() {
985            Self::DEPENDENCY_KINDS.to_vec()
986        } else {
987            kinds.to_vec()
988        };
989        let want_up = matches!(direction, BlastDirection::Upstream | BlastDirection::Both);
990        let want_down = matches!(direction, BlastDirection::Downstream | BlastDirection::Both);
991
992        let upstream = if want_up {
993            self.reach_nodes(&self.reach_directed(start, &kinds, false))
994        } else {
995            Vec::new()
996        };
997        let downstream = if want_down {
998            self.reach_nodes(&self.reach_directed(start, &kinds, true))
999        } else {
1000            Vec::new()
1001        };
1002        let single_points_of_failure: Vec<Dominator> = if want_up {
1003            self.support_dominators(start, &kinds)
1004                .into_iter()
1005                .filter(|d| d.single_point_of_failure)
1006                .collect()
1007        } else {
1008            Vec::new()
1009        };
1010        let max_downstream_distance = downstream.iter().map(|n| n.distance).max().unwrap_or(0);
1011        BlastRadius {
1012            center: start.to_string(),
1013            center_label: self.label_of(start).unwrap_or("").to_string(),
1014            center_state: self.nodes.get(start).map(|n| n.state),
1015            kinds: kinds.iter().map(|k| k.as_str()).collect(),
1016            summary: BlastSummary {
1017                upstream: upstream.len(),
1018                downstream: downstream.len(),
1019                max_downstream_distance,
1020                single_points_of_failure: single_points_of_failure.len(),
1021            },
1022            single_points_of_failure,
1023            upstream,
1024            downstream,
1025        }
1026    }
1027
1028    /// The calculus reading of the blast radius (the licensed propagation,
1029    /// project_true_math_atlas roadmap #4): the center's canonical graded status,
1030    /// and for each structural downstream dependent the drop in its support kappa
1031    /// when the center's support is retracted, min-propagated along the dependency
1032    /// edges (the Bottleneck semiring — a chain is as strong as its weakest
1033    /// premise). Needs `project` for the per-finding provenance (events).
1034    /// Dependents whose kappa does not drop are pruned: they have alternative
1035    /// support, so structural reachability overcounted them.
1036    #[must_use]
1037    pub fn blast_radius_graded(
1038        &self,
1039        project: &Project,
1040        start: &str,
1041        kinds: &[EdgeKind],
1042        direction: BlastDirection,
1043    ) -> GradedBlast {
1044        let structural = self.blast_radius(start, kinds, direction);
1045        let center_sp = derive_status_provenance(&project.events, start);
1046        let center_support = !center_sp.support.is_empty();
1047        let center_refute = !center_sp.refute.is_empty();
1048        let center_status = GradedStatus {
1049            support_kappa: coord_string(center_support),
1050            refute_kappa: coord_string(center_refute),
1051            // conflict = min(support, refute) on {0,1} = AND.
1052            conflict: coord_string(center_support && center_refute),
1053            belnap: corner_letter(center_support, center_refute),
1054        };
1055
1056        // The cascade min-propagates over REQUIRED premises only (the structural
1057        // `kinds` govern reachability, but corroborating `supports` is not a
1058        // bottleneck). A dependent reachable only via `supports` therefore does
1059        // not lose support and is pruned.
1060        let mut before = PropCtx::new(self, project, &Self::REQUIRED_PREMISE_KINDS, "");
1061        let mut after = PropCtx::new(self, project, &Self::REQUIRED_PREMISE_KINDS, start);
1062        // `true` first so the support-losing dependents sort ahead; then id.
1063        let mut scored: Vec<(bool, GradedImpact)> = Vec::new();
1064        for node in &structural.downstream {
1065            let b = before.prop(&node.id, &mut BTreeSet::new());
1066            let a = after.prop(&node.id, &mut BTreeSet::new());
1067            // Support genuinely drops only when it was present and is now gone.
1068            if b && !a {
1069                scored.push((
1070                    true,
1071                    GradedImpact {
1072                        id: node.id.clone(),
1073                        label: node.label.clone(),
1074                        kappa_before: coord_string(b),
1075                        kappa_after: coord_string(a),
1076                        delta_kappa: coord_string(b && !a),
1077                        support_killed: !a,
1078                    },
1079                ));
1080            }
1081        }
1082        // strongest impact first, then id for stable ordering
1083        scored.sort_by(|x, y| y.0.cmp(&x.0).then(x.1.id.cmp(&y.1.id)));
1084        let killed = scored.iter().filter(|(_, g)| g.support_killed).count();
1085        let weakened = scored.len();
1086        let impacted: Vec<GradedImpact> = scored.into_iter().map(|(_, g)| g).collect();
1087        let summary = GradedBlastSummary {
1088            downstream_candidates: structural.downstream.len(),
1089            weakened,
1090            killed,
1091            semiring: "bottleneck",
1092        };
1093        GradedBlast {
1094            structural,
1095            center_status,
1096            impacted,
1097            summary,
1098        }
1099    }
1100
1101    /// Serialize to a stable claim-level JSON view. This is a focused
1102    /// `vela.frontier_graph.claims.v0.1` artifact — deliberately
1103    /// distinct from the broad provenance `vela.frontier_graph.v0.1`
1104    /// export so the two are never confused. Always marked derived.
1105    #[must_use]
1106    pub fn to_json(&self) -> serde_json::Value {
1107        let nodes: Vec<&Node> = self.nodes.values().collect();
1108        serde_json::json!({
1109            "schema": "vela.frontier_graph.claims.v0.1",
1110            "summary": {
1111                "nodes": self.node_count(),
1112                "edges": self.edge_count(),
1113                "edge_kinds": self.edge_kind_counts(),
1114                "contradiction_pairs": self.contradiction_pairs().len(),
1115            },
1116            "nodes": nodes,
1117            "edges": self.edges,
1118            "claim_boundary": {
1119                "graph_is_derived": true,
1120                "edges_are_declared_links": true,
1121                "relations_are_candidates_not_adjudicated": true,
1122            },
1123        })
1124    }
1125}
1126
1127/// Result of a multi-hop [`FrontierGraph::explore`]: each reached node
1128/// keyed to its hop distance, plus the edges inside the explored
1129/// subgraph.
1130#[derive(Debug, Clone, Default)]
1131pub struct Exploration {
1132    node_hops: BTreeMap<String, usize>,
1133    pub edges: Vec<Edge>,
1134}
1135
1136impl Exploration {
1137    /// Total nodes reached (including the start node at hop 0).
1138    #[must_use]
1139    pub fn node_count(&self) -> usize {
1140        self.node_hops.len()
1141    }
1142
1143    /// The greatest hop distance reached.
1144    #[must_use]
1145    pub fn max_hop(&self) -> usize {
1146        self.node_hops.values().copied().max().unwrap_or(0)
1147    }
1148
1149    /// Sorted node ids at exactly `hop` distance from the start.
1150    #[must_use]
1151    pub fn nodes_at(&self, hop: usize) -> Vec<&str> {
1152        self.node_hops
1153            .iter()
1154            .filter(|(_, h)| **h == hop)
1155            .map(|(id, _)| id.as_str())
1156            .collect()
1157    }
1158
1159    /// Per-edge-kind counts within the explored subgraph.
1160    #[must_use]
1161    pub fn edge_kind_counts(&self) -> BTreeMap<&'static str, usize> {
1162        let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
1163        for e in &self.edges {
1164            *counts.entry(e.kind.as_str()).or_default() += 1;
1165        }
1166        counts
1167    }
1168}
1169
1170#[cfg(test)]
1171mod tests {
1172    use super::*;
1173    use crate::project::assemble;
1174    use crate::project::reverse_dep_index_tests::{link_to, synth_finding};
1175
1176    fn link_typed(target: &str, link_type: &str) -> crate::bundle::Link {
1177        let mut link = link_to(target);
1178        link.link_type = link_type.into();
1179        link
1180    }
1181
1182    #[test]
1183    fn gate_verified_establishes_regardless_of_confidence() {
1184        use crate::bundle::{Flags, ReviewState};
1185        use crate::verifier_attachment::GateStatus;
1186        // A passing frozen-verifier gate IS the verification: Established even at a
1187        // low confidence prior (verified is not "thin ground").
1188        let flags = Flags::default();
1189        assert_eq!(
1190            FindingState::derive(&flags, 0.3, Some(GateStatus::Verified)),
1191            FindingState::Established,
1192            "gate=Verified at confidence 0.3 must be Established"
1193        );
1194        // A human accept of an as-yet-unverified low-confidence claim stays Fragile
1195        // (the floor applies only to the review-verdict path)…
1196        let accepted = Flags {
1197            review_state: Some(ReviewState::Accepted),
1198            ..Default::default()
1199        };
1200        assert_eq!(
1201            FindingState::derive(&accepted, 0.3, None),
1202            FindingState::Fragile
1203        );
1204        // …and lifts to Established once its confidence clears the floor.
1205        assert_eq!(
1206            FindingState::derive(&accepted, 0.9, None),
1207            FindingState::Established
1208        );
1209    }
1210
1211    #[test]
1212    fn from_edges_builds_a_premise_graph_and_blasts_downstream() {
1213        // A tiny conjunctive premise graph: thm1 and thm2 both use lemma; lemma
1214        // uses prim. Retract `prim` -> impacts lemma, thm1, thm2 (all transitive
1215        // dependents), at depths 1, 2, 2.
1216        let edges = vec![
1217            ("thm1".to_string(), "lemma".to_string(), EdgeKind::DependsOn),
1218            ("thm2".to_string(), "lemma".to_string(), EdgeKind::DependsOn),
1219            ("lemma".to_string(), "prim".to_string(), EdgeKind::DependsOn),
1220        ];
1221        let g = FrontierGraph::from_edges(edges);
1222        assert_eq!(g.node_count(), 4);
1223        assert_eq!(g.edge_count(), 3);
1224        // in-degree: lemma is referenced twice, prim once.
1225        let ranked = g.in_degree_ranked(&[EdgeKind::DependsOn]);
1226        assert_eq!(ranked[0], ("lemma".to_string(), 2));
1227        // downstream of `prim` (the dependents that rest on it) = lemma, thm1, thm2.
1228        let blast = g.blast_radius("prim", &[EdgeKind::DependsOn], BlastDirection::Downstream);
1229        assert_eq!(
1230            blast.summary.downstream, 3,
1231            "all transitive dependents impacted"
1232        );
1233        assert_eq!(blast.summary.max_downstream_distance, 2);
1234        let ids: Vec<&str> = blast.downstream.iter().map(|n| n.id.as_str()).collect();
1235        assert!(ids.contains(&"lemma") && ids.contains(&"thm1") && ids.contains(&"thm2"));
1236        // a leaf (thm1) has no dependents.
1237        let leaf = g.blast_radius("thm1", &[EdgeKind::DependsOn], BlastDirection::Downstream);
1238        assert_eq!(leaf.summary.downstream, 0);
1239    }
1240
1241    #[test]
1242    fn every_valid_link_type_maps_to_an_edge_kind() {
1243        // Drift guard: a link type accepted by validation but unmapped
1244        // here would be silently dropped from the typed graph.
1245        for lt in crate::bundle::VALID_LINK_TYPES {
1246            assert!(
1247                EdgeKind::from_link_type(lt).is_some(),
1248                "VALID_LINK_TYPES has '{lt}' with no EdgeKind mapping"
1249            );
1250        }
1251    }
1252
1253    #[test]
1254    fn maps_all_t7_link_types_to_edge_kinds() {
1255        for (s, k) in [
1256            ("supports", EdgeKind::Supports),
1257            ("contradicts", EdgeKind::Contradicts),
1258            ("depends", EdgeKind::DependsOn),
1259            ("synthesized_from", EdgeKind::DerivedFrom),
1260            ("derived_from", EdgeKind::DerivedFrom),
1261            ("improves", EdgeKind::Improves),
1262            ("generalizes", EdgeKind::Generalizes),
1263            ("specializes", EdgeKind::Specializes),
1264            ("supersedes", EdgeKind::Supersedes),
1265            ("extends", EdgeKind::Extends),
1266            ("replicates", EdgeKind::Replicates),
1267        ] {
1268            assert_eq!(EdgeKind::from_link_type(s), Some(k));
1269        }
1270        assert_eq!(EdgeKind::from_link_type("nonsense"), None);
1271    }
1272
1273    #[test]
1274    fn builds_typed_nodes_and_edges_from_project() {
1275        let base = synth_finding(0, vec![]);
1276        let a = synth_finding(1, vec![link_typed(&base.id, "improves")]);
1277        let b = synth_finding(2, vec![link_typed(&a.id, "supersedes")]);
1278        let (base_id, a_id, b_id) = (base.id.clone(), a.id.clone(), b.id.clone());
1279
1280        let mut project = assemble("fg", vec![], 0, 0, "test");
1281        project.findings = vec![base, a, b];
1282
1283        let g = FrontierGraph::from_project(&project);
1284        assert_eq!(g.node_count(), 3);
1285        assert_eq!(g.edge_count(), 2);
1286        assert!(g.contains(&base_id));
1287
1288        let improves: Vec<&Edge> = g.edges_of_kind(EdgeKind::Improves).collect();
1289        assert_eq!(improves.len(), 1);
1290        assert_eq!(improves[0].source, a_id);
1291        assert_eq!(improves[0].target, base_id);
1292        assert!(improves[0].target_in_frontier);
1293
1294        // a improves base, b supersedes a — closure of `improves` from
1295        // `a` reaches base; supersedes is a different kind.
1296        assert!(
1297            g.closure_of_kind(&a_id, EdgeKind::Improves)
1298                .contains(&base_id)
1299        );
1300        assert!(
1301            g.closure_of_kind(&b_id, EdgeKind::Supersedes)
1302                .contains(&a_id)
1303        );
1304    }
1305
1306    #[test]
1307    fn explore_walks_multiple_hops_with_distances() {
1308        let base = synth_finding(0, vec![]);
1309        let a = synth_finding(1, vec![link_typed(&base.id, "improves")]);
1310        let b = synth_finding(2, vec![link_typed(&a.id, "supersedes")]);
1311        let (base_id, a_id, b_id) = (base.id.clone(), a.id.clone(), b.id.clone());
1312        let mut project = assemble("explore", vec![], 0, 0, "test");
1313        project.findings = vec![base, a, b];
1314
1315        let g = FrontierGraph::from_project(&project);
1316        let ex = g.explore(&base_id, 2);
1317        assert_eq!(ex.node_count(), 3);
1318        assert_eq!(ex.node_hops[&base_id], 0);
1319        assert_eq!(ex.node_hops[&a_id], 1);
1320        assert_eq!(ex.node_hops[&b_id], 2);
1321        assert_eq!(ex.max_hop(), 2);
1322        assert_eq!(ex.nodes_at(1), vec![a_id.as_str()]);
1323
1324        // Bounded by max_hops: depth 1 reaches only the immediate neighbor.
1325        assert_eq!(g.explore(&base_id, 1).node_count(), 2);
1326    }
1327
1328    #[test]
1329    fn support_dominators_find_the_single_point_of_failure() {
1330        // z depends_on a depends_on b: every support path out of z funnels
1331        // through a, so a is a single point of failure (weight = full = 2);
1332        // b is a leaf (weight 1).
1333        let b = synth_finding(0, vec![]);
1334        let a = synth_finding(1, vec![link_typed(&b.id, "depends")]);
1335        let z = synth_finding(2, vec![link_typed(&a.id, "depends")]);
1336        let (a_id, b_id, z_id) = (a.id.clone(), b.id.clone(), z.id.clone());
1337        let mut project = assemble("dom", vec![], 0, 0, "test");
1338        project.findings = vec![b, a, z];
1339
1340        let g = FrontierGraph::from_project(&project);
1341        let doms = g.support_dominators(&z_id, &[EdgeKind::DependsOn]);
1342        // a and b are both reachable; a dominates everything.
1343        let a_dom = doms.iter().find(|d| d.node == a_id).unwrap();
1344        let b_dom = doms.iter().find(|d| d.node == b_id).unwrap();
1345        assert_eq!(a_dom.weight, 2);
1346        assert!(a_dom.single_point_of_failure);
1347        assert_eq!(b_dom.weight, 1);
1348        assert!(!b_dom.single_point_of_failure);
1349        // top dominator is `a`.
1350        assert_eq!(doms.first().unwrap().node, a_id);
1351    }
1352
1353    #[test]
1354    fn support_dominators_empty_for_unsupported_claim() {
1355        let z = synth_finding(0, vec![]);
1356        let z_id = z.id.clone();
1357        let mut project = assemble("dom2", vec![], 0, 0, "test");
1358        project.findings = vec![z];
1359        let g = FrontierGraph::from_project(&project);
1360        assert!(
1361            g.support_dominators(&z_id, &[EdgeKind::DependsOn])
1362                .is_empty()
1363        );
1364    }
1365
1366    #[test]
1367    fn blast_radius_splits_upstream_and_downstream() {
1368        // z depends_on a depends_on b (the same chain as the dominator test).
1369        let b = synth_finding(0, vec![]);
1370        let a = synth_finding(1, vec![link_typed(&b.id, "depends")]);
1371        let z = synth_finding(2, vec![link_typed(&a.id, "depends")]);
1372        let (a_id, b_id, z_id) = (a.id.clone(), b.id.clone(), z.id.clone());
1373        let mut project = assemble("blast", vec![], 0, 0, "test");
1374        project.findings = vec![b, a, z];
1375        let g = FrontierGraph::from_project(&project);
1376
1377        // z rests on a (hop 1) and b (hop 2); nothing rests on z.
1378        let from_z = g.blast_radius(&z_id, &[EdgeKind::DependsOn], BlastDirection::Both);
1379        assert_eq!(from_z.summary.upstream, 2);
1380        assert_eq!(from_z.summary.downstream, 0);
1381        let up_ids: Vec<&str> = from_z.upstream.iter().map(|n| n.id.as_str()).collect();
1382        assert_eq!(up_ids, vec![a_id.as_str(), b_id.as_str()]); // sorted by distance
1383        assert_eq!(from_z.upstream[0].distance, 1);
1384        assert_eq!(from_z.upstream[1].distance, 2);
1385        // a is the single point of failure on z's support.
1386        assert_eq!(from_z.single_points_of_failure.len(), 1);
1387        assert_eq!(from_z.single_points_of_failure[0].node, a_id);
1388
1389        // b is rested on BY a (hop 1) and z (hop 2); it rests on nothing.
1390        let from_b = g.blast_radius(&b_id, &[EdgeKind::DependsOn], BlastDirection::Both);
1391        assert_eq!(from_b.summary.upstream, 0);
1392        assert_eq!(from_b.summary.downstream, 2);
1393        assert_eq!(from_b.summary.max_downstream_distance, 2);
1394        let down_ids: Vec<&str> = from_b.downstream.iter().map(|n| n.id.as_str()).collect();
1395        assert_eq!(down_ids, vec![a_id.as_str(), z_id.as_str()]);
1396
1397        // direction filters: downstream-only yields no upstream work.
1398        let down_only = g.blast_radius(&b_id, &[EdgeKind::DependsOn], BlastDirection::Downstream);
1399        assert!(down_only.upstream.is_empty());
1400        assert_eq!(down_only.downstream.len(), 2);
1401    }
1402
1403    #[test]
1404    fn blast_radius_graded_prunes_unweakened_dependents() {
1405        use crate::events::{EVENT_SCHEMA, NULL_HASH, StateActor, StateEvent, StateTarget};
1406        let asserted = |idx: usize, target: &str| StateEvent {
1407            schema: EVENT_SCHEMA.to_string(),
1408            id: format!("vev_g_{idx:04}"),
1409            kind: "finding.asserted".into(),
1410            target: StateTarget {
1411                r#type: "finding".to_string(),
1412                id: target.to_string(),
1413            },
1414            actor: StateActor {
1415                id: "reviewer:test".to_string(),
1416                r#type: "human".to_string(),
1417            },
1418            timestamp: format!("2026-06-17T00:00:{:02}Z", idx % 60),
1419            reason: "graded blast test".to_string(),
1420            before_hash: NULL_HASH.to_string(),
1421            after_hash: NULL_HASH.to_string(),
1422            payload: serde_json::json!({}),
1423            caveats: vec![],
1424            signature: None,
1425        };
1426
1427        // z depends_on a depends_on b (a required chain); s corroborates b via
1428        // `supports` only (not a required premise). All four are asserted, so
1429        // each has own support kappa = 1.
1430        let b = synth_finding(0, vec![]);
1431        let a = synth_finding(1, vec![link_typed(&b.id, "depends")]);
1432        let z = synth_finding(2, vec![link_typed(&a.id, "depends")]);
1433        let s = synth_finding(3, vec![link_typed(&b.id, "supports")]);
1434        let (a_id, z_id, s_id, b_id) = (a.id.clone(), z.id.clone(), s.id.clone(), b.id.clone());
1435        let mut project = assemble("graded", vec![], 0, 0, "test");
1436        project.events = vec![
1437            asserted(0, &b_id),
1438            asserted(1, &a_id),
1439            asserted(2, &z_id),
1440            asserted(3, &s_id),
1441        ];
1442        project.findings = vec![b, a, z, s];
1443        let g = FrontierGraph::from_project(&project);
1444
1445        let gb = g.blast_radius_graded(&project, &b_id, &[], BlastDirection::Downstream);
1446
1447        // b is supported: center reads T with support kappa 1.
1448        assert_eq!(gb.center_status.belnap, 'T');
1449        assert_eq!(gb.center_status.support_kappa, "1/1");
1450
1451        // Structural downstream of b is {a, z, s}; the graded impact is {a, z}
1452        // only — s corroborates via `supports`, not a required premise, so its
1453        // kappa does not drop (Δκ = 0) and it is pruned.
1454        let ids: Vec<&str> = gb.impacted.iter().map(|i| i.id.as_str()).collect();
1455        assert!(ids.contains(&a_id.as_str()) && ids.contains(&z_id.as_str()));
1456        assert!(
1457            !ids.contains(&s_id.as_str()),
1458            "a supports-only corroborator must be pruned from the graded impact"
1459        );
1460        assert_eq!(gb.summary.downstream_candidates, 3);
1461        assert_eq!(gb.summary.weakened, 2);
1462        assert_eq!(gb.summary.killed, 2);
1463        for imp in &gb.impacted {
1464            assert_eq!(imp.kappa_before, "1/1");
1465            assert_eq!(imp.kappa_after, "0/1");
1466            assert_eq!(imp.delta_kappa, "1/1");
1467            assert!(imp.support_killed);
1468        }
1469    }
1470
1471    #[test]
1472    fn contradiction_pairs_dedupe_symmetrically() {
1473        let x = synth_finding(0, vec![]);
1474        let y = synth_finding(1, vec![link_typed(&x.id, "contradicts")]);
1475        // x also contradicts y (the reverse direction): one pair, not two.
1476        let mut x = x;
1477        x.links.push(link_typed(&y.id, "contradicts"));
1478        let (x_id, y_id) = (x.id.clone(), y.id.clone());
1479
1480        let mut project = assemble("fg-contra", vec![], 0, 0, "test");
1481        project.findings = vec![x, y];
1482
1483        let g = FrontierGraph::from_project(&project);
1484        let pairs = g.contradiction_pairs();
1485        assert_eq!(pairs.len(), 1);
1486        let expected = if x_id <= y_id {
1487            (x_id, y_id)
1488        } else {
1489            (y_id, x_id)
1490        };
1491        assert_eq!(pairs[0], expected);
1492    }
1493
1494    #[test]
1495    fn cross_frontier_target_is_flagged_out_of_frontier() {
1496        let f = synth_finding(
1497            0,
1498            vec![link_typed("vf_abcdef0123456789@vfr_remote", "supports")],
1499        );
1500        let mut project = assemble("fg-xf", vec![], 0, 0, "test");
1501        project.findings = vec![f];
1502
1503        let g = FrontierGraph::from_project(&project);
1504        let edge = g.edges_of_kind(EdgeKind::Supports).next().unwrap();
1505        assert!(!edge.target_in_frontier);
1506    }
1507
1508    #[test]
1509    fn cross_frontier_link_resolves_in_merged_project() {
1510        // Simulates `serve --frontiers <dir>`: the remote target's
1511        // finding is present in the merged Project, so a `@vfr_…` link
1512        // resolves to the bare node and composes for traversal (P2).
1513        let remote = synth_finding(0, vec![]);
1514        let cross_target = format!("{}@vfr_remote", remote.id);
1515        let local = synth_finding(1, vec![link_typed(&cross_target, "depends")]);
1516        let (remote_id, local_id) = (remote.id.clone(), local.id.clone());
1517
1518        let mut project = assemble("fg-merge", vec![], 0, 0, "test");
1519        project.findings = vec![remote, local];
1520
1521        let g = FrontierGraph::from_project(&project);
1522        let edge = g.edges_of_kind(EdgeKind::DependsOn).next().unwrap();
1523        assert!(edge.target_in_frontier, "bare id present → resolves");
1524        assert_eq!(edge.target, remote_id, "target rewritten to bare id");
1525        // Traversal now composes across the former frontier boundary.
1526        assert!(
1527            g.closure_of_kind(&local_id, EdgeKind::DependsOn)
1528                .contains(&remote_id)
1529        );
1530    }
1531
1532    #[test]
1533    fn to_json_is_marked_derived_with_claim_boundary() {
1534        let project = assemble("fg-json", vec![], 0, 0, "test");
1535        let g = FrontierGraph::from_project(&project);
1536        let v = g.to_json();
1537        assert_eq!(v["schema"], "vela.frontier_graph.claims.v0.1");
1538        assert_eq!(v["claim_boundary"]["graph_is_derived"], true);
1539        assert_eq!(
1540            v["claim_boundary"]["relations_are_candidates_not_adjudicated"],
1541            true
1542        );
1543    }
1544}