lean-ctx 3.9.17

Context Runtime for AI Agents with CCP. 71 MCP tools, 10 read modes, 95+ compression patterns, cross-session memory (CCP), persistent AI knowledge with temporal facts + contradiction detection, multi-agent context sharing, LITM-aware positioning, AAAK compact format, adaptive compression with Thompson Sampling bandits. Supports 24+ AI tools. Reduces LLM token consumption by up to 99%.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
//! Verified Savings Ledger (G1) — the per-event, auditable counterfactual store.
//!
//! Local-only and on by default (set `LEAN_CTX_SAVINGS_LEDGER=off` to disable). It never
//! leaves the machine; opt-in org roll-up + cryptographic signing are later phases. See
//! `docs/business/03-verified-savings-ledger.md`.

pub mod combined;
pub mod event;
pub mod evidence_projection;
pub mod push;
pub mod roi;
pub mod signed_batch;
pub mod store;

#[cfg(test)]
mod migration_tests;

pub use combined::CombinedSavingsReport;
pub use event::{MECHANISM_CACHING, MECHANISM_COMPRESSION, MECHANISM_ROUTING, SavingsEvent};
pub use evidence_projection::{
    LedgerAttributionLinkV2, LedgerEvidenceProjectionV2, LedgerEvidenceSourceBindingV2,
    LedgerProjectionErrorV2, VerifiedLedgerSnapshotV2, load_projection_artifact_v2,
    project_settlement_attribution_v2,
};
pub use roi::{RoiReport, roi_report};
pub use signed_batch::{BatchVerifyResult, SignedSavingsBatchV1};
pub use store::{
    LedgerSnapshotReadErrorV2, LedgerSummary, VerifyResult, read_verified_snapshot_v2,
};

use std::sync::OnceLock;

use crate::core::ocla::unified_ledger::{FileUnifiedLedger, UnifiedLedger};

fn enabled() -> bool {
    enabled_from(std::env::var("LEAN_CTX_SAVINGS_LEDGER").ok().as_deref())
}

/// Pure opt-out logic (testable without mutating process env). Enabled unless explicitly
/// set to a falsy value.
fn enabled_from(value: Option<&str>) -> bool {
    match value {
        Some(v) => !matches!(
            v.trim().to_lowercase().as_str(),
            "off" | "0" | "false" | "no"
        ),
        None => true,
    }
}

/// Resolved (model_key, input_price_per_m) for this process. The active model is stable
/// within a process, so we resolve the pricing table once.
fn model_and_price() -> &'static (String, f64) {
    static CACHE: OnceLock<(String, f64)> = OnceLock::new();
    CACHE.get_or_init(|| {
        let resolved = std::env::var("LEAN_CTX_MODEL")
            .or_else(|_| std::env::var("LCTX_MODEL"))
            .ok()
            .filter(|s| !s.trim().is_empty())
            // No explicit model → value savings against the real model the proxy
            // measured most, instead of the blended fallback (cross-process hint
            // from `proxy_usage.json`). Falls back to blended when absent.
            .or_else(crate::proxy::usage_meter::persisted_dominant_model);
        let quote =
            crate::core::gain::model_pricing::ModelPricing::load().quote(resolved.as_deref());
        (quote.model_key, quote.cost.input_per_m)
    })
}

/// Privacy-preserving repo attribution: truncated SHA-256 of the process working
/// directory. Never the file path or contents. Process-scoped (cached once).
fn repo_hash() -> &'static str {
    static CACHE: OnceLock<String> = OnceLock::new();
    CACHE.get_or_init(|| {
        use sha2::{Digest, Sha256};
        let cwd = std::env::current_dir()
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_default();
        let mut hasher = Sha256::new();
        hasher.update(cwd.as_bytes());
        let hex = crate::core::agent_identity::hex_encode(&hasher.finalize());
        hex.get(..16).unwrap_or(&hex).to_string()
    })
}

