Skip to main content

lean_ctx/core/value/
proof.rs

1// SPDX-License-Identifier: Apache-2.0
2//! `lean-ctx value`: every number the value surface shows, re-derived from the
3//! two tamper-evident chains instead of the display counters.
4//!
5//! * Tokens come from the savings ledger (SHA-256 chain, `session_id`
6//!   committed since canonical v7).
7//! * Security events come from the audit trail (SHA-256 chain, Ed25519
8//!   signed; kind, count and session committed in the hashed `action`).
9//!
10//! Both chains are re-walked from genesis first. A broken chain makes the
11//! report *tampered*: the numbers are still printed, but flagged as not proof,
12//! and the CLI exits non-zero.
13
14use std::collections::{BTreeMap, BTreeSet};
15use std::path::Path;
16
17use lean_ctx_time::{OffsetDateTime, UtcDateTime};
18use serde::Serialize;
19
20use crate::core::audit_trail;
21use crate::core::savings_ledger;
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/// First and last `entry_hash` of the chain entries a claim rests on —
38/// anyone can look them up in the JSONL file.
39#[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    /// `None` = lifetime (every session).
59    pub session_id: Option<String>,
60    pub ledger: ChainCheck,
61    pub audit: ChainCheck,
62    /// ✓ measured: counterfactual input tokens of the attributed tool results.
63    pub tokens_baseline: u64,
64    /// ✓ measured: tokens kept out of the model's context.
65    pub tokens_saved: u64,
66    /// ✓ measured: tokens the agent spent re-reading (netted out).
67    pub tokens_bounced: u64,
68    pub ledger_evidence: Evidence,
69    /// ✓ measured: security events committed to the audit trail.
70    pub security: SecurityCounts,
71    pub audit_evidence: Evidence,
72    /// The live display counters, for comparison only — not proof.
73    pub live: Option<ValueSnapshot>,
74    /// UTC days (`YYYY-MM-DD`) with at least one attributed ledger event —
75    /// the evidence behind streak milestones.
76    #[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    /// ≈ derived: share of the attributed input kept out of context.
90    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
100/// Builds the proof for `session` (or lifetime) from the chains at the given
101/// paths. A missing file is an empty, intact chain.
102pub fn build_from(
103    ledger_path: Option<&Path>,
104    trail_path: Option<&Path>,
105    session: Option<&str>,
106    live: Option<ValueSnapshot>,
107) -> Proof {
108    build_scoped(ledger_path, trail_path, session, live, None)
109}
110
111/// [`build_from`] narrowed to one project's ledger events and audit entries
112/// (`None`: every project). An audit entry without a session belongs to no
113/// one project, so a project's proof leaves it out.
114pub fn build_scoped(
115    ledger_path: Option<&Path>,
116    trail_path: Option<&Path>,
117    session: Option<&str>,
118    live: Option<ValueSnapshot>,
119    scope: Option<&savings_ledger::ProjectScope>,
120) -> Proof {
121    let mut proof = empty(ledger_path, trail_path, session, live);
122
123    // One streaming pass checks the chain and sums the events (#2240): the
124    // ledger is never held in memory.
125    if let Some(path) = ledger_path {
126        let (verify, visited) = savings_ledger::store::verify_each(path, |ev| {
127            if !in_session(ev.session_id.as_deref(), session)
128                || scope.is_some_and(|scope| !scope.holds_event(ev))
129                || (ev.saved_tokens == 0 && ev.bounce_adjustment == 0)
130            {
131                return;
132            }
133            add_event(&mut proof, ev);
134        });
135        proof.ledger.entries = verify.total.max(visited);
136        proof.ledger.intact = verify.valid;
137        proof.ledger.first_invalid_at = verify.first_invalid_at;
138    }
139
140    if let Some(path) = trail_path {
141        // The lifetime proof over an intact chain comes from the verifier's
142        // (incremental) state; only a session view or a broken chain reads
143        // the entries again.
144        let (verify, evidence) = audit_trail::verified_security_at(path);
145        proof.audit.entries = verify.total_entries;
146        proof.audit.intact = verify.valid;
147        proof.audit.first_invalid_at = verify.first_invalid_at;
148        if let (None, None, Some(evidence)) = (session, scope, evidence) {
149            proof.security = evidence.counts;
150            proof.audit_evidence = Evidence {
151                entries: evidence.entries,
152                first_hash: evidence.first_hash,
153                last_hash: evidence.last_hash,
154            };
155            return proof;
156        }
157        // A session's entries are not older than the session and carry its
158        // id in the hashed action: segments sealed before it started and
159        // lines without its id cannot hold one of them (#2240).
160        let since = session.and_then(session_started_at);
161        let needle = session.filter(|id| appears_verbatim_in_json(id));
162        let visited = audit_trail::for_each_entry_at(path, since, needle, |entry| {
163            let Some((kind, n, entry_session)) = entry.action.as_deref().and_then(parse_action)
164            else {
165                return;
166            };
167            if !in_session(entry_session, session)
168                || scope.is_some_and(|scope| !scope.holds_session(entry_session))
169            {
170                return;
171            }
172            proof.security.add(kind, n);
173            proof.audit_evidence.push(&entry.entry_hash);
174        });
175        if since.is_none() && needle.is_none() {
176            proof.audit.entries = proof.audit.entries.max(visited);
177        } else if !verify.valid {
178            // A broken or unreadable chain reports every entry still on disk,
179            // as the full read did: rare, so it may read the trail once more.
180            let all = audit_trail::for_each_entry_at(path, None, None, |_| {});
181            proof.audit.entries = proof.audit.entries.max(all);
182        }
183    }
184    proof
185}
186
187/// A proof with nothing counted yet over intact, empty chains.
188fn empty(
189    ledger_path: Option<&Path>,
190    trail_path: Option<&Path>,
191    session: Option<&str>,
192    live: Option<ValueSnapshot>,
193) -> Proof {
194    Proof {
195        session_id: session.map(str::to_string),
196        ledger: ChainCheck {
197            name: "savings ledger",
198            path: ledger_path.map(|p| p.display().to_string()),
199            entries: 0,
200            intact: true,
201            first_invalid_at: None,
202        },
203        audit: ChainCheck {
204            name: "audit trail",
205            path: trail_path.map(|p| p.display().to_string()),
206            entries: 0,
207            intact: true,
208            first_invalid_at: None,
209        },
210        tokens_baseline: 0,
211        tokens_saved: 0,
212        tokens_bounced: 0,
213        ledger_evidence: Evidence::default(),
214        security: SecurityCounts::default(),
215        audit_evidence: Evidence::default(),
216        live,
217        active_days: BTreeSet::new(),
218    }
219}
220
221/// Counts one attributed savings-ledger event into `proof`.
222fn add_event(proof: &mut Proof, ev: &savings_ledger::SavingsEvent) {
223    proof.tokens_baseline = proof.tokens_baseline.saturating_add(ev.baseline_tokens);
224    proof.tokens_saved = proof.tokens_saved.saturating_add(ev.saved_tokens);
225    proof.tokens_bounced = proof.tokens_bounced.saturating_add(ev.bounce_adjustment);
226    proof.ledger_evidence.push(&ev.entry_hash);
227    if let Some(day) = ev.ts.get(..10) {
228        proof.active_days.insert(day.to_string());
229    }
230}
231
232/// The groups (indexes) that hold the session id an entry was recorded under.
233fn holders_of<'a>(holders: &'a BTreeMap<&str, Vec<usize>>, session: Option<&str>) -> &'a [usize] {
234    session
235        .and_then(|id| holders.get(id))
236        .map_or(&[], Vec::as_slice)
237}
238
239/// The proofs of several sessions at once: one per group of session ids (an
240/// app session id with the engine sessions opened under it), in group order.
241///
242/// Each chain is walked and verified once for every group together, so the
243/// cost does not grow with the number of groups: one streaming ledger pass,
244/// one trail verification, one trail pass. A group's evidence is the entries
245/// recorded under any of its ids, first and last in chain order. The chain
246/// checks are those of [`build_from`] and identical in every proof.
247pub fn build_sessions(
248    ledger_path: Option<&Path>,
249    trail_path: Option<&Path>,
250    groups: &[BTreeSet<String>],
251) -> Vec<Proof> {
252    let mut proofs: Vec<Proof> = groups
253        .iter()
254        .map(|_| empty(ledger_path, trail_path, None, None))
255        .collect();
256    // Session id → the groups that hold it (an id may be in several).
257    let mut holders: BTreeMap<&str, Vec<usize>> = BTreeMap::new();
258    for (index, group) in groups.iter().enumerate() {
259        for id in group {
260            holders.entry(id.as_str()).or_default().push(index);
261        }
262    }
263
264    if let Some(path) = ledger_path {
265        let (verify, visited) = savings_ledger::store::verify_each(path, |ev| {
266            if ev.saved_tokens == 0 && ev.bounce_adjustment == 0 {
267                return;
268            }
269            for &index in holders_of(&holders, ev.session_id.as_deref()) {
270                add_event(&mut proofs[index], ev);
271            }
272        });
273        for proof in &mut proofs {
274            proof.ledger.entries = verify.total.max(visited);
275            proof.ledger.intact = verify.valid;
276            proof.ledger.first_invalid_at = verify.first_invalid_at;
277        }
278    }
279
280    if let Some(path) = trail_path {
281        let (verify, _) = audit_trail::verified_security_at(path);
282        // Segments sealed before the oldest session started cannot hold one
283        // of their entries; an id without a start time reads every segment.
284        let since = holders
285            .keys()
286            .map(|id| session_started_at(id))
287            .collect::<Option<Vec<_>>>()
288            .and_then(|starts| starts.into_iter().min());
289        // Only entries recorded under a session can belong to one.
290        audit_trail::for_each_entry_at(path, since, Some("|session="), |entry| {
291            let Some((kind, n, entry_session)) = entry.action.as_deref().and_then(parse_action)
292            else {
293                return;
294            };
295            for &index in holders_of(&holders, entry_session) {
296                proofs[index].security.add(kind, n);
297                proofs[index].audit_evidence.push(&entry.entry_hash);
298            }
299        });
300        let entries = if verify.valid {
301            verify.total_entries
302        } else {
303            // A broken or unreadable chain reports every entry still on disk.
304            verify
305                .total_entries
306                .max(audit_trail::for_each_entry_at(path, None, None, |_| {}))
307        };
308        for proof in &mut proofs {
309            proof.audit.entries = entries;
310            proof.audit.intact = verify.valid;
311            proof.audit.first_invalid_at = verify.first_invalid_at;
312        }
313    }
314    proofs
315}
316
317/// Slack before an engine session's start time (UTC, from its id) within
318/// which the audit trail is still read for it, against clock steps.
319const SESSION_START_SLACK_HOURS: i64 = 24;
320
321/// When the engine session `id` (`YYYYMMDD-HHMMSS…`, UTC; see
322/// `generate_session_id`) started, less [`SESSION_START_SLACK_HOURS`].
323/// `None` for an id in another format: then every segment is read.
324fn session_started_at(id: &str) -> Option<UtcDateTime> {
325    let stamp = id.get(..15)?;
326    let started = lean_ctx_time::parse_civil_datetime(stamp, "%Y%m%d-%H%M%S").ok()?;
327    Some(
328        lean_ctx_time::utc_from_civil(started)?
329            - lean_ctx_time::Duration::hours(SESSION_START_SLACK_HOURS),
330    )
331}
332
333/// Whether `text` is written as-is inside a JSON string, so a line holding
334/// it in a field must contain it byte for byte.
335fn appears_verbatim_in_json(text: &str) -> bool {
336    !text.is_empty()
337        && text
338            .chars()
339            .all(|c| c.is_ascii_graphic() && c != '"' && c != '\\' && c != '/')
340}
341
342/// The proof over the local chains. `session = None` and `lifetime = false`
343/// picks the most recently active session (from `value/current.json`).
344pub fn build(session: Option<&str>, lifetime: bool) -> Proof {
345    let live = if lifetime {
346        None
347    } else {
348        super::snapshot::load(session)
349    };
350    let session = if lifetime {
351        None
352    } else {
353        session
354            .map(str::to_string)
355            .or_else(|| live.as_ref().map(|s| s.session_id.clone()))
356            .filter(|id| !id.is_empty())
357    };
358    let ledger = savings_ledger::store::default_path();
359    let trail = audit_trail::default_trail_path();
360    build_from(
361        ledger.as_deref(),
362        trail.as_deref(),
363        session.as_deref(),
364        live,
365    )
366}
367
368/// The lifetime proof over the local chains for one project.
369pub fn build_lifetime_for(scope: &savings_ledger::ProjectScope) -> Proof {
370    let ledger = savings_ledger::store::default_path();
371    let trail = audit_trail::default_trail_path();
372    build_scoped(ledger.as_deref(), trail.as_deref(), None, None, Some(scope))
373}
374
375/// ✓ measured security events since `cutoff` (lifetime when `None`), from the
376/// local audit trail. `None` when the trail fails verification, so a tampered
377/// chain never reaches a report or share card.
378pub fn verified_security_since(cutoff: Option<UtcDateTime>) -> Option<SecurityCounts> {
379    security_since_at(&audit_trail::default_trail_path()?, cutoff)
380}
381
382/// ✓ measured lifetime security events together with the audit-trail entry
383/// hashes they rest on, for a signed savings-batch tally: only the kinds that
384/// tally carries (see `SecurityCounts::signed_tally_projection`), so the
385/// evidence names exactly the entries the counts rest on. `None` when there is
386/// no trail or it fails verification.
387pub fn verified_security_evidence() -> Option<(SecurityCounts, Evidence)> {
388    security_evidence_at(&audit_trail::default_trail_path()?)
389}
390
391/// Aggregated by the verifying pass itself, so a resumed (checkpointed)
392/// verification reads only the appended entries for the evidence too.
393fn security_evidence_at(path: &Path) -> Option<(SecurityCounts, Evidence)> {
394    let tally = audit_trail::verified_signed_tally_at(path)?;
395    Some((
396        tally.counts,
397        Evidence {
398            entries: tally.entries,
399            first_hash: tally.first_hash,
400            last_hash: tally.last_hash,
401        },
402    ))
403}
404
405fn security_since_at(path: &Path, cutoff: Option<UtcDateTime>) -> Option<SecurityCounts> {
406    if !audit_trail::verify_chain_at(path).valid {
407        return None;
408    }
409    let mut counts = SecurityCounts::default();
410    for entry in audit_trail::load_all_at(path) {
411        if let Some(cutoff) = cutoff {
412            let Ok(ts) = OffsetDateTime::parse_from_rfc3339(&entry.timestamp) else {
413                continue;
414            };
415            if ts.to_utc() < cutoff {
416                continue;
417            }
418        }
419        if let Some((kind, n, _)) = entry.action.as_deref().and_then(parse_action) {
420            counts.add(kind, n);
421        }
422    }
423    Some(counts)
424}
425
426fn short(hash: Option<&String>) -> String {
427    hash.map_or_else(|| "—".to_string(), |h| h.chars().take(12).collect())
428}
429
430struct Marks {
431    measured: String,
432    derived: String,
433    ok: String,
434    bad: String,
435}
436
437impl Marks {
438    fn new(style: Style) -> Self {
439        let paint = |code: &str, text: &str| {
440            if style.color {
441                format!("\x1b[{code}m{text}\x1b[0m")
442            } else {
443                text.to_string()
444            }
445        };
446        let (check, approx, cross) = if style.unicode {
447            ("✓", "≈", "✗")
448        } else {
449            ("OK", "~", "FAIL")
450        };
451        Self {
452            measured: paint("32", &format!("{check} measured")),
453            derived: paint("2", &format!("{approx} derived ")),
454            ok: paint("32", check),
455            bad: paint("31", cross),
456        }
457    }
458}
459
460fn chain_line(check: &ChainCheck, marks: &Marks) -> String {
461    if check.intact {
462        format!(
463            "{} {} intact ({} entries)",
464            marks.ok, check.name, check.entries
465        )
466    } else {
467        format!(
468            "{} {} TAMPERED at entry {}",
469            marks.bad,
470            check.name,
471            check.first_invalid_at.unwrap_or(0)
472        )
473    }
474}
475
476/// Human report. Every value line carries its label and source.
477pub fn render(proof: &Proof, style: Style) -> String {
478    let marks = Marks::new(style);
479    let mut out = String::new();
480    let scope = proof
481        .session_id
482        .as_deref()
483        .map_or_else(|| "all sessions".to_string(), |id| format!("session {id}"));
484    out.push_str(&format!("lean-ctx value · {scope}\n\n"));
485
486    if proof.ledger_evidence.entries == 0 && proof.security.is_empty() {
487        out.push_str("  nothing recorded for this scope yet\n");
488    }
489    if proof.ledger_evidence.entries > 0 {
490        out.push_str(&format!(
491            "  {}  {} tokens kept out of context   savings ledger, {} events\n",
492            marks.measured,
493            format_tokens(proof.net_saved()),
494            proof.ledger_evidence.entries
495        ));
496        if proof.tokens_bounced > 0 {
497            out.push_str(&format!(
498                "                 (net of {} tokens re-read by the agent)\n",
499                format_tokens(proof.tokens_bounced)
500            ));
501        }
502        if let Some(pct) = proof.saved_pct() {
503            out.push_str(&format!(
504                "  {}  {pct:.0}% of {} tool-input tokens   net saved ÷ baseline\n",
505                marks.derived,
506                format_tokens(proof.tokens_baseline)
507            ));
508        }
509    }
510    for phrase in security_phrases(&proof.security) {
511        out.push_str(&format!("  {}  {phrase}   audit trail\n", marks.measured));
512    }
513
514    out.push('\n');
515    if proof.ledger_evidence.entries > 0 {
516        out.push_str(&format!(
517            "  evidence  ledger {} … {}\n",
518            short(proof.ledger_evidence.first_hash.as_ref()),
519            short(proof.ledger_evidence.last_hash.as_ref())
520        ));
521    }
522    if proof.audit_evidence.entries > 0 {
523        out.push_str(&format!(
524            "  evidence  audit  {} … {}\n",
525            short(proof.audit_evidence.first_hash.as_ref()),
526            short(proof.audit_evidence.last_hash.as_ref())
527        ));
528    }
529    out.push_str(&format!(
530        "  chains    {}\n",
531        chain_line(&proof.ledger, &marks)
532    ));
533    out.push_str(&format!(
534        "            {}\n",
535        chain_line(&proof.audit, &marks)
536    ));
537
538    if let Some(line) = proof.live.as_ref().and_then(|snap| {
539        super::format::one_line(
540            snap,
541            Style {
542                color: false,
543                ..style
544            },
545        )
546    }) {
547        out.push_str(&format!(
548            "\n  live      {line}\n            (display counters; the chains above are the proof)\n"
549        ));
550    }
551    if proof.tampered() {
552        out.push_str(
553            "\n  A chain failed verification: the numbers above are NOT proof.\n\
554             \x20 Inspect the file at the reported entry; `lean-ctx savings verify` shows details.\n",
555        );
556    }
557    out
558}
559
560#[cfg(test)]
561mod tests {
562    use super::*;
563    use crate::core::audit_trail::{AuditEntryData, AuditEventType};
564    use crate::core::savings_ledger::SavingsEvent;
565
566    fn ledger_event(saved: u64, session: Option<&str>) -> SavingsEvent {
567        let mut json = serde_json::json!({
568            "ts": "2026-09-25T10:00:00+00:00",
569            "tool": "ctx_read",
570            "mechanism": "compression",
571            "model_id": "m",
572            "tokenizer": "o200k_base",
573            "baseline_tokens": saved + 100,
574            "actual_tokens": 100,
575            "saved_tokens": saved,
576            "bounce_adjustment": 0,
577            "unit_price_per_m_usd": 3.0,
578            "saved_usd": 0.0,
579            "repo_hash": "r",
580            "agent_id": "a",
581            "prev_hash": "",
582            "entry_hash": "",
583            "version": "3.10.3",
584        });
585        if let Some(id) = session {
586            json["session_id"] = id.into();
587        }
588        serde_json::from_value(json).unwrap()
589    }
590
591    fn security(path: &Path, action: &str) {
592        audit_trail::record_at(
593            path,
594            AuditEntryData {
595                agent_id: "a".into(),
596                tool: "ctx_shell".into(),
597                action: Some(action.into()),
598                input_hash: String::new(),
599                output_tokens: 0,
600                role: "coder".into(),
601                event_type: AuditEventType::SecretDetected,
602            },
603        );
604    }
605
606    /// Chains in an isolated data dir, held for the test: the trail's entries
607    /// are signed with this data dir's `lean-ctx` key and verified against
608    /// it, so a parallel test switching the data dir cannot swap the key.
609    fn fixture() -> (
610        crate::core::data_dir::IsolatedDataDir,
611        std::path::PathBuf,
612        std::path::PathBuf,
613    ) {
614        let dir = crate::core::data_dir::isolated_data_dir();
615        let ledger = dir.path().join("ledger.jsonl");
616        let trail = dir.path().join("trail.jsonl");
617        savings_ledger::store::append(&ledger, ledger_event(1_000, Some("s1"))).unwrap();
618        savings_ledger::store::append(&ledger, ledger_event(500, Some("s2"))).unwrap();
619        savings_ledger::store::append(&ledger, ledger_event(250, None)).unwrap();
620        security(&trail, "secret_redacted:2|session=s1");
621        security(&trail, "shell_blocked:1|session=s2");
622        security(&trail, "tool_call");
623        (dir, ledger, trail)
624    }
625
626    #[test]
627    fn session_scope_counts_only_that_session() {
628        let (_dir, ledger, trail) = fixture();
629        let proof = build_from(Some(&ledger), Some(&trail), Some("s1"), None);
630        assert!(!proof.tampered());
631        assert_eq!(proof.tokens_saved, 1_000);
632        assert_eq!(proof.ledger_evidence.entries, 1);
633        assert_eq!(proof.security.secrets_redacted, 2);
634        assert_eq!(proof.security.shell_blocked, 0);
635        assert_eq!(proof.audit_evidence.entries, 1);
636        assert_eq!(proof.ledger.entries, 3);
637        assert_eq!(proof.audit.entries, 3);
638    }
639
640    /// An engine session id carries its UTC start: the session view reads
641    /// only what was sealed after it (less a day of slack) and still counts
642    /// every entry of the session (#2240).
643    #[test]
644    fn engine_session_view_counts_the_same_as_a_full_read() {
645        let (_dir, ledger, trail) = fixture();
646        let id = crate::core::session::SessionState::new().id;
647        savings_ledger::store::append(&ledger, ledger_event(70, Some(&id))).unwrap();
648        security(&trail, &format!("secret_redacted:3|session={id}"));
649        security(&trail, &format!("shell_blocked:1|session={id}x"));
650
651        let proof = build_from(Some(&ledger), Some(&trail), Some(&id), None);
652        assert!(!proof.tampered());
653        assert_eq!(proof.tokens_saved, 70);
654        assert_eq!(proof.ledger_evidence.entries, 1);
655        assert_eq!(proof.ledger.entries, 4);
656        assert_eq!(proof.security.secrets_redacted, 3);
657        assert_eq!(
658            proof.security.shell_blocked, 0,
659            "a longer id is another session"
660        );
661        assert_eq!(proof.audit_evidence.entries, 1);
662        assert_eq!(proof.audit.entries, 5);
663    }
664
665    #[test]
666    fn session_start_comes_from_an_engine_id_less_the_slack() {
667        let started = session_started_at("20261111-195640u478865p2526s0").unwrap();
668        assert_eq!(
669            started,
670            "2026-11-10T19:56:40Z".parse::<UtcDateTime>().unwrap()
671        );
672        assert_eq!(
673            session_started_at("20261111-195640-478865-2526").map(UtcDateTime::to_rfc3339),
674            Some("2026-11-10T19:56:40+00:00".into()),
675            "the legacy id format"
676        );
677        assert_eq!(session_started_at("s1"), None);
678        assert_eq!(session_started_at("claude-7f3e-…"), None);
679    }
680
681    #[test]
682    fn only_ids_json_leaves_unescaped_filter_lines() {
683        assert!(appears_verbatim_in_json("20261111-195640u478865p2526s0"));
684        assert!(!appears_verbatim_in_json(""));
685        for escaped in ["a\"b", "a\\b", "a/b", "a b", "naïve"] {
686            assert!(!appears_verbatim_in_json(escaped), "{escaped}");
687        }
688    }
689
690    /// The streaming pass reports the same chain check as `verify` and still
691    /// sums the events past a break, like the numbers `load` returned.
692    #[test]
693    fn a_broken_ledger_is_flagged_and_still_summed() {
694        let (_dir, ledger, trail) = fixture();
695        let text = std::fs::read_to_string(&ledger).unwrap();
696        std::fs::write(
697            &ledger,
698            text.replacen("\"saved_tokens\":500", "\"saved_tokens\":900", 1),
699        )
700        .unwrap();
701        let expected = savings_ledger::store::verify(&ledger);
702        assert!(!expected.valid);
703
704        let proof = build_from(Some(&ledger), Some(&trail), None, None);
705        assert!(proof.tampered());
706        assert!(!proof.ledger.intact);
707        assert_eq!(proof.ledger.first_invalid_at, expected.first_invalid_at);
708        assert_eq!(proof.ledger.entries, 3);
709        assert_eq!(proof.tokens_saved, 1_000 + 900 + 250);
710    }
711
712    /// A project's proof counts the events recorded in its folders or its
713    /// sessions, over its whole lifetime; entries without a session stay out.
714    #[test]
715    fn project_scope_counts_only_that_projects_events_and_sessions() {
716        let (dir, ledger, trail) = fixture();
717        let project = dir.path().join("project");
718        std::fs::create_dir_all(project.join(".git")).unwrap();
719        let root = project.to_string_lossy().into_owned();
720        let other = dir.path().join("other");
721        std::fs::create_dir_all(other.join(".git")).unwrap();
722        let other_root = other.to_string_lossy().into_owned();
723        let mut folder_event = ledger_event(40, None);
724        folder_event.repo_hash = savings_ledger::hash_folder(&root);
725        savings_ledger::store::append(&ledger, folder_event).unwrap();
726        let scope = savings_ledger::ProjectScope::from_sessions(
727            &project,
728            [("s1", root.as_str()), ("s2", other_root.as_str())].into_iter(),
729        );
730
731        let proof = build_scoped(Some(&ledger), Some(&trail), None, None, Some(&scope));
732        assert!(!proof.tampered());
733        assert_eq!(
734            proof.tokens_saved, 1_040,
735            "session s1 plus the project's folder"
736        );
737        assert_eq!(proof.ledger_evidence.entries, 2);
738        assert_eq!(proof.security.secrets_redacted, 2);
739        assert_eq!(
740            proof.security.shell_blocked, 0,
741            "s2 worked in another project"
742        );
743        assert_eq!(proof.security.total(), 2);
744        assert_eq!(
745            proof.ledger.entries, 4,
746            "the chain check still covers the whole ledger"
747        );
748    }
749
750    #[test]
751    fn lifetime_scope_counts_everything() {
752        let (_dir, ledger, trail) = fixture();
753        let proof = build_from(Some(&ledger), Some(&trail), None, None);
754        assert_eq!(proof.tokens_saved, 1_750);
755        assert_eq!(proof.security.total(), 3);
756        let text = render(&proof, Style::PLAIN);
757        assert!(text.contains("✓ measured"), "{text}");
758        assert!(text.contains("2 secrets kept out of context"), "{text}");
759        assert!(text.contains("savings ledger intact (3 entries)"), "{text}");
760    }
761
762    #[test]
763    fn tampered_ledger_is_reported() {
764        let (_dir, ledger, trail) = fixture();
765        let raw = std::fs::read_to_string(&ledger).unwrap();
766        std::fs::write(
767            &ledger,
768            raw.replacen("\"saved_tokens\":1000", "\"saved_tokens\":9000", 1),
769        )
770        .unwrap();
771        let proof = build_from(Some(&ledger), Some(&trail), Some("s1"), None);
772        assert!(proof.tampered());
773        assert!(!proof.ledger.intact);
774        let text = render(&proof, Style::PLAIN);
775        assert!(text.contains("TAMPERED"), "{text}");
776        assert!(text.contains("NOT proof"), "{text}");
777    }
778
779    #[test]
780    fn tampered_trail_is_reported() {
781        let (_dir, ledger, trail) = fixture();
782        let raw = std::fs::read_to_string(&trail).unwrap();
783        std::fs::write(
784            &trail,
785            raw.replacen("secret_redacted:2", "secret_redacted:9", 1),
786        )
787        .unwrap();
788        let proof = build_from(Some(&ledger), Some(&trail), None, None);
789        assert!(proof.tampered());
790        assert!(!proof.audit.intact);
791    }
792
793    /// A session view of a broken trail reports every entry on disk, as the
794    /// lifetime view and the full read before #2240 did, not the break index.
795    #[test]
796    fn a_session_view_of_a_tampered_trail_counts_every_entry() {
797        let (_dir, ledger, trail) = fixture();
798        let raw = std::fs::read_to_string(&trail).unwrap();
799        std::fs::write(
800            &trail,
801            raw.replacen("secret_redacted:2", "secret_redacted:9", 1),
802        )
803        .unwrap();
804        let lifetime = build_from(Some(&ledger), Some(&trail), None, None);
805        let session = build_from(Some(&ledger), Some(&trail), Some("s2"), None);
806        assert!(!session.audit.intact);
807        assert_eq!(
808            session.audit.first_invalid_at,
809            lifetime.audit.first_invalid_at
810        );
811        assert_eq!(session.audit.entries, lifetime.audit.entries);
812        assert_eq!(session.audit.entries, 3);
813    }
814
815    #[test]
816    fn missing_chains_are_empty_and_intact() {
817        let dir = tempfile::tempdir().unwrap();
818        let proof = build_from(
819            Some(&dir.path().join("none.jsonl")),
820            Some(&dir.path().join("none2.jsonl")),
821            Some("x"),
822            None,
823        );
824        assert!(!proof.tampered());
825        assert!(render(&proof, Style::PLAIN).contains("nothing recorded"));
826    }
827
828    #[test]
829    fn security_since_filters_by_time_and_refuses_a_tampered_trail() {
830        let (_dir, _ledger, trail) = fixture();
831        let all = security_since_at(&trail, None).unwrap();
832        assert_eq!(all.total(), 3);
833        let future = UtcDateTime::now() + lean_ctx_time::Duration::days(1);
834        assert!(security_since_at(&trail, Some(future)).unwrap().is_empty());
835        let past = UtcDateTime::now() - lean_ctx_time::Duration::days(7);
836        assert_eq!(security_since_at(&trail, Some(past)).unwrap(), all);
837
838        let raw = std::fs::read_to_string(&trail).unwrap();
839        std::fs::write(
840            &trail,
841            raw.replacen("secret_redacted:2", "secret_redacted:9", 1),
842        )
843        .unwrap();
844        assert_eq!(security_since_at(&trail, None), None);
845    }
846
847    #[test]
848    fn security_evidence_carries_the_hashes_and_refuses_a_tampered_trail() {
849        let (_dir, _ledger, trail) = fixture();
850        let (counts, evidence) = security_evidence_at(&trail).unwrap();
851        assert_eq!(counts.total(), 3);
852        assert_eq!(evidence.entries, 2);
853        assert!(evidence.first_hash.is_some() && evidence.last_hash.is_some());
854
855        let raw = std::fs::read_to_string(&trail).unwrap();
856        std::fs::write(
857            &trail,
858            raw.replacen("shell_blocked:1", "shell_blocked:5", 1),
859        )
860        .unwrap();
861        assert!(security_evidence_at(&trail).is_none());
862    }
863
864    /// The evidence a full parse of the trail yields (the pre-checkpoint
865    /// algorithm): the reference the incremental aggregate must reproduce.
866    fn full_parse_evidence(path: &Path) -> (SecurityCounts, Evidence) {
867        let mut counts = SecurityCounts::default();
868        let mut evidence = Evidence::default();
869        for entry in audit_trail::load_all_at(path) {
870            if let Some((kind, n, _)) = entry.action.as_deref().and_then(parse_action) {
871                if kind.in_signed_tally() {
872                    counts.add(kind, n);
873                    evidence.push(&entry.entry_hash);
874                }
875            }
876        }
877        (counts, evidence)
878    }
879
880    /// In the data dir the evidence comes from the checkpointed pass, which
881    /// reads only appended entries; after every append it must serialize
882    /// byte-identically to a full parse.
883    #[test]
884    fn resumed_security_evidence_matches_a_full_parse_after_appends() {
885        let iso = crate::core::data_dir::isolated_data_dir();
886        let trail = audit_trail::default_trail_path().unwrap();
887        let bytes = |(counts, evidence): &(SecurityCounts, Evidence)| {
888            serde_json::to_string(&(counts, evidence)).unwrap()
889        };
890        security(&trail, "pii_redacted:4");
891        assert_eq!(
892            bytes(&security_evidence_at(&trail).unwrap()),
893            bytes(&full_parse_evidence(&trail))
894        );
895        let checkpoints = iso.path().join("audit").join("verified");
896        assert!(
897            std::fs::read_dir(&checkpoints).unwrap().next().is_some(),
898            "the first pass leaves a checkpoint to resume from"
899        );
900        for action in [
901            "secret_redacted:2|session=s1",
902            "tool_call",
903            "shell_blocked:1",
904            "path_blocked:3|session=s2",
905        ] {
906            security(&trail, action);
907            assert_eq!(
908                bytes(&security_evidence_at(&trail).unwrap()),
909                bytes(&full_parse_evidence(&trail)),
910                "after appending {action}"
911            );
912        }
913        assert_eq!(security_evidence_at(&trail).unwrap().1.entries, 3);
914    }
915
916    /// The lifetime proof takes its security counts and evidence from the
917    /// verifier's (resumed) state instead of reading the trail again; it must
918    /// equal a full parse after every append, every kind included.
919    #[test]
920    fn lifetime_proof_from_the_verified_state_matches_a_full_parse() {
921        let _iso = crate::core::data_dir::isolated_data_dir();
922        let trail = audit_trail::default_trail_path().unwrap();
923        let bytes = |counts: &SecurityCounts, evidence: &Evidence| {
924            serde_json::to_string(&(counts, evidence)).unwrap()
925        };
926        for action in [
927            "pii_redacted:4",
928            "secret_redacted:2|session=s1",
929            "tool_call",
930            "shell_blocked:1",
931            "path_blocked:3|session=s2",
932        ] {
933            security(&trail, action);
934            let proof = build_from(None, Some(&trail), None, None);
935            let mut counts = SecurityCounts::default();
936            let mut evidence = Evidence::default();
937            for entry in audit_trail::load_all_at(&trail) {
938                if let Some((kind, n, _)) = entry.action.as_deref().and_then(parse_action) {
939                    counts.add(kind, n);
940                    evidence.push(&entry.entry_hash);
941                }
942            }
943            assert_eq!(
944                bytes(&proof.security, &proof.audit_evidence),
945                bytes(&counts, &evidence),
946                "after appending {action}"
947            );
948            assert_eq!(proof.audit.entries, audit_trail::load_all_at(&trail).len());
949            assert!(!proof.tampered());
950        }
951    }
952
953    /// Several session groups in one pass count what one pass per session
954    /// counts; a group counts every id it holds, first and last in chain order.
955    #[test]
956    fn session_groups_count_like_one_pass_per_session() {
957        let (_dir, ledger, trail) = fixture();
958        let group = |ids: &[&str]| ids.iter().map(|id| (*id).to_owned()).collect();
959        let groups: Vec<BTreeSet<String>> =
960            vec![group(&["s1"]), group(&["s1", "s2"]), group(&["nobody"])];
961        let mut proofs = build_sessions(Some(&ledger), Some(&trail), &groups);
962        let s1 = build_from(Some(&ledger), Some(&trail), Some("s1"), None);
963        let s2 = build_from(Some(&ledger), Some(&trail), Some("s2"), None);
964        let json = |p: &Proof| serde_json::to_value(p).unwrap();
965
966        proofs[0].session_id = Some("s1".into());
967        assert_eq!(json(&proofs[0]), json(&s1));
968
969        let both = &proofs[1];
970        assert_eq!(both.tokens_saved, 1_500);
971        assert_eq!(both.ledger_evidence.entries, 2);
972        assert_eq!(
973            both.ledger_evidence.first_hash,
974            s1.ledger_evidence.first_hash
975        );
976        assert_eq!(both.ledger_evidence.last_hash, s2.ledger_evidence.last_hash);
977        assert_eq!(both.security.secrets_redacted, 2);
978        assert_eq!(both.security.shell_blocked, 1);
979        assert_eq!(both.audit_evidence.entries, 2);
980
981        let nobody = &proofs[2];
982        assert_eq!(nobody.ledger_evidence.entries, 0);
983        assert_eq!(nobody.audit_evidence.entries, 0);
984        assert_eq!(nobody.ledger.entries, 3);
985        assert_eq!(nobody.audit.entries, 3);
986        assert!(!nobody.tampered());
987    }
988
989    #[test]
990    fn json_has_labels_tooling_needs() {
991        let (_dir, ledger, trail) = fixture();
992        let proof = build_from(Some(&ledger), Some(&trail), Some("s2"), None);
993        let json = serde_json::to_value(&proof).unwrap();
994        assert_eq!(json["tokens_saved"], 500);
995        assert_eq!(json["security"]["shell_blocked"], 1);
996        assert_eq!(json["ledger"]["intact"], true);
997        assert!(json["ledger_evidence"]["last_hash"].is_string());
998    }
999}