Skip to main content

lean_ctx/core/semantic/
evidence.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Typed evidence attached to graph edges (`Edge.metadata`).
3//!
4//! An edge says *that* two things are related; its evidence says *how sure*
5//! lean-ctx is. Consumers weight edges by grade instead of treating a name
6//! match and a compiler-verified call as equal.
7
8use serde::{Deserialize, Serialize};
9
10use crate::core::call_graph::ScopeMatch;
11
12/// Strength of a relationship, weakest first (`Ord` = strength).
13#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
14#[serde(rename_all = "snake_case")]
15pub enum EvidenceGrade {
16    /// Plausible by name only (e.g. a name unique in the project but not in
17    /// the caller's scope — could still be an external function).
18    HeuristicStructural,
19    /// Bound by the caller's own scope (same file / unique import).
20    ResolvedStructural,
21    /// A local semantic backend (language server / IDE) resolved it.
22    VerifiedSemantic,
23}
24
25impl EvidenceGrade {
26    pub fn from_scope(via: ScopeMatch) -> Self {
27        match via {
28            ScopeMatch::SameFile | ScopeMatch::UniqueImport => Self::ResolvedStructural,
29            ScopeMatch::UniqueInProject => Self::HeuristicStructural,
30        }
31    }
32
33    pub fn as_str(self) -> &'static str {
34        match self {
35            Self::HeuristicStructural => "heuristic",
36            Self::ResolvedStructural => "resolved",
37            Self::VerifiedSemantic => "verified",
38        }
39    }
40
41    /// Multiplier applied to an edge kind's weight in ranking/impact scoring.
42    /// Scope-bound and verified edges count fully; a name-only guess counts
43    /// less so it cannot outrank real relationships.
44    pub fn weight_factor(self) -> f64 {
45        match self {
46            Self::HeuristicStructural => 0.5,
47            Self::ResolvedStructural | Self::VerifiedSemantic => 1.0,
48        }
49    }
50}
51
52/// Which producer derives an edge. Each producer owns only its own
53/// [`Contribution`]; see [`EdgeEvidence::merge`] and [`EdgeEvidence::without`].
54#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Serialize, Deserialize)]
55#[serde(rename_all = "snake_case")]
56pub enum EvidenceOrigin {
57    /// Graph enrichment (call-graph consolidation + semantic escalation).
58    #[default]
59    Enrichment,
60    /// The `ctx_impact` index builder.
61    ImpactIndex,
62}
63
64/// One producer's evidence for an edge.
65#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
66pub struct Contribution {
67    pub origin: EvidenceOrigin,
68    pub grade: EvidenceGrade,
69    /// Semantic backend identity (`lsp:rust-analyzer@1.0`) for verified edges.
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub backend: Option<String>,
72    /// Number of call sites supporting this edge.
73    pub sites: u32,
74}
75
76/// Serialized into `Edge.metadata`. Deliberately small and deterministic: no
77/// timestamps, no source text, no paths beyond the edge's own endpoints.
78///
79/// Several producers can derive the same edge; each keeps its own
80/// contribution, so a recompute or withdrawal by one never erases or
81/// downgrades what another one established.
82#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
83pub struct EdgeEvidence {
84    /// Schema version of this record.
85    pub v: u8,
86    /// Strongest contribution — what ranking and impact weight by.
87    pub grade: EvidenceGrade,
88    /// Every producer currently deriving the edge, sorted by origin.
89    pub by: Vec<Contribution>,
90}
91
92impl EdgeEvidence {
93    pub const VERSION: u8 = 1;
94
95    /// Evidence from a single producer.
96    pub fn new(
97        grade: EvidenceGrade,
98        origin: EvidenceOrigin,
99        backend: Option<String>,
100        sites: u32,
101    ) -> Self {
102        Self {
103            v: Self::VERSION,
104            grade,
105            by: vec![Contribution {
106                origin,
107                grade,
108                backend,
109                sites,
110            }],
111        }
112    }
113
114    fn from_contributions(mut by: Vec<Contribution>) -> Option<Self> {
115        by.sort_by_key(|c| c.origin);
116        let grade = by.iter().map(|c| c.grade).max()?;
117        Some(Self {
118            v: Self::VERSION,
119            grade,
120            by,
121        })
122    }
123
124    /// The strongest contribution (lowest origin on ties) — the one whose
125    /// backend and site count describe the edge.
126    pub fn primary(&self) -> Option<&Contribution> {
127        self.by
128            .iter()
129            .max_by(|a, b| a.grade.cmp(&b.grade).then(b.origin.cmp(&a.origin)))
130    }
131
132    pub fn has(&self, origin: EvidenceOrigin) -> bool {
133        self.by.iter().any(|c| c.origin == origin)
134    }
135
136    /// `incoming` replaces the contributions of its own origins on top of
137    /// `existing`; every other producer's contribution is kept as is. A
138    /// producer recomputing its edge is authoritative for its own part only.
139    pub fn merge(existing: Option<Self>, incoming: Self) -> Self {
140        let mut by: Vec<Contribution> = existing
141            .map(|e| e.by)
142            .unwrap_or_default()
143            .into_iter()
144            .filter(|c| !incoming.has(c.origin))
145            .collect();
146        by.extend(incoming.by.iter().cloned());
147        // `by` holds at least `incoming`'s contributions, so this is `Some`.
148        Self::from_contributions(by).unwrap_or(incoming)
149    }
150
151    /// Withdraws `origin`'s contribution. `None` when no producer derives the
152    /// edge any more (the edge should be deleted).
153    pub fn without(self, origin: EvidenceOrigin) -> Option<Self> {
154        Self::from_contributions(self.by.into_iter().filter(|c| c.origin != origin).collect())
155    }
156
157    pub fn to_metadata(&self) -> String {
158        serde_json::to_string(self).unwrap_or_default()
159    }
160
161    /// Parses edge metadata written by this module; anything else (legacy
162    /// edges, other producers' metadata) yields `None`.
163    pub fn from_metadata(metadata: Option<&str>) -> Option<Self> {
164        serde_json::from_str::<Self>(metadata?)
165            .ok()
166            .filter(|e| e.v == Self::VERSION)
167    }
168
169    /// Ranking factor for an edge's metadata. Edges without evidence (legacy,
170    /// non-call producers) keep their full kind weight — unchanged behaviour.
171    pub fn weight_factor_of(metadata: Option<&str>) -> f64 {
172        Self::from_metadata(metadata).map_or(1.0, |e| e.grade.weight_factor())
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179
180    /// Producers own only their contribution: one recomputing never
181    /// downgrades another's, and withdrawing keeps the edge while anyone
182    /// else still derives it.
183    #[test]
184    fn contributions_are_owned_per_producer() {
185        use EvidenceGrade::{ResolvedStructural, VerifiedSemantic};
186        use EvidenceOrigin::{Enrichment, ImpactIndex};
187        let verified = EdgeEvidence::new(VerifiedSemantic, Enrichment, Some("lsp:ra@1".into()), 1);
188        let structural = |origin| EdgeEvidence::new(ResolvedStructural, origin, None, 1);
189
190        let both = EdgeEvidence::merge(Some(verified.clone()), structural(ImpactIndex));
191        assert_eq!(both.grade, VerifiedSemantic, "no cross-producer downgrade");
192        assert_eq!(
193            both.primary().and_then(|c| c.backend.as_deref()),
194            Some("lsp:ra@1")
195        );
196
197        let recomputed = EdgeEvidence::merge(Some(both.clone()), structural(Enrichment));
198        assert_eq!(
199            recomputed.grade, ResolvedStructural,
200            "owner may weaken its own part"
201        );
202        assert!(recomputed.has(ImpactIndex));
203
204        let kept = both.clone().without(Enrichment).unwrap();
205        assert_eq!(
206            kept.grade, ResolvedStructural,
207            "impact still derives the edge"
208        );
209        assert!(
210            kept.without(ImpactIndex).is_none(),
211            "nobody derives it → delete"
212        );
213        assert_eq!(
214            EdgeEvidence::from_metadata(Some(&both.to_metadata())),
215            Some(both),
216            "deterministic round trip of the stored form"
217        );
218    }
219
220    #[test]
221    fn foreign_or_legacy_metadata_keeps_full_weight() {
222        let heuristic = EdgeEvidence::new(
223            EvidenceGrade::HeuristicStructural,
224            EvidenceOrigin::Enrichment,
225            None,
226            1,
227        );
228        assert_eq!(
229            EdgeEvidence::weight_factor_of(Some(&heuristic.to_metadata())),
230            0.5
231        );
232        assert_eq!(EdgeEvidence::weight_factor_of(None), 1.0);
233        assert_eq!(
234            EdgeEvidence::weight_factor_of(Some("kind=fn;exported")),
235            1.0
236        );
237        assert_eq!(
238            EdgeEvidence::weight_factor_of(Some(
239                r#"{"v":9,"grade":"verified_semantic","sites":1}"#
240            )),
241            1.0,
242            "unknown schema versions are ignored, not misread"
243        );
244    }
245}