fn agent_id() -> &'static str {
    crate::core::agent_identity::current_agent_id()
}

/// The tokenizer family the **ledger** denominates savings in: the active
/// model's own family, so recorded tokens (and the USD derived from them) match
/// the units the provider actually bills (#685). Resolved once per process from
/// the same model `model_and_price` resolves — for the default O200kBase model
/// (OpenAI/Cursor/unknown) this is `o200k_base`, so the common path is unchanged.
pub(crate) fn ledger_family() -> crate::core::tokens::TokenizerFamily {
    static CACHE: OnceLock<crate::core::tokens::TokenizerFamily> = OnceLock::new();
    *CACHE.get_or_init(|| crate::core::tokens::detect_tokenizer(&model_and_price().0))
}

/// Count `text` in the ledger's tokenizer family (the active model's own) so
/// recorded savings are model-correct (#685). For the default O200kBase model
/// this is byte-identical to [`crate::core::tokens::count_tokens`] — same BPE,
/// same cache key — so the common path keeps its exact o200k numbers at zero
/// extra cost; only a resolved Claude/Gemini/Llama model triggers re-tokenizing.
///
/// NOTE: this is for the **internal ledger only**. Tool-output framing/footers
/// must stay on `count_tokens` (o200k) to keep outputs byte-stable for provider
/// prompt caching (#498) — do not route those through here.
pub fn count_for_ledger(text: &str) -> usize {
    crate::core::tokens::count_tokens_for(text, ledger_family())
}

/// The tokenizer family that produced the token counts we record (G2). Resolved
/// once — now the active model's family (see [`ledger_family`]), so the ledger no
/// longer claims `o200k_base` for a Claude/Gemini run it measured differently.
fn tokenizer() -> &'static str {
    static CACHE: OnceLock<String> = OnceLock::new();
    CACHE.get_or_init(|| ledger_family().to_string())
}

/// Shared event skeleton with the per-process attribution + pricing context filled in.
/// Chain hashes are computed by `store::append`.
fn new_event(tool: &str) -> SavingsEvent {
    let (model_id, price_per_m) = model_and_price();
    let evidence_class = if tool == "proxy_route" {
        event::EvidenceClass::Approximated
    } else {
        event::EvidenceClass::Measured
    };
    SavingsEvent {
        ts: chrono::Utc::now().to_rfc3339(),
        tool: tool.to_string(),
        mechanism: event::MECHANISM_COMPRESSION.to_string(),
        model_id: model_id.clone(),
        tokenizer: tokenizer().to_string(),
        baseline_tokens: 0,
        actual_tokens: 0,
        saved_tokens: 0,
        bounce_adjustment: 0,
        unit_price_per_m_usd: *price_per_m,
        saved_usd: 0.0,
        repo_hash: repo_hash().to_string(),
        agent_id: agent_id().to_string(),
        prev_hash: String::new(),
        entry_hash: String::new(),
        version: env!("CARGO_PKG_VERSION").to_string(),
        intent_tag: None,
        outcome: None,
        model_original: None,
        model_routed: None,
        routing_savings: None,
        response_original_tokens: None,
        response_delivered_tokens: None,
        agent_chain_id: None,
        chain_depth: None,
        measurement_method: Some(event::MeasurementMethod::DirectCount),
        evidence_class: Some(evidence_class),
        confidence: None,
        request_id: None,
        session_id: None,
        trace_id: None,
        quality_signal: None,
        attribution_group: None,
        attribution_id: None,
        baseline_ref: None,
        price_version: None,
        customer_approval: None,
        settlement_status: None,
        is_first_inject: None,
        cache_read_per_m_usd: None,
        cache_write_per_m_usd: None,
    }
}

