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