Skip to main content

cortex_context/
certificate.rs

1//! Structured completeness for a compiled packet.
2//!
3//! A boolean `sufficient` only says the compiler is happy. A certificate
4//! names every required facet, the citations that close it, what is still
5//! missing, and the snapshot that claim was checked against.
6
7use std::collections::BTreeMap;
8
9use serde::{Deserialize, Serialize};
10
11/// Facet names the packet can require or expand.
12pub const FACET_DEFINITION: &str = "target.complete_definition";
13pub const FACET_SIGNATURES: &str = "target.signatures";
14pub const FACET_GUARDS: &str = "target.guards";
15pub const FACET_DEFAULTS: &str = "target.defaults";
16pub const FACET_CALLERS: &str = "direct_callers";
17pub const FACET_PUBLIC_API: &str = "public_api_effect";
18pub const FACET_TESTS: &str = "relevant_tests";
19pub const FACET_CONFIG: &str = "runtime_config";
20pub const FACET_ERRORS: &str = "exact_errors";
21pub const FACET_MEMORY: &str = "prior_verified_failure";
22pub const FACET_GIT: &str = "git_history";
23
24/// Highest-risk missing facet is expanded first.
25pub const FACET_EXPANSION_ORDER: &[&str] = &[
26    FACET_DEFINITION,
27    FACET_SIGNATURES,
28    FACET_CALLERS,
29    FACET_PUBLIC_API,
30    FACET_DEFAULTS,
31    FACET_GUARDS,
32    FACET_CONFIG,
33    FACET_ERRORS,
34    FACET_TESTS,
35    FACET_MEMORY,
36    FACET_GIT,
37];
38
39#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
40#[serde(rename_all = "camelCase")]
41pub struct CoverageCertificate {
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub packet_id: Option<String>,
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub snapshot_id: Option<String>,
46    pub required: Vec<String>,
47    pub satisfied: BTreeMap<String, Vec<String>>,
48    pub missing: Vec<String>,
49    #[serde(default, skip_serializing_if = "Vec::is_empty")]
50    pub contradictions: Vec<ContradictionGroup>,
51    #[serde(default)]
52    pub stale: bool,
53    pub sufficient: bool,
54    #[serde(default)]
55    pub expansions_performed: u32,
56    /// How each satisfied facet was closed. Empty when nothing validated.
57    #[serde(default, skip_serializing_if = "Vec::is_empty")]
58    pub claims: Vec<FacetClaim>,
59}
60
61/// One validated facet close: not "a Dependents fragment existed".
62#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
63#[serde(rename_all = "camelCase")]
64pub struct FacetClaim {
65    pub facet: String,
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub target: Option<String>,
68    pub evidence_ids: Vec<String>,
69    pub validator: String,
70    pub cardinality: u32,
71}
72
73#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
74#[serde(rename_all = "camelCase")]
75pub struct ContradictionGroup {
76    pub id: String,
77    pub evidence_ids: Vec<String>,
78}
79
80impl CoverageCertificate {
81    #[must_use]
82    pub fn critical_missing(&self) -> Vec<&str> {
83        self.missing
84            .iter()
85            .filter(|facet| is_critical_facet(facet))
86            .map(String::as_str)
87            .collect()
88    }
89
90    /// Facets and citations the L0 map prints. Packet/snapshot ids are
91    /// stamped later and must not count as a ledger change.
92    #[must_use]
93    pub fn ledger_matches(&self, other: &Self) -> bool {
94        self.required == other.required
95            && self.satisfied == other.satisfied
96            && self.missing == other.missing
97            && self.sufficient == other.sufficient
98            && self.contradictions == other.contradictions
99            && self.claims == other.claims
100    }
101
102    #[must_use]
103    pub fn next_expansion(&self) -> Option<&str> {
104        FACET_EXPANSION_ORDER
105            .iter()
106            .copied()
107            .find(|facet| self.missing.iter().any(|missing| missing == facet))
108    }
109
110    #[must_use]
111    pub fn expand_handle(facet: &str) -> &'static str {
112        match facet {
113            FACET_DEFINITION | FACET_SIGNATURES => "complete_definition",
114            FACET_CALLERS => "callers",
115            FACET_PUBLIC_API => "public_api_effect",
116            FACET_TESTS => "tests",
117            FACET_GIT => "git_history",
118            _ => "source",
119        }
120    }
121}
122
123#[must_use]
124pub fn is_critical_facet(facet: &str) -> bool {
125    matches!(
126        facet,
127        FACET_DEFINITION | FACET_SIGNATURES | FACET_CALLERS | FACET_PUBLIC_API
128    )
129}
130
131/// L0 decision map: intent, snapshot, and a facet ledger.
132#[must_use]
133pub fn render_decision_map(
134    intent: &str,
135    targets: &[String],
136    snapshot_id: Option<&str>,
137    risk: &str,
138    certificate: &CoverageCertificate,
139) -> String {
140    let mut lines = vec![
141        format!("intent: {intent}"),
142        format!("targets: {}", display_list(targets)),
143        format!("snapshot: {}", snapshot_id.unwrap_or("unknown")),
144        format!("risk: {risk}"),
145        "required:".to_owned(),
146    ];
147    for facet in &certificate.required {
148        let rank = if is_critical_facet(facet) {
149            "CRITICAL"
150        } else {
151            "HIGH"
152        };
153        if let Some(ids) = certificate.satisfied.get(facet) {
154            lines.push(format!("- {facet} [{rank}] {}", ids.join(", ")));
155        } else {
156            lines.push(format!(
157                "- {facet} [{rank}] MISSING → EXPAND {}",
158                CoverageCertificate::expand_handle(facet)
159            ));
160        }
161    }
162    if certificate.contradictions.is_empty() {
163        lines.push("contradictions: none".to_owned());
164    } else {
165        lines.push("contradictions:".to_owned());
166        for group in &certificate.contradictions {
167            lines.push(format!("- {} {}", group.id, group.evidence_ids.join(", ")));
168        }
169    }
170    lines.join("\n")
171}
172
173/// L2 expansion handles for facets the packet did not close.
174#[must_use]
175pub fn render_expansions(certificate: &CoverageCertificate) -> String {
176    let lines: Vec<String> = certificate
177        .missing
178        .iter()
179        .map(|facet| {
180            format!(
181                "EXPAND {} — {facet}",
182                CoverageCertificate::expand_handle(facet)
183            )
184        })
185        .collect();
186    if lines.is_empty() {
187        "EXPAND none — every required facet is cited".to_owned()
188    } else {
189        lines.join("\n")
190    }
191}
192
193fn display_list(values: &[String]) -> String {
194    if values.is_empty() {
195        "(none)".to_owned()
196    } else {
197        values.join(", ")
198    }
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204
205    #[test]
206    fn certificate_picks_the_highest_risk_missing_facet() {
207        let certificate = CoverageCertificate {
208            required: vec![FACET_TESTS.to_owned(), FACET_DEFINITION.to_owned()],
209            missing: vec![FACET_TESTS.to_owned(), FACET_DEFINITION.to_owned()],
210            sufficient: false,
211            ..CoverageCertificate::default()
212        };
213        assert_eq!(certificate.next_expansion(), Some(FACET_DEFINITION));
214        assert_eq!(certificate.critical_missing(), [FACET_DEFINITION]);
215    }
216
217    #[test]
218    fn decision_map_names_ids_and_expand_handles() {
219        let mut certificate = CoverageCertificate {
220            required: vec![FACET_DEFINITION.to_owned(), FACET_CALLERS.to_owned()],
221            sufficient: false,
222            ..CoverageCertificate::default()
223        };
224        certificate
225            .satisfied
226            .insert(FACET_DEFINITION.to_owned(), vec!["ev_a91".to_owned()]);
227        certificate.missing.push(FACET_CALLERS.to_owned());
228        let map = render_decision_map(
229            "identifier_change",
230            &["ArchiveOptions".to_owned()],
231            Some("git:abc+dirty:0"),
232            "mutation",
233            &certificate,
234        );
235        assert!(map.contains("intent: identifier_change"));
236        assert!(map.contains("target.complete_definition [CRITICAL] ev_a91"));
237        assert!(map.contains("direct_callers [CRITICAL] MISSING → EXPAND callers"));
238        assert!(render_expansions(&certificate).contains("EXPAND callers — direct_callers"));
239    }
240
241    #[test]
242    fn ledger_ignores_packet_identity() {
243        let mut left = CoverageCertificate {
244            required: vec![FACET_CALLERS.to_owned()],
245            missing: vec![FACET_CALLERS.to_owned()],
246            sufficient: false,
247            packet_id: Some("a".to_owned()),
248            ..CoverageCertificate::default()
249        };
250        let mut right = left.clone();
251        right.packet_id = Some("b".to_owned());
252        assert!(left.ledger_matches(&right));
253        left.missing.clear();
254        assert!(!left.ledger_matches(&right));
255    }
256}