fn append_with_unified(path: &std::path::Path, event: SavingsEvent, efficiency_etpao: Option<u64>) {
    let Ok(event) = store::append(path, event) else {
        return;
    };
    let unified = FileUnifiedLedger::from_savings_event(&event).and_then(|mut event| {
        event.efficiency_etpao = efficiency_etpao;
        FileUnifiedLedger::from_data_dir()?.record_unified(event)
    });
    if let Err(error) = unified {
        tracing::warn!(%error, "failed to dual-write unified savings event");
    }
}

fn compression_quality_signal(original: usize, compressed: usize) -> Option<String> {
    if original == 0 {
        return None;
    }
    let ratio = 1.0 - (compressed as f64 / original as f64);
    let signal = match ratio {
        r if r >= 0.7 => "excellent",
        r if r >= 0.5 => "good",
        r if r >= 0.3 => "moderate",
        _ => "marginal",
    };
    Some(signal.to_owned())
}

/// Best-effort append of one auditable savings event for a value-producing read.
/// Skips zero-saving events (keeps the ledger meaningful and cheap) and never panics.
pub fn record_read_event(
    original_tokens: usize,
    saved_tokens: usize,
    quality_signal: Option<&str>,
    efficiency_etpao: Option<u64>,
) {
    record_tool_event(
        "ctx_read",
        original_tokens,
        original_tokens.saturating_sub(saved_tokens),
        quality_signal,
        efficiency_etpao,
    );
}

/// Best-effort append of one auditable savings event for any non-read tool
/// (GL #479 D2: shell, grep/search, …). Callers MUST pass the **measured**
/// baseline — the raw tokens the uncompressed output would have cost — never a
/// counterfactual estimate (e.g. the search 2.5x factor stays out of here, so
/// `lean-ctx ledger verify` only ever attests measured numbers). Skips events
/// where compression saved nothing and never panics.
pub fn record_tool_event(
    tool: &str,
    baseline_tokens: usize,
    actual_tokens: usize,
    quality_signal: Option<&str>,
    efficiency_etpao: Option<u64>,
) {
    let saved = baseline_tokens.saturating_sub(actual_tokens);
    if saved == 0 || !enabled() {
        return;
    }
    let Some(path) = store::default_path() else {
        return;
    };

    let mut event = new_event(tool);
    event.attribution_group = Some(
        crate::core::attribution::attribution_group_for_mechanism(&event.mechanism).to_string(),
    );
    event.baseline_tokens = baseline_tokens as u64;
    event.actual_tokens = actual_tokens as u64;
    event.saved_tokens = saved as u64;
    event.saved_usd = saved as f64 / 1_000_000.0 * event.unit_price_per_m_usd;
    event.confidence = Some(1.0);
    event.quality_signal = quality_signal
        .map(str::to_owned)
        .or_else(|| compression_quality_signal(baseline_tokens, actual_tokens));
    append_with_unified(&path, event, efficiency_etpao);
}

/// Like `record_tool_event` but with G8 token-stream attribution (#1191).
/// `is_first_inject`: `true` for first read of a path (cache_write rate),
/// `false` for subsequent reads (cache_read rate).
pub fn record_tool_event_with_stream(
    tool: &str,
    baseline_tokens: usize,
    actual_tokens: usize,
    is_first_inject: bool,
) {
    let saved = baseline_tokens.saturating_sub(actual_tokens);
    if saved == 0 || !enabled() {
        return;
    }
    let Some(path) = store::default_path() else {
        return;
    };

    let quote = crate::core::gain::model_pricing::ModelPricing::load().quote(None);
    let mut event = new_event(tool);
    event.attribution_group = Some(
        crate::core::attribution::attribution_group_for_mechanism(&event.mechanism).to_string(),
    );
    event.baseline_tokens = baseline_tokens as u64;
    event.actual_tokens = actual_tokens as u64;
    event.saved_tokens = saved as u64;
    event.saved_usd = saved as f64 / 1_000_000.0 * event.unit_price_per_m_usd;
    event.confidence = Some(1.0);
    event.is_first_inject = Some(is_first_inject);
    event.cache_read_per_m_usd = Some(quote.cost.cache_read_per_m);
    event.cache_write_per_m_usd = Some(quote.cost.cache_write_per_m);
    append_with_unified(&path, event, None);
}

