Skip to main content

lean_ctx/core/
context_proof.rs

1use serde::Serialize;
2use std::path::{Path, PathBuf};
3use std::sync::atomic::{AtomicU64, Ordering};
4
5static PROOFS_COLLECTED: AtomicU64 = AtomicU64::new(0);
6static PROOFS_WRITTEN: AtomicU64 = AtomicU64::new(0);
7static LAST_WRITTEN_UNIX_MS: AtomicU64 = AtomicU64::new(0);
8
9#[derive(Debug, Clone, Serialize)]
10pub struct ProofStatsSnapshot {
11    pub collected: u64,
12    pub written: u64,
13    pub last_written_at: Option<String>,
14}
15
16pub(crate) fn proof_stats_snapshot() -> ProofStatsSnapshot {
17    let collected = PROOFS_COLLECTED.load(Ordering::Relaxed);
18    let written = PROOFS_WRITTEN.load(Ordering::Relaxed);
19    let last_ms = LAST_WRITTEN_UNIX_MS.load(Ordering::Relaxed);
20    let last_written_at = if last_ms == 0 {
21        None
22    } else {
23        lean_ctx_time::UtcDateTime::from_timestamp_millis(last_ms as i64)
24            .map(lean_ctx_time::UtcDateTime::to_rfc3339)
25    };
26    ProofStatsSnapshot {
27        collected,
28        written,
29        last_written_at,
30    }
31}
32
33#[derive(Debug, Clone, Serialize)]
34pub struct ContextProofV1 {
35    pub schema_version: u32,
36    pub created_at: String,
37    pub lean_ctx_version: String,
38    pub session_id: Option<String>,
39    pub project: ProjectIdentity,
40    pub role: RoleIdentity,
41    pub profile: ProfileIdentity,
42    /// Kept for the proof's wire shape. Per-layer metrics are not collected,
43    /// so this is `runs: 0` unless a legacy `pipeline_stats.json` exists.
44    pub pipeline: crate::core::pipeline::PipelineStats,
45    pub verification: crate::core::output_verification::VerificationSnapshot,
46    pub ledger: LedgerSummary,
47    pub evidence: Vec<EvidenceReceipt>,
48}
49
50#[derive(Debug, Clone, Serialize)]
51pub struct ProjectIdentity {
52    pub project_root_hash: Option<String>,
53    pub project_identity_hash: Option<String>,
54}
55
56#[derive(Debug, Clone, Serialize)]
57pub struct RoleIdentity {
58    pub name: String,
59    /// BLAKE3 hex; the serialized name keeps its historical `_md5` suffix.
60    #[serde(rename = "policy_md5")]
61    pub policy_blake3: String,
62}
63
64#[derive(Debug, Clone, Serialize)]
65pub struct ProfileIdentity {
66    pub name: String,
67    /// BLAKE3 hex; the serialized name keeps its historical `_md5` suffix.
68    #[serde(rename = "policy_md5")]
69    pub policy_blake3: String,
70}
71
72#[derive(Debug, Clone, Serialize)]
73pub struct LedgerSummary {
74    pub window_size: usize,
75    pub entries: usize,
76    pub total_tokens_sent: usize,
77    pub total_tokens_saved: usize,
78    pub compression_ratio: f64,
79    pub top_files_by_sent_tokens: Vec<LedgerFileSummary>,
80}
81
82#[derive(Debug, Clone, Serialize)]
83pub struct LedgerFileSummary {
84    pub path: String,
85    pub mode: String,
86    pub sent_tokens: usize,
87    pub original_tokens: usize,
88}
89
90#[derive(Debug, Clone, Serialize)]
91pub struct EvidenceReceipt {
92    pub tool: Option<String>,
93    pub input_md5: Option<String>,
94    pub output_md5: Option<String>,
95    pub agent_id: Option<String>,
96    pub client_name: Option<String>,
97    pub timestamp: String,
98}
99
100#[derive(Debug, Clone, Copy, Default)]
101pub struct ProofOptions {
102    pub max_evidence: usize,
103    pub max_ledger_files: usize,
104}
105
106#[derive(Debug, Clone, Default)]
107pub struct ProofSources {
108    pub project_root: Option<String>,
109    pub session: Option<crate::core::session::SessionState>,
110    pub pipeline: Option<crate::core::pipeline::PipelineStats>,
111    pub ledger: Option<crate::core::context_ledger::ContextLedger>,
112}
113
114pub fn collect_v1(sources: ProofSources, opts: ProofOptions) -> ContextProofV1 {
115    PROOFS_COLLECTED.fetch_add(1, Ordering::Relaxed);
116    let created_at = lean_ctx_time::UtcDateTime::now().to_rfc3339();
117
118    let role_name = crate::core::roles::active_role_name();
119    let role = crate::core::roles::active_role();
120
121    let profile_name = crate::core::profiles::active_profile_name();
122    let profile = crate::core::profiles::active_profile();
123
124    let role_policy_blake3 =
125        crate::core::hasher::hash_str(&serde_json::to_string(&role).unwrap_or_default());
126    let profile_policy_blake3 =
127        crate::core::hasher::hash_str(&serde_json::to_string(&profile).unwrap_or_default());
128
129    let project_root = sources.project_root.clone().or_else(|| {
130        sources
131            .session
132            .as_ref()
133            .and_then(|s| s.project_root.clone())
134    });
135
136    let (project_root_hash, project_identity_hash) = if let Some(ref root) = project_root {
137        let root_hash = crate::core::project_hash::hash_project_root(root);
138        let identity = crate::core::project_hash::project_identity(root);
139        let identity_hash = identity.as_deref().map(crate::core::hasher::hash_str);
140        (Some(root_hash), identity_hash)
141    } else {
142        (None, None)
143    };
144
145    let verification = crate::core::output_verification::stats_snapshot();
146
147    let pipeline = sources
148        .pipeline
149        .unwrap_or_else(crate::core::pipeline::PipelineStats::load);
150
151    let ledger = sources
152        .ledger
153        .unwrap_or_else(crate::core::context_ledger::ContextLedger::load);
154
155    let top_files = ledger
156        .files_by_token_cost()
157        .into_iter()
158        .take(opts.max_ledger_files.max(1))
159        .filter_map(|(path, _)| ledger.entries.iter().find(|e| e.path == path).cloned())
160        .map(|e| LedgerFileSummary {
161            path: e.path,
162            mode: e.mode,
163            sent_tokens: e.sent_tokens,
164            original_tokens: e.original_tokens,
165        })
166        .collect::<Vec<_>>();
167
168    let ledger_summary = LedgerSummary {
169        window_size: ledger.window_size,
170        entries: ledger.entries.len(),
171        total_tokens_sent: ledger.total_tokens_sent,
172        total_tokens_saved: ledger.total_tokens_saved,
173        compression_ratio: ledger.compression_ratio(),
174        top_files_by_sent_tokens: top_files,
175    };
176
177    let session = sources.session.or_else(|| {
178        project_root
179            .as_deref()
180            .and_then(crate::core::session::SessionState::load_latest_for_project_root)
181            .or_else(crate::core::session::SessionState::load_latest)
182    });
183
184    let (session_id, evidence) = if let Some(s) = session {
185        let mut receipts = s
186            .evidence
187            .into_iter()
188            .filter(|e| matches!(e.kind, crate::core::session::EvidenceKind::ToolCall))
189            .rev()
190            .take(opts.max_evidence.max(1))
191            .map(|e| EvidenceReceipt {
192                tool: e.tool,
193                input_md5: e.input_md5,
194                output_md5: e.output_md5,
195                agent_id: e.agent_id,
196                client_name: e.client_name,
197                timestamp: e.timestamp.to_rfc3339(),
198            })
199            .collect::<Vec<_>>();
200        receipts.reverse();
201        (Some(s.id), receipts)
202    } else {
203        (None, Vec::new())
204    };
205
206    ContextProofV1 {
207        schema_version: crate::core::contracts::CONTEXT_PROOF_V1_SCHEMA_VERSION,
208        created_at,
209        lean_ctx_version: env!("CARGO_PKG_VERSION").to_string(),
210        session_id,
211        project: ProjectIdentity {
212            project_root_hash,
213            project_identity_hash,
214        },
215        role: RoleIdentity {
216            name: role_name,
217            policy_blake3: role_policy_blake3,
218        },
219        profile: ProfileIdentity {
220            name: profile_name,
221            policy_blake3: profile_policy_blake3,
222        },
223        pipeline,
224        verification,
225        ledger: ledger_summary,
226        evidence,
227    }
228}
229
230/// A checked destination for a proof artifact: `<project>/.lean-ctx/proofs/<name>`.
231///
232/// Every proof-shaped artifact (context proof, context IR, architecture
233/// overview, A2A snapshot, handoff bundle) is written through here.
234/// `.lean-ctx`, `proofs` and the file itself must not be symlinks, and the
235/// write walks the path without following one (see
236/// [`crate::core::pathjail_write`]).
237#[derive(Debug, Clone)]
238pub struct ProofDestination {
239    project_root: PathBuf,
240    rel: PathBuf,
241    path: PathBuf,
242}
243
244impl ProofDestination {
245    /// The path the artifact is written to.
246    pub fn path(&self) -> &Path {
247        &self.path
248    }
249
250    /// Write `content`; refuses (writes nothing) when a component is or
251    /// became a symlink.
252    pub fn write(&self, content: &str) -> Result<PathBuf, String> {
253        crate::core::pathjail_write::write_project_data(
254            &self.project_root,
255            &self.rel,
256            content.as_bytes(),
257        )
258    }
259}
260
261/// The destination for the proof artifact `name` of `project_root`.
262///
263/// `name` comes from tool callers: only a bare file name is accepted
264/// (`Path::join` drops the base for an absolute path, and `..` would walk out
265/// of `proofs/`).
266pub fn proof_destination(project_root: &Path, name: &str) -> Result<ProofDestination, String> {
267    let mut components = Path::new(name).components();
268    match (components.next(), components.next()) {
269        (Some(std::path::Component::Normal(_)), None) => {}
270        _ => return Err(format!("filename must be a plain file name: {name}")),
271    }
272    let rel = Path::new("proofs").join(name);
273    let path = crate::core::pathjail_write::project_data_destination(project_root, &rel)?;
274    Ok(ProofDestination {
275        project_root: project_root.to_path_buf(),
276        rel,
277        path,
278    })
279}
280
281pub fn write_project_proof(
282    project_root: &Path,
283    proof: &ContextProofV1,
284    filename: Option<&str>,
285) -> Result<PathBuf, String> {
286    let ts = lean_ctx_time::UtcDateTime::now().format("%Y-%m-%d_%H%M%S");
287    let name = filename.map_or_else(|| format!("context-proof-v1_{ts}.json"), str::to_string);
288    let destination = proof_destination(project_root, &name)?;
289
290    let json = serde_json::to_string_pretty(proof).map_err(|e| e.to_string())?;
291    // Proof artifacts may be attached to CI logs; always redact (even for admin).
292    let json = crate::core::redaction::redact_text(&json);
293    let path = destination.write(&json)?;
294
295    PROOFS_WRITTEN.fetch_add(1, Ordering::Relaxed);
296    let ms = std::time::SystemTime::now()
297        .duration_since(std::time::SystemTime::UNIX_EPOCH)
298        .map_or(0, |d| d.as_millis() as u64);
299    LAST_WRITTEN_UNIX_MS.store(ms, Ordering::Relaxed);
300
301    Ok(path)
302}
303
304#[cfg(test)]
305mod tests {
306    use super::*;
307
308    #[test]
309    fn proof_has_required_fields() {
310        let proof = collect_v1(
311            ProofSources {
312                project_root: Some(".".to_string()),
313                ..Default::default()
314            },
315            ProofOptions {
316                max_evidence: 5,
317                max_ledger_files: 3,
318            },
319        );
320        let v = serde_json::to_value(&proof).unwrap();
321        assert_eq!(v["schema_version"], 1);
322        assert!(v["created_at"].as_str().unwrap_or_default().contains('T'));
323        assert!(v["lean_ctx_version"].as_str().unwrap_or_default().len() >= 3);
324        // The BLAKE3 policy hashes keep their historical wire name.
325        assert!(v["role"]["policy_md5"].is_string(), "{v}");
326        assert!(v["profile"]["policy_md5"].is_string(), "{v}");
327    }
328
329    #[test]
330    fn write_project_proof_creates_file() {
331        let dir = tempfile::tempdir().unwrap();
332        let proof = collect_v1(
333            ProofSources {
334                project_root: Some(dir.path().to_string_lossy().to_string()),
335                ..Default::default()
336            },
337            ProofOptions {
338                max_evidence: 3,
339                max_ledger_files: 2,
340            },
341        );
342        let path = write_project_proof(dir.path(), &proof, None).unwrap();
343        assert!(path.exists());
344        let content = std::fs::read_to_string(path).unwrap();
345        assert!(content.contains("\"schema_version\": 1"));
346    }
347
348    #[test]
349    fn write_project_proof_rejects_filenames_outside_proofs_dir() {
350        let dir = tempfile::tempdir().unwrap();
351        let project = dir.path().join("proj");
352        std::fs::create_dir_all(&project).unwrap();
353        let proof = collect_v1(
354            ProofSources {
355                project_root: Some(project.to_string_lossy().to_string()),
356                ..Default::default()
357            },
358            ProofOptions {
359                max_evidence: 1,
360                max_ledger_files: 1,
361            },
362        );
363        let outside = dir.path().join("outside.json");
364        let outside_abs = outside.to_string_lossy().to_string();
365        for name in [
366            "../../../outside.json",
367            outside_abs.as_str(),
368            "sub/dir.json",
369            "..",
370            ".",
371            "",
372        ] {
373            assert!(
374                write_project_proof(&project, &proof, Some(name)).is_err(),
375                "filename {name:?} must be rejected"
376            );
377        }
378        assert!(!outside.exists(), "nothing may be written outside proofs/");
379
380        let path = write_project_proof(&project, &proof, Some("named.json")).unwrap();
381        assert_eq!(path.file_name().unwrap(), "named.json");
382        assert!(path.parent().unwrap().ends_with("proofs"));
383    }
384
385    #[cfg(unix)]
386    fn sample_proof(project: &Path) -> ContextProofV1 {
387        collect_v1(
388            ProofSources {
389                project_root: Some(project.to_string_lossy().to_string()),
390                ..Default::default()
391            },
392            ProofOptions {
393                max_evidence: 1,
394                max_ledger_files: 1,
395            },
396        )
397    }
398
399    #[cfg(unix)]
400    #[test]
401    fn write_project_proof_refuses_a_symlinked_proofs_dir() {
402        let dir = tempfile::tempdir().unwrap();
403        let project = dir.path().join("proj");
404        let outside = dir.path().join("outside");
405        std::fs::create_dir_all(project.join(".lean-ctx")).unwrap();
406        std::fs::create_dir_all(&outside).unwrap();
407        std::os::unix::fs::symlink(&outside, project.join(".lean-ctx/proofs")).unwrap();
408        let proof = sample_proof(&project);
409        let err = write_project_proof(&project, &proof, Some("p.json")).unwrap_err();
410        assert!(err.contains("symlink"), "{err}");
411        assert!(!outside.join("p.json").exists());
412    }
413
414    #[cfg(unix)]
415    #[test]
416    fn write_project_proof_refuses_a_symlinked_target_file() {
417        let dir = tempfile::tempdir().unwrap();
418        let project = dir.path().join("proj");
419        std::fs::create_dir_all(project.join(".lean-ctx/proofs")).unwrap();
420        let victim = dir.path().join("victim");
421        std::fs::write(&victim, "keep").unwrap();
422        std::os::unix::fs::symlink(&victim, project.join(".lean-ctx/proofs/p.json")).unwrap();
423        let proof = sample_proof(&project);
424        // The victim lies inside $HOME: the dotfile write-through rule of
425        // config writes must not apply to project data.
426        let _guard = crate::core::data_dir::test_env_lock();
427        let previous = std::env::var_os("HOME");
428        crate::test_env::set_var("HOME", dir.path());
429        let result = write_project_proof(&project, &proof, Some("p.json"));
430        match previous {
431            Some(home) => crate::test_env::set_var("HOME", home),
432            None => crate::test_env::remove_var("HOME"),
433        }
434        assert!(result.is_err());
435        assert_eq!(std::fs::read_to_string(&victim).unwrap(), "keep");
436    }
437
438    #[cfg(unix)]
439    #[test]
440    fn write_project_proof_refuses_a_dangling_data_dir_link() {
441        let dir = tempfile::tempdir().unwrap();
442        let project = dir.path().join("proj");
443        std::fs::create_dir_all(&project).unwrap();
444        let missing = dir.path().join("not-yet");
445        std::os::unix::fs::symlink(&missing, project.join(".lean-ctx")).unwrap();
446        let proof = sample_proof(&project);
447        assert!(write_project_proof(&project, &proof, Some("p.json")).is_err());
448        assert!(
449            !missing.exists(),
450            "a dangling link must not be created through"
451        );
452
453        // A dangling target-file link into $HOME is not created through
454        // either (the dotfile write-through rule of config writes would).
455        let project = dir.path().join("proj2");
456        std::fs::create_dir_all(project.join(".lean-ctx/proofs")).unwrap();
457        let planted = dir.path().join("planted.json");
458        std::os::unix::fs::symlink(&planted, project.join(".lean-ctx/proofs/p.json")).unwrap();
459        let _guard = crate::core::data_dir::test_env_lock();
460        let previous = std::env::var_os("HOME");
461        crate::test_env::set_var("HOME", dir.path());
462        let result = write_project_proof(&project, &proof, Some("p.json"));
463        match previous {
464            Some(home) => crate::test_env::set_var("HOME", home),
465            None => crate::test_env::remove_var("HOME"),
466        }
467        assert!(result.is_err());
468        assert!(
469            !planted.exists(),
470            "a dangling file link must not be created through"
471        );
472    }
473}