Skip to main content

lean_ctx/core/value/
proof.rs

1//! `lean-ctx value`: every number the value surface shows, re-derived from the
2//! two tamper-evident chains instead of the display counters.
3//!
4//! * Tokens come from the savings ledger (SHA-256 chain, `session_id`
5//!   committed since canonical v7).
6//! * Security events come from the audit trail (SHA-256 chain, Ed25519
7//!   signed; kind, count and session committed in the hashed `action`).
8//!
9//! Both chains are re-walked from genesis first. A broken chain makes the
10//! report *tampered*: the numbers are still printed, but flagged as not proof,
11//! and the CLI exits non-zero.
12
13use std::collections::BTreeSet;
14use std::path::Path;
15
16use chrono::{DateTime, Utc};
17use serde::Serialize;
18
19use crate::core::audit_trail::{self, AuditEntry};
20use crate::core::savings_ledger::{self, SavingsEvent};
21use crate::core::security_events::{SecurityCounts, parse_action};
22use crate::core::wrapped::format_tokens;
23
24use super::format::{Style, security_phrases};
25use super::snapshot::ValueSnapshot;
26
27#[derive(Debug, Clone, Serialize)]
28pub struct ChainCheck {
29    pub name: &'static str,
30    pub path: Option<String>,
31    pub entries: usize,
32    pub intact: bool,
33    pub first_invalid_at: Option<usize>,
34}
35
36/// First and last `entry_hash` of the chain entries a claim rests on —
37/// anyone can look them up in the JSONL file.
38#[derive(Debug, Clone, Default, Serialize)]
39pub struct Evidence {
40    pub entries: u64,
41    pub first_hash: Option<String>,
42    pub last_hash: Option<String>,
43}
44
45impl Evidence {
46    fn push(&mut self, hash: &str) {
47        self.entries += 1;
48        if self.first_hash.is_none() {
49            self.first_hash = Some(hash.to_string());
50        }
51        self.last_hash = Some(hash.to_string());
52    }
53}
54
55#[derive(Debug, Clone, Serialize)]
56pub struct Proof {
57    /// `None` = lifetime (every session).
58    pub session_id: Option<String>,
59    pub ledger: ChainCheck,
60    pub audit: ChainCheck,
61    /// ✓ measured: counterfactual input tokens of the attributed tool results.
62    pub tokens_baseline: u64,
63    /// ✓ measured: tokens kept out of the model's context.
64    pub tokens_saved: u64,
65    /// ✓ measured: tokens the agent spent re-reading (netted out).
66    pub tokens_bounced: u64,
67    pub ledger_evidence: Evidence,
68    /// ✓ measured: security events committed to the audit trail.
69    pub security: SecurityCounts,
70    pub audit_evidence: Evidence,
71    /// The live display counters, for comparison only — not proof.
72    pub live: Option<ValueSnapshot>,
73    /// UTC days (`YYYY-MM-DD`) with at least one attributed ledger event —
74    /// the evidence behind streak milestones.
75    #[serde(skip)]
76    pub active_days: BTreeSet<String>,
77}
78
79impl Proof {
80    pub fn tampered(&self) -> bool {
81        !self.ledger.intact || !self.audit.intact
82    }
83
84    pub fn net_saved(&self) -> u64 {
85        self.tokens_saved.saturating_sub(self.tokens_bounced)
86    }
87
88    /// ≈ derived: share of the attributed input kept out of context.
89    pub fn saved_pct(&self) -> Option<f64> {
90        (self.tokens_baseline > 0)
91            .then(|| self.net_saved() as f64 * 100.0 / self.tokens_baseline as f64)
92    }
93}
94
95fn in_session(entry_session: Option<&str>, wanted: Option<&str>) -> bool {
96    wanted.is_none_or(|id| entry_session == Some(id))
97}
98
99/// Builds the proof for `session` (or lifetime) from the chains at the given
100/// paths. A missing file is an empty, intact chain.
101pub fn build_from(
102    ledger_path: Option<&Path>,
103    trail_path: Option<&Path>,
104    session: Option<&str>,
105    live: Option<ValueSnapshot>,
106) -> Proof {
107    let ledger_verify = ledger_path.map_or_else(savings_ledger::VerifyResult::empty, |p| {
108        savings_ledger::store::verify(p)
109    });
110    let events: Vec<SavingsEvent> = ledger_path
111        .map(savings_ledger::store::load)
112        .unwrap_or_default();
113
114    let mut proof = Proof {
115        session_id: session.map(str::to_string),
116        ledger: ChainCheck {
117            name: "savings ledger",
118            path: ledger_path.map(|p| p.display().to_string()),
119            entries: ledger_verify.total.max(events.len()),
120            intact: ledger_verify.valid,
121            first_invalid_at: ledger_verify.first_invalid_at,
122        },
123        audit: ChainCheck {
124            name: "audit trail",
125            path: trail_path.map(|p| p.display().to_string()),
126            entries: 0,
127            intact: true,
128            first_invalid_at: None,
129        },
130        tokens_baseline: 0,
131        tokens_saved: 0,
132        tokens_bounced: 0,
133        ledger_evidence: Evidence::default(),
134        security: SecurityCounts::default(),
135        audit_evidence: Evidence::default(),
136        live,
137        active_days: BTreeSet::new(),
138    };
139
140    for ev in &events {
141        if !in_session(ev.session_id.as_deref(), session) {
142            continue;
143        }
144        if ev.saved_tokens == 0 && ev.bounce_adjustment == 0 {
145            continue;
146        }
147        proof.tokens_baseline = proof.tokens_baseline.saturating_add(ev.baseline_tokens);
148        proof.tokens_saved = proof.tokens_saved.saturating_add(ev.saved_tokens);
149        proof.tokens_bounced = proof.tokens_bounced.saturating_add(ev.bounce_adjustment);
150        proof.ledger_evidence.push(&ev.entry_hash);
151        if let Some(day) = ev.ts.get(..10) {
152            proof.active_days.insert(day.to_string());
153        }
154    }
155
156    if let Some(path) = trail_path {
157        let verify = audit_trail::verify_chain_at(path);
158        let entries: Vec<AuditEntry> = audit_trail::load_all_at(path);
159        proof.audit.entries = verify.total_entries.max(entries.len());
160        proof.audit.intact = verify.valid;
161        proof.audit.first_invalid_at = verify.first_invalid_at;
162        for entry in &entries {
163            let Some((kind, n, entry_session)) = entry.action.as_deref().and_then(parse_action)
164            else {
165                continue;
166            };
167            if !in_session(entry_session, session) {
168                continue;
169            }
170            proof.security.add(kind, n);
171            proof.audit_evidence.push(&entry.entry_hash);
172        }
173    }
174    proof
175}
176
177/// The proof over the local chains. `session = None` and `lifetime = false`
178/// picks the most recently active session (from `value/current.json`).
179pub fn build(session: Option<&str>, lifetime: bool) -> Proof {
180    let live = if lifetime {
181        None
182    } else {
183        super::snapshot::load(session)
184    };
185    let session = if lifetime {
186        None
187    } else {
188        session
189            .map(str::to_string)
190            .or_else(|| live.as_ref().map(|s| s.session_id.clone()))
191            .filter(|id| !id.is_empty())
192    };
193    let ledger = savings_ledger::store::default_path();
194    let trail = audit_trail::default_trail_path();
195    build_from(
196        ledger.as_deref(),
197        trail.as_deref(),
198        session.as_deref(),
199        live,
200    )
201}
202
203/// ✓ measured security events since `cutoff` (lifetime when `None`), from the
204/// local audit trail. `None` when the trail fails verification, so a tampered
205/// chain never reaches a report or share card.
206pub fn verified_security_since(cutoff: Option<DateTime<Utc>>) -> Option<SecurityCounts> {
207    security_since_at(&audit_trail::default_trail_path()?, cutoff)
208}
209
210/// ✓ measured lifetime security events together with the audit-trail entry
211/// hashes they rest on. `None` when there is no trail or it fails verification.
212pub fn verified_security_evidence() -> Option<(SecurityCounts, Evidence)> {
213    security_evidence_at(&audit_trail::default_trail_path()?)
214}
215
216fn security_evidence_at(path: &Path) -> Option<(SecurityCounts, Evidence)> {
217    let proof = build_from(None, Some(path), None, None);
218    proof
219        .audit
220        .intact
221        .then_some((proof.security, proof.audit_evidence))
222}
223
224fn security_since_at(path: &Path, cutoff: Option<DateTime<Utc>>) -> Option<SecurityCounts> {
225    if !audit_trail::verify_chain_at(path).valid {
226        return None;
227    }
228    let mut counts = SecurityCounts::default();
229    for entry in audit_trail::load_all_at(path) {
230        if let Some(cutoff) = cutoff {
231            let Ok(ts) = DateTime::parse_from_rfc3339(&entry.timestamp) else {
232                continue;
233            };
234            if ts.with_timezone(&Utc) < cutoff {
235                continue;
236            }
237        }
238        if let Some((kind, n, _)) = entry.action.as_deref().and_then(parse_action) {
239            counts.add(kind, n);
240        }
241    }
242    Some(counts)
243}
244
245fn short(hash: Option<&String>) -> String {
246    hash.map_or_else(|| "—".to_string(), |h| h.chars().take(12).collect())
247}
248
249struct Marks {
250    measured: String,
251    derived: String,
252    ok: String,
253    bad: String,
254}
255
256impl Marks {
257    fn new(style: Style) -> Self {
258        let paint = |code: &str, text: &str| {
259            if style.color {
260                format!("\x1b[{code}m{text}\x1b[0m")
261            } else {
262                text.to_string()
263            }
264        };
265        let (check, approx, cross) = if style.unicode {
266            ("✓", "≈", "✗")
267        } else {
268            ("OK", "~", "FAIL")
269        };
270        Self {
271            measured: paint("32", &format!("{check} measured")),
272            derived: paint("2", &format!("{approx} derived ")),
273            ok: paint("32", check),
274            bad: paint("31", cross),
275        }
276    }
277}
278
279fn chain_line(check: &ChainCheck, marks: &Marks) -> String {
280    if check.intact {
281        format!(
282            "{} {} intact ({} entries)",
283            marks.ok, check.name, check.entries
284        )
285    } else {
286        format!(
287            "{} {} TAMPERED at entry {}",
288            marks.bad,
289            check.name,
290            check.first_invalid_at.unwrap_or(0)
291        )
292    }
293}
294
295/// Human report. Every value line carries its label and source.
296pub fn render(proof: &Proof, style: Style) -> String {
297    let marks = Marks::new(style);
298    let mut out = String::new();
299    let scope = proof
300        .session_id
301        .as_deref()
302        .map_or_else(|| "all sessions".to_string(), |id| format!("session {id}"));
303    out.push_str(&format!("lean-ctx value · {scope}\n\n"));
304
305    if proof.ledger_evidence.entries == 0 && proof.security.is_empty() {
306        out.push_str("  nothing recorded for this scope yet\n");
307    }
308    if proof.ledger_evidence.entries > 0 {
309        out.push_str(&format!(
310            "  {}  {} tokens kept out of context   savings ledger, {} events\n",
311            marks.measured,
312            format_tokens(proof.net_saved()),
313            proof.ledger_evidence.entries
314        ));
315        if proof.tokens_bounced > 0 {
316            out.push_str(&format!(
317                "                 (net of {} tokens re-read by the agent)\n",
318                format_tokens(proof.tokens_bounced)
319            ));
320        }
321        if let Some(pct) = proof.saved_pct() {
322            out.push_str(&format!(
323                "  {}  {pct:.0}% of {} tool-input tokens   net saved ÷ baseline\n",
324                marks.derived,
325                format_tokens(proof.tokens_baseline)
326            ));
327        }
328    }
329    for phrase in security_phrases(&proof.security) {
330        out.push_str(&format!("  {}  {phrase}   audit trail\n", marks.measured));
331    }
332
333    out.push('\n');
334    if proof.ledger_evidence.entries > 0 {
335        out.push_str(&format!(
336            "  evidence  ledger {} … {}\n",
337            short(proof.ledger_evidence.first_hash.as_ref()),
338            short(proof.ledger_evidence.last_hash.as_ref())
339        ));
340    }
341    if proof.audit_evidence.entries > 0 {
342        out.push_str(&format!(
343            "  evidence  audit  {} … {}\n",
344            short(proof.audit_evidence.first_hash.as_ref()),
345            short(proof.audit_evidence.last_hash.as_ref())
346        ));
347    }
348    out.push_str(&format!(
349        "  chains    {}\n",
350        chain_line(&proof.ledger, &marks)
351    ));
352    out.push_str(&format!(
353        "            {}\n",
354        chain_line(&proof.audit, &marks)
355    ));
356
357    if let Some(line) = proof.live.as_ref().and_then(|snap| {
358        super::format::one_line(
359            snap,
360            Style {
361                color: false,
362                ..style
363            },
364        )
365    }) {
366        out.push_str(&format!(
367            "\n  live      {line}\n            (display counters; the chains above are the proof)\n"
368        ));
369    }
370    if proof.tampered() {
371        out.push_str(
372            "\n  A chain failed verification: the numbers above are NOT proof.\n\
373             \x20 Inspect the file at the reported entry; `lean-ctx savings verify` shows details.\n",
374        );
375    }
376    out
377}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382    use crate::core::audit_trail::{AuditEntryData, AuditEventType};
383
384    fn ledger_event(saved: u64, session: Option<&str>) -> SavingsEvent {
385        let mut json = serde_json::json!({
386            "ts": "2026-09-25T10:00:00+00:00",
387            "tool": "ctx_read",
388            "mechanism": "compression",
389            "model_id": "m",
390            "tokenizer": "o200k_base",
391            "baseline_tokens": saved + 100,
392            "actual_tokens": 100,
393            "saved_tokens": saved,
394            "bounce_adjustment": 0,
395            "unit_price_per_m_usd": 3.0,
396            "saved_usd": 0.0,
397            "repo_hash": "r",
398            "agent_id": "a",
399            "prev_hash": "",
400            "entry_hash": "",
401            "version": "3.10.3",
402        });
403        if let Some(id) = session {
404            json["session_id"] = id.into();
405        }
406        serde_json::from_value(json).unwrap()
407    }
408
409    fn security(path: &Path, action: &str) {
410        audit_trail::record_at(
411            path,
412            AuditEntryData {
413                agent_id: "a".into(),
414                tool: "ctx_shell".into(),
415                action: Some(action.into()),
416                input_hash: String::new(),
417                output_tokens: 0,
418                role: "coder".into(),
419                event_type: AuditEventType::SecretDetected,
420            },
421        );
422    }
423
424    fn fixture() -> (tempfile::TempDir, std::path::PathBuf, std::path::PathBuf) {
425        let dir = tempfile::tempdir().unwrap();
426        let ledger = dir.path().join("ledger.jsonl");
427        let trail = dir.path().join("trail.jsonl");
428        savings_ledger::store::append(&ledger, ledger_event(1_000, Some("s1"))).unwrap();
429        savings_ledger::store::append(&ledger, ledger_event(500, Some("s2"))).unwrap();
430        savings_ledger::store::append(&ledger, ledger_event(250, None)).unwrap();
431        security(&trail, "secret_redacted:2|session=s1");
432        security(&trail, "shell_blocked:1|session=s2");
433        security(&trail, "tool_call");
434        (dir, ledger, trail)
435    }
436
437    #[test]
438    fn session_scope_counts_only_that_session() {
439        let (_dir, ledger, trail) = fixture();
440        let proof = build_from(Some(&ledger), Some(&trail), Some("s1"), None);
441        assert!(!proof.tampered());
442        assert_eq!(proof.tokens_saved, 1_000);
443        assert_eq!(proof.ledger_evidence.entries, 1);
444        assert_eq!(proof.security.secrets_redacted, 2);
445        assert_eq!(proof.security.shell_blocked, 0);
446        assert_eq!(proof.audit_evidence.entries, 1);
447        assert_eq!(proof.ledger.entries, 3);
448        assert_eq!(proof.audit.entries, 3);
449    }
450
451    #[test]
452    fn lifetime_scope_counts_everything() {
453        let (_dir, ledger, trail) = fixture();
454        let proof = build_from(Some(&ledger), Some(&trail), None, None);
455        assert_eq!(proof.tokens_saved, 1_750);
456        assert_eq!(proof.security.total(), 3);
457        let text = render(&proof, Style::PLAIN);
458        assert!(text.contains("✓ measured"), "{text}");
459        assert!(text.contains("2 secrets kept out of context"), "{text}");
460        assert!(text.contains("savings ledger intact (3 entries)"), "{text}");
461    }
462
463    #[test]
464    fn tampered_ledger_is_reported() {
465        let (_dir, ledger, trail) = fixture();
466        let raw = std::fs::read_to_string(&ledger).unwrap();
467        std::fs::write(
468            &ledger,
469            raw.replacen("\"saved_tokens\":1000", "\"saved_tokens\":9000", 1),
470        )
471        .unwrap();
472        let proof = build_from(Some(&ledger), Some(&trail), Some("s1"), None);
473        assert!(proof.tampered());
474        assert!(!proof.ledger.intact);
475        let text = render(&proof, Style::PLAIN);
476        assert!(text.contains("TAMPERED"), "{text}");
477        assert!(text.contains("NOT proof"), "{text}");
478    }
479
480    #[test]
481    fn tampered_trail_is_reported() {
482        let (_dir, ledger, trail) = fixture();
483        let raw = std::fs::read_to_string(&trail).unwrap();
484        std::fs::write(
485            &trail,
486            raw.replacen("secret_redacted:2", "secret_redacted:9", 1),
487        )
488        .unwrap();
489        let proof = build_from(Some(&ledger), Some(&trail), None, None);
490        assert!(proof.tampered());
491        assert!(!proof.audit.intact);
492    }
493
494    #[test]
495    fn missing_chains_are_empty_and_intact() {
496        let dir = tempfile::tempdir().unwrap();
497        let proof = build_from(
498            Some(&dir.path().join("none.jsonl")),
499            Some(&dir.path().join("none2.jsonl")),
500            Some("x"),
501            None,
502        );
503        assert!(!proof.tampered());
504        assert!(render(&proof, Style::PLAIN).contains("nothing recorded"));
505    }
506
507    #[test]
508    fn security_since_filters_by_time_and_refuses_a_tampered_trail() {
509        let (_dir, _ledger, trail) = fixture();
510        let all = security_since_at(&trail, None).unwrap();
511        assert_eq!(all.total(), 3);
512        let future = Utc::now() + chrono::Duration::days(1);
513        assert!(security_since_at(&trail, Some(future)).unwrap().is_empty());
514        let past = Utc::now() - chrono::Duration::days(7);
515        assert_eq!(security_since_at(&trail, Some(past)).unwrap(), all);
516
517        let raw = std::fs::read_to_string(&trail).unwrap();
518        std::fs::write(
519            &trail,
520            raw.replacen("secret_redacted:2", "secret_redacted:9", 1),
521        )
522        .unwrap();
523        assert_eq!(security_since_at(&trail, None), None);
524    }
525
526    #[test]
527    fn security_evidence_carries_the_hashes_and_refuses_a_tampered_trail() {
528        let (_dir, _ledger, trail) = fixture();
529        let (counts, evidence) = security_evidence_at(&trail).unwrap();
530        assert_eq!(counts.total(), 3);
531        assert_eq!(evidence.entries, 2);
532        assert!(evidence.first_hash.is_some() && evidence.last_hash.is_some());
533
534        let raw = std::fs::read_to_string(&trail).unwrap();
535        std::fs::write(
536            &trail,
537            raw.replacen("shell_blocked:1", "shell_blocked:5", 1),
538        )
539        .unwrap();
540        assert!(security_evidence_at(&trail).is_none());
541    }
542
543    #[test]
544    fn json_has_labels_tooling_needs() {
545        let (_dir, ledger, trail) = fixture();
546        let proof = build_from(Some(&ledger), Some(&trail), Some("s2"), None);
547        let json = serde_json::to_value(&proof).unwrap();
548        assert_eq!(json["tokens_saved"], 500);
549        assert_eq!(json["security"]["shell_blocked"], 1);
550        assert_eq!(json["ledger"]["intact"], true);
551        assert!(json["ledger_evidence"]["last_hash"].is_string());
552    }
553}