/// Best-effort append of a *routing* savings event (enterprise#13/#19): the gateway served
/// the request with a cheaper model than requested. Unlike compression events the saving is
/// a **rate** difference on the same tokens, so the caller passes the measured input tokens
/// plus both models; the event is valued with the shared ledger attribution formula
/// (`eval_ab::routing_eval::routing_saving_usd`). Negative-value routes (an upgrade) are
/// recorded too — the ledger never hides regressions. Skips only true no-ops.
pub fn record_routing_event(requested_model: &str, serving_model: &str, input_tokens: u64) {
    if input_tokens == 0 || requested_model == serving_model || !enabled() {
        return;
    }
    let Some(path) = store::default_path() else {
        return;
    };

    let pricing = crate::core::gain::model_pricing::ModelPricing::load();
    let saved_usd = crate::core::eval_ab::routing_eval::routing_saving_usd(
        &pricing,
        requested_model,
        serving_model,
        input_tokens,
    );
    if saved_usd == 0.0 {
        return; // same rate — nothing to attribute
    }

    let mut event = new_event("proxy_route");
    event.mechanism = event::MECHANISM_ROUTING.to_string();
    event.attribution_group = Some(
        crate::core::attribution::attribution_group_for_mechanism(event::MECHANISM_ROUTING)
            .to_string(),
    );
    // The event is denominated in the *serving* model (what actually ran); the
    // rate delta to the requested model is captured in saved_usd.
    let quote = pricing.quote(Some(serving_model));
    event.model_id = quote.model_key;
    event.unit_price_per_m_usd = quote.cost.input_per_m;
    event.model_original = Some(requested_model.to_string());
    event.model_routed = Some(serving_model.to_string());
    event.baseline_tokens = input_tokens;
    event.actual_tokens = input_tokens;
    event.routing_savings = Some(event.baseline_tokens.saturating_sub(event.actual_tokens));
    // saved_tokens stays 0: routing saves dollars at equal tokens. Token
    // savings remain the compression mechanism's dimension.
    event.saved_usd = saved_usd;
    append_with_unified(&path, event, None);
}

/// Best-effort append of a *caching* savings event: provider prompt-cache reads billed
/// below the input rate. `discount_usd` must be the measured price difference
/// (input rate − cache-read rate) × cache-read tokens for the serving model.
pub fn record_caching_event(model: &str, cache_read_tokens: u64, discount_usd: f64) {
    if cache_read_tokens == 0 || discount_usd <= 0.0 || !enabled() {
        return;
    }
    let Some(path) = store::default_path() else {
        return;
    };

    let mut event = new_event("proxy_cache");
    event.mechanism = event::MECHANISM_CACHING.to_string();
    event.attribution_group = Some(
        crate::core::attribution::attribution_group_for_mechanism(event::MECHANISM_CACHING)
            .to_string(),
    );
    let quote = crate::core::gain::model_pricing::ModelPricing::load().quote(Some(model));
    event.model_id = quote.model_key;
    event.unit_price_per_m_usd = quote.cost.input_per_m;
    event.baseline_tokens = cache_read_tokens;
    event.actual_tokens = cache_read_tokens;
    event.saved_usd = discount_usd;
    append_with_unified(&path, event, None);
}

