Skip to main content

lean_ctx/core/
claim_extractor.rs

1//! Claim Extraction — decomposes context pipeline outputs into verifiable claims.
2//!
3//! Inspired by VERGE (arXiv:2601.20055): instead of verifying entire outputs
4//! monolithically, we decompose them into atomic, individually verifiable claims
5//! and route each to the appropriate verifier.
6
7use std::path::Path;
8
9use super::context_proof_v2::{
10    Claim, ClaimKind, ClaimStatus, ContextProofV2, VerifierKind, deterministic_claim, policy_claim,
11};
12
13pub struct ClaimExtractor {
14    proof: ContextProofV2,
15}
16
17impl ClaimExtractor {
18    pub fn new(run_id: &str, session_id: Option<&str>) -> Self {
19        Self {
20            proof: ContextProofV2::new(
21                run_id.to_string(),
22                session_id.map(std::string::ToString::to_string),
23            ),
24        }
25    }
26
27    pub fn verify_pathjail(&mut self, path: &str, jail_root: &Path) {
28        let resolved = crate::core::pathjail::jail_path(&std::path::PathBuf::from(path), jail_root);
29        let passed = resolved.is_ok();
30        self.proof.add_claim(policy_claim(
31            &format!("pathjail:{path}"),
32            &format!("Path '{path}' is within jail root"),
33            ClaimKind::PathjailCompliance,
34            passed,
35        ));
36    }
37
38    pub fn verify_no_secrets_in_output(&mut self, output: &str) {
39        let secret_matches = crate::core::secret_detection::detect_secrets(output);
40
41        let passed = secret_matches.is_empty();
42        let text = if passed {
43            "No secret patterns found in output".to_string()
44        } else {
45            let names: Vec<&str> = secret_matches.iter().map(|m| m.pattern_name).collect();
46            let mut unique_names: Vec<&str> = names.clone();
47            unique_names.sort_unstable();
48            unique_names.dedup();
49            format!(
50                "Secret patterns detected ({}): {}",
51                secret_matches.len(),
52                unique_names.join(", ")
53            )
54        };
55
56        self.proof.add_claim(policy_claim(
57            "no_secrets",
58            &text,
59            ClaimKind::SecretPolicy,
60            passed,
61        ));
62    }
63
64    pub fn verify_budget_compliance(&mut self) {
65        let snapshot = crate::core::budget_tracker::BudgetTracker::global().check();
66        let level = snapshot.worst_level();
67        let passed = *level != crate::core::budget_tracker::BudgetLevel::Exhausted;
68
69        self.proof.add_claim(policy_claim(
70            "budget_compliance",
71            &format!("Budget level: {level}"),
72            ClaimKind::BudgetCompliance,
73            passed,
74        ));
75    }
76
77    pub fn verify_signatures_preserved(&mut self, original: &[String], compressed: &[String]) {
78        let mut missing = Vec::new();
79        for sig in original {
80            if !compressed.iter().any(|c| c.contains(sig)) {
81                missing.push(sig.clone());
82            }
83        }
84
85        let passed = missing.is_empty();
86        let text = if passed {
87            format!("All {} signatures preserved", original.len())
88        } else {
89            format!(
90                "{} of {} signatures missing: {:?}",
91                missing.len(),
92                original.len(),
93                &missing[..missing.len().min(3)]
94            )
95        };
96
97        self.proof.add_claim(Claim {
98            id: "signatures_preserved".to_string(),
99            text,
100            kind: ClaimKind::CompressionInvariant,
101            verifier: VerifierKind::Ast,
102            status: if passed {
103                ClaimStatus::Passed
104            } else {
105                ClaimStatus::Failed
106            },
107            evidence_ref: None,
108        });
109    }
110
111    pub fn verify_imports_preserved(&mut self, original_imports: &[String], compressed: &str) {
112        let mut missing = Vec::new();
113        for imp in original_imports {
114            if !compressed.contains(imp) {
115                missing.push(imp.clone());
116            }
117        }
118
119        let passed = missing.is_empty();
120        let text = if passed {
121            format!("All {} imports preserved", original_imports.len())
122        } else {
123            format!(
124                "{} of {} imports missing",
125                missing.len(),
126                original_imports.len()
127            )
128        };
129
130        self.proof
131            .add_claim(deterministic_claim("imports_preserved", &text, passed));
132    }
133
134    pub fn add_custom_claim(&mut self, claim: Claim) {
135        self.proof.add_claim(claim);
136    }
137
138    pub fn finalize(self) -> ContextProofV2 {
139        self.proof
140    }
141}
142
143#[cfg(test)]
144pub mod tests {
145    use super::*;
146
147    #[test]
148    fn secret_detection_catches_aws_keys() {
149        let mut ext = ClaimExtractor::new("test_1", None);
150        ext.verify_no_secrets_in_output(concat!("const key = 'AK", "IAIOSFODNN7EXAMPLE'"));
151        let proof = ext.finalize();
152        assert_eq!(proof.summary.failed, 1);
153    }
154
155    #[test]
156    fn clean_output_passes_secret_check() {
157        let mut ext = ClaimExtractor::new("test_2", None);
158        ext.verify_no_secrets_in_output("fn main() { println!(\"hello\"); }");
159        let proof = ext.finalize();
160        assert_eq!(proof.summary.passed, 1);
161        assert_eq!(proof.summary.failed, 0);
162    }
163
164    #[test]
165    fn signatures_preserved_check() {
166        let mut ext = ClaimExtractor::new("test_3", None);
167        let original = vec!["fn main".to_string(), "pub fn process".to_string()];
168        let compressed = vec![
169            "fn main() { ... }".to_string(),
170            "pub fn process(data: &[u8]) -> Result<(), Error>".to_string(),
171        ];
172        ext.verify_signatures_preserved(&original, &compressed);
173        let proof = ext.finalize();
174        assert_eq!(proof.summary.passed, 1);
175    }
176
177    #[test]
178    fn missing_signatures_detected() {
179        let mut ext = ClaimExtractor::new("test_4", None);
180        let original = vec!["fn main()".to_string(), "pub fn gone()".to_string()];
181        let compressed = vec!["fn main() { ... }".to_string()];
182        ext.verify_signatures_preserved(&original, &compressed);
183        let proof = ext.finalize();
184        assert_eq!(proof.summary.failed, 1);
185    }
186
187    #[test]
188    fn pathjail_claim_reports_what_the_build_enforces() {
189        // Hold the env lock with a clean config: parallel pathjail tests set
190        // LEAN_CTX_ALLOW_PATH=/ under that lock, which would admit any path.
191        let _iso = crate::core::data_dir::isolated_data_dir();
192        let root = tempfile::tempdir().unwrap();
193        let outside = tempfile::tempdir().unwrap();
194        let escaped = outside.path().join("secret.txt");
195        std::fs::write(&escaped, "outside the jail").unwrap();
196        let mut ext = ClaimExtractor::new("test_5", None);
197        ext.verify_pathjail(&escaped.to_string_lossy(), root.path());
198        let proof = ext.finalize();
199        // A normal build rejects the escape and must say so. The `no-jail`
200        // build (part of `--all-features`) admits every path, so the claim
201        // must honestly report that the path was allowed.
202        let (failed, passed, level) = if cfg!(feature = "no-jail") {
203            (
204                0,
205                1,
206                super::super::context_proof_v2::QualityLevel::PolicyChecked,
207            )
208        } else {
209            (
210                1,
211                0,
212                super::super::context_proof_v2::QualityLevel::Provenance,
213            )
214        };
215        assert_eq!(proof.summary.failed, failed);
216        assert_eq!(proof.summary.passed, passed);
217        assert_eq!(proof.quality_level, level);
218    }
219
220    #[test]
221    fn combined_extraction_computes_quality() {
222        let _iso = crate::core::data_dir::isolated_data_dir();
223        let root = tempfile::tempdir().unwrap();
224        let inside = root.path().join("src.rs");
225        std::fs::write(&inside, "fn main() {}").unwrap();
226        let mut ext = ClaimExtractor::new("test_6", None);
227        ext.verify_no_secrets_in_output("clean code");
228        ext.verify_pathjail(&inside.to_string_lossy(), root.path());
229        let proof = ext.finalize();
230        assert_eq!(proof.summary.passed, 2);
231        assert_eq!(
232            proof.quality_level,
233            super::super::context_proof_v2::QualityLevel::PolicyChecked
234        );
235    }
236
237    #[test]
238    fn detects_github_pat() {
239        let mut ext = ClaimExtractor::new("test_gh", None);
240        ext.verify_no_secrets_in_output(concat!("token = gh", "p_1234567890abcdef"));
241        let proof = ext.finalize();
242        assert_eq!(proof.summary.failed, 1);
243    }
244
245    #[test]
246    fn detects_gitlab_pat() {
247        let mut ext = ClaimExtractor::new("test_gl", None);
248        ext.verify_no_secrets_in_output("glpat-xxxxxxxxxxxxxxxxxxxx");
249        let proof = ext.finalize();
250        assert_eq!(proof.summary.failed, 1);
251    }
252
253    #[test]
254    fn detects_pem_private_key() {
255        let mut ext = ClaimExtractor::new("test_pem", None);
256        ext.verify_no_secrets_in_output("-----BEGIN RSA PRIVATE KEY-----");
257        let proof = ext.finalize();
258        assert_eq!(proof.summary.failed, 1);
259    }
260
261    #[test]
262    fn empty_signatures_passes() {
263        let mut ext = ClaimExtractor::new("test_empty", None);
264        ext.verify_signatures_preserved(&[], &[]);
265        let proof = ext.finalize();
266        assert_eq!(proof.summary.passed, 1);
267        assert_eq!(proof.summary.failed, 0);
268    }
269
270    #[test]
271    fn empty_imports_passes() {
272        let mut ext = ClaimExtractor::new("test_imp", None);
273        ext.verify_imports_preserved(&[], "some content");
274        let proof = ext.finalize();
275        assert_eq!(proof.summary.passed, 1);
276    }
277
278    #[test]
279    fn finalize_returns_correct_run_id() {
280        let ext = ClaimExtractor::new("my_run_42", Some("sess_7"));
281        let proof = ext.finalize();
282        assert_eq!(proof.run_id, "my_run_42");
283        assert_eq!(proof.session_id, Some("sess_7".to_string()));
284    }
285
286    #[test]
287    fn multiple_secret_patterns_all_detected() {
288        let mut ext = ClaimExtractor::new("test_multi", None);
289        ext.verify_no_secrets_in_output(concat!(
290            "AK",
291            "IAIOSFODNN7EXAMPLE1 and ",
292            "sk",
293            "-abcdefghijklmnopqrstuvwx and password=longvalue1234567890extra",
294        ));
295        let proof = ext.finalize();
296        assert_eq!(proof.summary.failed, 1);
297        assert!(proof.claims[0].text.contains("aws_key"));
298    }
299}