Skip to main content

cortex_context/
evidence.rs

1//! Typed evidence identity, trust, and provenance.
2
3use serde::{Deserialize, Serialize};
4use sha2::{Digest, Sha256};
5
6#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
7#[serde(rename_all = "snake_case")]
8pub enum EvidencePriority {
9    Critical,
10    High,
11    Normal,
12    Low,
13}
14
15impl EvidencePriority {
16    #[must_use]
17    pub const fn rank(self) -> u8 {
18        match self {
19            Self::Critical => 0,
20            Self::High => 1,
21            Self::Normal => 2,
22            Self::Low => 3,
23        }
24    }
25}
26
27#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
28#[serde(rename_all = "snake_case")]
29pub enum EvidenceState {
30    Verified,
31    Unverified,
32    Contradictory,
33}
34
35/// How a fragment was derived. Shown in the packet heading so a model
36/// cannot treat an unverified plan as exact source.
37#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
38#[serde(rename_all = "snake_case")]
39pub enum EvidenceDerivation {
40    #[default]
41    ExactSource,
42    Plan,
43    Graph,
44    Search,
45    Memory,
46    Inferred,
47}
48
49/// Why this fragment is in the packet. Criticality attaches to the facet,
50/// not to the Weavatrix operation that produced it.
51#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
52#[serde(rename_all = "snake_case")]
53pub enum EvidenceFacet {
54    #[default]
55    Unspecified,
56    Definition,
57    CallerSignature,
58    SourceWindow,
59    References,
60    Plan,
61    Structure,
62    Memory,
63}
64
65/// Revision-stable locator. Empty fields mean the gatherer did not know.
66#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
67#[serde(rename_all = "camelCase")]
68pub struct EvidenceLocator {
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub path: Option<String>,
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub start_line: Option<u32>,
73    #[serde(default, skip_serializing_if = "Option::is_none")]
74    pub end_line: Option<u32>,
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub blob_hash: Option<String>,
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub snapshot_id: Option<String>,
79}
80
81impl EvidenceLocator {
82    #[must_use]
83    pub fn from_source(source: &str) -> Self {
84        let mut locator = Self::default();
85        let trimmed = source.trim();
86        if let Some((path, rest)) = trimmed.rsplit_once(':')
87            && let Ok(line) = rest.parse::<u32>()
88            && (path.contains('/') || path.contains('\\') || path.contains('.'))
89        {
90            locator.path = Some(path.to_owned());
91            locator.start_line = Some(line);
92            locator.end_line = Some(line);
93        }
94        locator
95    }
96
97    #[must_use]
98    pub fn is_empty(&self) -> bool {
99        self.path.is_none()
100            && self.start_line.is_none()
101            && self.end_line.is_none()
102            && self.blob_hash.is_none()
103            && self.snapshot_id.is_none()
104    }
105
106    /// True when both locators name the same span but a different blob or
107    /// snapshot, so a packet citing `self` is stale against `current`.
108    #[must_use]
109    pub fn is_revision_stale(&self, current: &Self) -> bool {
110        let same_span = self.path.is_some()
111            && self.path == current.path
112            && self.start_line == current.start_line
113            && self.end_line == current.end_line;
114        same_span
115            && (option_mismatch(self.blob_hash.as_ref(), current.blob_hash.as_ref())
116                || option_mismatch(self.snapshot_id.as_ref(), current.snapshot_id.as_ref()))
117    }
118}
119
120fn option_mismatch(left: Option<&String>, right: Option<&String>) -> bool {
121    matches!((left, right), (Some(left), Some(right)) if left != right)
122}
123
124/// `true` when the packet was compiled against a different tree than `current`.
125/// A missing packet snapshot cannot prove staleness.
126#[must_use]
127pub fn snapshot_is_stale(packet_snapshot: Option<&str>, current: &str) -> bool {
128    packet_snapshot.is_some_and(|id| id != current)
129}
130
131/// Content-addressed citation: `ev_<12 hex>`.
132#[must_use]
133pub fn evidence_id(parts: &[&str]) -> String {
134    digest_id("ev_", parts, 12)
135}
136
137/// Packet handle: `pk_<12 hex>`.
138#[must_use]
139pub fn packet_id(parts: &[&str]) -> String {
140    digest_id("pk_", parts, 12)
141}
142
143/// Span body hash: `blob_<12 hex>`.
144#[must_use]
145pub fn blob_id(parts: &[&str]) -> String {
146    digest_id("blob_", parts, 12)
147}
148
149fn digest_id(prefix: &str, parts: &[&str], hex_chars: usize) -> String {
150    let mut hasher = Sha256::new();
151    for part in parts {
152        hasher.update(part.as_bytes());
153        hasher.update([0xff]);
154    }
155    format!("{prefix}{}", hex::encode(hasher.finalize()))
156        .chars()
157        .take(prefix.chars().count() + hex_chars)
158        .collect()
159}
160
161#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
162#[serde(rename_all = "camelCase", deny_unknown_fields)]
163pub struct EvidenceItem {
164    pub id: String,
165    pub source: String,
166    pub content: String,
167    pub priority: EvidencePriority,
168    pub state: EvidenceState,
169    #[serde(default, skip_serializing_if = "Option::is_none")]
170    pub relevance: Option<f64>,
171    #[serde(default, skip_serializing_if = "Option::is_none")]
172    pub derivation: Option<EvidenceDerivation>,
173    #[serde(default, skip_serializing_if = "Option::is_none")]
174    pub facet: Option<EvidenceFacet>,
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub contradiction_group: Option<String>,
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub locator: Option<EvidenceLocator>,
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub group_id: Option<String>,
181}
182
183impl EvidenceItem {
184    #[must_use]
185    pub fn new(
186        id: impl Into<String>,
187        source: impl Into<String>,
188        content: impl Into<String>,
189        priority: EvidencePriority,
190        state: EvidenceState,
191    ) -> Self {
192        let source = source.into();
193        let locator = EvidenceLocator::from_source(&source);
194        Self {
195            id: id.into(),
196            locator: (!locator.is_empty()).then_some(locator),
197            source,
198            content: content.into(),
199            priority,
200            state,
201            relevance: None,
202            derivation: None,
203            facet: None,
204            contradiction_group: None,
205            group_id: None,
206        }
207    }
208
209    #[must_use]
210    pub fn heading_label(&self) -> String {
211        match self.state {
212            EvidenceState::Contradictory => self.contradiction_group.as_deref().map_or_else(
213                || "CONTRADICTORY".to_owned(),
214                |group| format!("CONTRADICTORY — group {group}"),
215            ),
216            EvidenceState::Unverified => match self.derivation {
217                Some(EvidenceDerivation::Plan) => "UNVERIFIED PLAN".to_owned(),
218                _ => "UNVERIFIED".to_owned(),
219            },
220            EvidenceState::Verified => match self.derivation {
221                Some(EvidenceDerivation::ExactSource) => "EXACT SOURCE".to_owned(),
222                Some(EvidenceDerivation::Graph) => "GRAPH".to_owned(),
223                Some(EvidenceDerivation::Search) => "SEARCH".to_owned(),
224                Some(EvidenceDerivation::Memory) => "MEMORY".to_owned(),
225                Some(EvidenceDerivation::Plan) => "PLAN".to_owned(),
226                Some(EvidenceDerivation::Inferred) | None => "VERIFIED".to_owned(),
227            },
228        }
229    }
230}