/// Best-effort append of a *bounce* event (G7): a compressed read later invalidated by a
/// full re-read, so the earlier saving was (partly) illusory. Recorded as a negative
/// adjustment with `tool = "bounce"` so totals net out without editing the original entry.
pub fn record_bounce_event(wasted_tokens: usize) {
    if wasted_tokens == 0 || !enabled() {
        return;
    }
    let Some(path) = store::default_path() else {
        return;
    };
    let wasted = wasted_tokens as u64;

    let mut event = new_event("bounce");
    event.attribution_group = Some(
        crate::core::attribution::attribution_group_for_mechanism(&event.mechanism).to_string(),
    );
    event.baseline_tokens = wasted;
    event.actual_tokens = wasted;
    event.bounce_adjustment = wasted;
    event.saved_usd = -(wasted as f64 / 1_000_000.0 * event.unit_price_per_m_usd);
    append_with_unified(&path, event, None);
}

/// Total bounce-adjusted tokens recorded, optionally limited to the last `days` (by event
/// timestamp). `None` = all time. Used to net the Wrapped headline per period.
pub fn bounce_tokens(days: Option<u32>) -> u64 {
    let Some(path) = store::default_path() else {
        return 0;
    };
    store::bounce_tokens_since(&path, days)
}

/// Aggregated totals + model/day/tool slices over the whole ledger.
pub fn summary() -> LedgerSummary {
    store::default_path()
        .map(|p| store::summarize(&p))
        .unwrap_or_default()
}

/// Per-day `(day, bounce_events, read_events)` for the last `days` days —
/// the dashboard's "is the system learning?" trend (#507).
pub fn daily_bounce_trend(days: u32) -> Vec<(String, u64, u64)> {
    store::default_path()
        .map(|p| store::daily_bounce_trend(&p, days))
        .unwrap_or_default()
}

/// Re-walks the hash chain and reports whether it is intact.
pub fn verify() -> VerifyResult {
    store::default_path().map_or_else(VerifyResult::empty, |p| store::verify(&p))
}

/// Re-hashes the ledger under the current (v2) canonical scheme, repairing a chain broken by
/// the legacy float round-trip bug. Returns the number of re-chained events (0 if no ledger).
pub fn rechain() -> std::io::Result<usize> {
    match store::default_path() {
        Some(p) if p.exists() => store::rechain(&p),
        _ => Ok(0),
    }
}

