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