/// Every recorded event (for `ledger export`).
pub fn all_events() -> Vec<SavingsEvent> {
    store::default_path()
        .map(|p| store::load(&p))
        .unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn opt_out_logic_is_correct() {
        assert!(enabled_from(None), "enabled by default when unset");
        assert!(enabled_from(Some("on")));
        assert!(enabled_from(Some("1")));
        assert!(!enabled_from(Some("off")));
        assert!(!enabled_from(Some("0")));
        assert!(!enabled_from(Some("false")));
        assert!(!enabled_from(Some(" No ")), "trim + case-insensitive");
    }

    #[test]
    fn repo_hash_is_truncated_hex() {
        let h = repo_hash();
        assert_eq!(h.len(), 16);
        assert!(h.chars().all(|c| c.is_ascii_hexdigit()));
    }

    /// #685: ledger counts are model-correct via a *real* BPE for the resolved
    /// family — never a fabricated scalar. Robust regardless of which model this
    /// process resolved to (the count always matches `count_tokens_for`).
    #[test]
    fn count_for_ledger_is_a_real_bpe_count_for_resolved_family() {
        let text = "fn honest_accounting(n: u64) -> u64 { n }";
        assert_eq!(
            count_for_ledger(text),
            crate::core::tokens::count_tokens_for(text, ledger_family())
        );
        assert!(count_for_ledger(text) > 0);
        assert_eq!(count_for_ledger(""), 0);
    }

    /// The honest tokenizer label the ledger stamps on every event matches the
    /// family its counts are denominated in — no more hardcoded `o200k_base` for
    /// a Claude/Gemini run (#685).
    #[test]
    fn tokenizer_label_matches_ledger_family() {
        assert_eq!(tokenizer(), ledger_family().to_string());
    }

    #[test]
    fn test_quality_signal_excellent() {
        assert_eq!(
            compression_quality_signal(100, 30).as_deref(),
            Some("excellent")
        );
    }

    #[test]
    fn test_quality_signal_good() {
        assert_eq!(compression_quality_signal(100, 50).as_deref(), Some("good"));
        assert_eq!(compression_quality_signal(100, 31).as_deref(), Some("good"));
    }

    #[test]
    fn test_quality_signal_moderate() {
        assert_eq!(
            compression_quality_signal(100, 70).as_deref(),
            Some("moderate")
        );
        assert_eq!(
            compression_quality_signal(100, 51).as_deref(),
            Some("moderate")
        );
    }

    #[test]
    fn test_quality_signal_marginal() {
        assert_eq!(
            compression_quality_signal(100, 71).as_deref(),
            Some("marginal")
        );
        assert_eq!(compression_quality_signal(0, 0), None);
    }

    #[test]
    fn test_record_tool_event_carries_quality() {
        let _lock = crate::core::data_dir::test_env_lock();
        let dir =
            std::env::temp_dir().join(format!("lctx-ledger-quality-test-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).expect("mkdir");
        crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());

        record_tool_event("cli_shell", 100, 20, Some("verified"), Some(800));

        let ledger = dir.join("savings").join("ledger.jsonl");
        let content = std::fs::read_to_string(&ledger).expect("ledger written");
        let unified_path = dir.join("savings").join("unified_ledger.jsonl");
        let unified_content =
            std::fs::read_to_string(&unified_path).expect("unified ledger written");
        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
        let _ = std::fs::remove_dir_all(&dir);

        let event: SavingsEvent =
            serde_json::from_str(content.lines().next().unwrap()).expect("valid event JSON");
        assert_eq!(event.quality_signal.as_deref(), Some("verified"));

        let unified: crate::core::ocla::unified_ledger::UnifiedSavingsEventV2 =
            serde_json::from_str(unified_content.lines().next().unwrap())
                .expect("valid unified event JSON");
        assert_eq!(unified.efficiency_etpao, Some(800));
    }

    /// GL #479 D2: tool events must never panic and must skip the degenerate
    /// cases (no saving / inverted inputs) so the ledger only carries value.
    #[test]
    fn record_tool_event_skips_zero_and_inverted_savings() {
        // actual >= baseline → saved == 0 → no-op (must not panic or write).
        record_tool_event("cli_shell", 100, 100, None, None);
        record_tool_event("ctx_search", 50, 80, None, None);
        record_tool_event("cli_shell", 0, 0, None, None);
    }

    /// GL #479 D2 wiring proof: a measured shell/search saving lands in the
    /// ledger with the *raw* baseline and the right tool tag.
    #[test]
    fn record_tool_event_appends_measured_event() {
        let _lock = crate::core::data_dir::test_env_lock();
        let dir = std::env::temp_dir().join(format!("lctx-ledger-test-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).expect("mkdir");
        crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());

        record_tool_event("cli_shell", 5000, 800, None, None);

        let ledger = dir.join("savings").join("ledger.jsonl");
        let content = std::fs::read_to_string(&ledger).expect("ledger written");
        let unified_path = dir.join("savings").join("unified_ledger.jsonl");
        let unified_content =
            std::fs::read_to_string(&unified_path).expect("unified ledger written");
        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
        let _ = std::fs::remove_dir_all(&dir);

        let last = content.lines().last().expect("one event");
        let ev: SavingsEvent = serde_json::from_str(last).expect("valid event JSON");
        assert_eq!(ev.tool, "cli_shell");
        assert_eq!(ev.mechanism, MECHANISM_COMPRESSION);
        assert_eq!(ev.baseline_tokens, 5000, "raw baseline, no estimate factor");
        assert_eq!(ev.actual_tokens, 800);
        assert_eq!(ev.saved_tokens, 4200);
        assert_eq!(
            ev.measurement_method,
            Some(event::MeasurementMethod::DirectCount)
        );
        assert_eq!(ev.evidence_class, Some(event::EvidenceClass::Measured));
        assert_eq!(ev.confidence, Some(1.0));

        let unified: crate::core::ocla::unified_ledger::UnifiedSavingsEventV2 =
            serde_json::from_str(unified_content.lines().next().unwrap()).unwrap();
        assert_eq!(unified.tool_name, ev.tool);
        assert_eq!(unified.mode, ev.mechanism);
        assert_eq!(unified.original_tokens, ev.baseline_tokens);
        assert_eq!(unified.compressed_tokens, ev.actual_tokens);
        assert_eq!(unified.saved_tokens, ev.saved_tokens);
        assert_eq!(unified.content_hash, ev.repo_hash);
        assert_eq!(unified.prev_hash, ev.prev_hash);
        assert_eq!(unified.event_hash, ev.entry_hash);
        assert_eq!(unified.agent_id.as_deref(), Some(ev.agent_id.as_str()));
        assert_eq!(unified.attribution_id, ev.repo_hash);
    }

    /// enterprise#19: a gateway route (requested ≠ serving) lands as a
    /// `routing`-mechanism event valued with the shared rate-delta formula,
    /// denominated in the serving model; no-ops are skipped.
    #[test]
    fn record_routing_event_appends_rate_delta() {
        let _lock = crate::core::data_dir::test_env_lock();
        let dir = std::env::temp_dir().join(format!("lctx-ledger-route-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).expect("mkdir");
        crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());

        record_routing_event("claude-opus-4.5", "claude-opus-4.5", 10_000); // no-op
        record_routing_event("claude-opus-4.5", "phi-4", 0); // no tokens
        record_routing_event("claude-opus-4.5", "phi-4", 10_000);

        let ledger = dir.join("savings").join("ledger.jsonl");
        let content = std::fs::read_to_string(&ledger).expect("ledger written");
        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
        let _ = std::fs::remove_dir_all(&dir);

        assert_eq!(
            content.lines().count(),
            1,
            "only the real route is recorded"
        );
        let ev: SavingsEvent =
            serde_json::from_str(content.lines().next().unwrap()).expect("valid JSON");
        assert_eq!(ev.tool, "proxy_route");
        assert_eq!(ev.mechanism, MECHANISM_ROUTING);
        assert_eq!(ev.model_id, "phi-4", "denominated in the serving model");
        assert_eq!(ev.model_original.as_deref(), Some("claude-opus-4.5"));
        assert_eq!(ev.model_routed.as_deref(), Some("phi-4"));
        assert_eq!(ev.routing_savings, Some(0));
        assert_eq!(
            ev.measurement_method,
            Some(event::MeasurementMethod::DirectCount)
        );
        assert_eq!(ev.evidence_class, Some(event::EvidenceClass::Approximated));
        assert_eq!(ev.saved_tokens, 0, "routing saves dollars, not tokens");
        // 10k tokens × (5.00 − 0.125)/MTok = $0.04875.
        assert!((ev.saved_usd - 0.048_75).abs() < 1e-9);
    }

    #[test]
    fn record_tool_event_sets_attribution_group() {
        let _lock = crate::core::data_dir::test_env_lock();
        let dir = std::env::temp_dir().join(format!("lctx-ledger-attr-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).expect("mkdir");
        crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());

        record_tool_event("ctx_read", 1000, 200, None, None);

        let ledger = dir.join("savings").join("ledger.jsonl");
        let content = std::fs::read_to_string(&ledger).expect("ledger written");
        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
        let _ = std::fs::remove_dir_all(&dir);

        let ev: SavingsEvent =
            serde_json::from_str(content.lines().next().unwrap()).expect("valid event JSON");
        assert_eq!(
            ev.attribution_group.as_deref(),
            Some("input_optimization"),
            "compression events must have attribution_group set"
        );
    }
}