lean-ctx-engine 3.12.1

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and proxy integrations.
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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
//! 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 observation;
pub mod project_scope;
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 project_scope::ProjectScope;
pub use roi::{RoiReport, roi_report, roi_report_for};
pub use signed_batch::{BatchVerifyResult, SignedSavingsBatchV1};
pub use store::{LedgerSummary, VerifyResult};

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_id, input_price_per_m) for this process. The active model is stable
/// within a process, so it is resolved once, at the first event: by then `initialize`
/// has named the MCP client (see [`agent_id`]).
fn model_and_price() -> &'static (String, f64) {
    static CACHE: OnceLock<(String, f64)> = OnceLock::new();
    CACHE.get_or_init(|| {
        let agent = agent_id();
        let client = agent.split(':').next().unwrap_or_default();
        let explicit = std::env::var("LEAN_CTX_MODEL")
            .or_else(|_| std::env::var("LCTX_MODEL"))
            .ok();
        let configured = crate::core::config::Config::load()
            .cost
            .model_for_client(client);
        let resolved = resolve_ledger_model(
            explicit,
            configured,
            client.starts_with("codex"),
            codex_configured_model,
            crate::core::proxy_usage::persisted_dominant_model,
        );
        // Disk cache only, no network: the price list the proxy keeps current.
        crate::core::gain::live_pricing::ensure_loaded();
        let quote =
            crate::core::gain::model_pricing::ModelPricing::load().quote(resolved.as_deref());
        (
            recorded_model(resolved.as_deref(), &quote),
            quote.cost.input_per_m,
        )
    })
}

/// The model this process's agent actually runs, first available wins:
/// 1. `LEAN_CTX_MODEL` / `LCTX_MODEL`
/// 2. `[cost.models]` for the client, then `[cost] default_model`
/// 3. Codex: the `model` of its own configuration (Codex bypasses the proxy)
/// 4. the model the LeanCTX proxy measured most (Claude Code and other proxied hosts)
fn resolve_ledger_model(
    explicit: Option<String>,
    configured: Option<String>,
    codex: bool,
    codex_model: impl FnOnce() -> Option<String>,
    proxy_model: impl FnOnce() -> Option<String>,
) -> Option<String> {
    let given = |value: Option<String>| {
        value
            .map(|model| model.trim().to_string())
            .filter(|model| !model.is_empty())
    };
    given(explicit)
        .or_else(|| given(configured))
        .or_else(|| if codex { given(codex_model()) } else { None })
        .or_else(|| given(proxy_model()))
}

/// The `model` Codex runs with: its active profile overlay first, then the base config.
fn codex_configured_model() -> Option<String> {
    let paths = crate::core::home::resolve_codex_config_paths()?;
    let model_in = |path: &std::path::Path| -> Option<String> {
        let doc: toml::Value = toml::from_str(&std::fs::read_to_string(path).ok()?).ok()?;
        doc.get("model")?.as_str().map(str::to_string)
    };
    paths
        .profile()
        .and_then(model_in)
        .or_else(|| model_in(paths.base()))
}

/// The model name an event records. An exact or live price names its model; an
/// estimated price keeps the real model name rather than the stand-in it was priced
/// by (`claude-opus-5-5`, never `claude-opus-4.5`). Without any known model the
/// blended fallback says exactly that.
fn recorded_model(
    resolved: Option<&str>,
    quote: &crate::core::gain::model_pricing::ModelQuote,
) -> String {
    match resolved.map(str::trim).filter(|model| !model.is_empty()) {
        Some(model) if quote.match_kind.is_estimated() => model.to_lowercase(),
        _ => quote.model_key.clone(),
    }
}

/// 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(|| {
        let cwd = std::env::current_dir()
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_default();
        hash_folder(&cwd)
    })
}

/// The ledger's attribution for a folder: the first 16 hex digits of SHA-256
/// over its path text.
pub fn hash_folder(folder: &str) -> String {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(folder.as_bytes());
    let hex = crate::core::agent_identity::hex_encode(&hasher.finalize());
    hex.get(..16).unwrap_or(&hex).to_string()
}

/// Per-agent attribution of each event (client + bus identity, or host);
/// see [`crate::core::agent_identity::ledger_agent_id`].
fn agent_id() -> String {
    crate::core::agent_identity::ledger_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 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(),
        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,
        // Committed into the v7 hash, so per-session totals are chain-backed.
        session_id: crate::core::value::current_session(),
        trace_id: None,
        solution_decision: None,
        loc_added: None,
        loc_removed: None,
        path: None,
        lines_added: None,
        lines_removed: None,
        net: 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,
        governor: None,
    }
}

/// Best-effort append of an edit measurement. Unlike token-savings events, this
/// deliberately records zero-net replacements: both sides of the LOC change are
/// evidence needed by Solution Intelligence.
pub fn record_edit_event(path: &str, lines_added: u64, lines_removed: u64) {
    if path.is_empty() || !enabled() {
        return;
    }
    let Some(ledger_path) = store::default_path() else {
        return;
    };

    let added = i64::try_from(lines_added).unwrap_or(i64::MAX);
    let removed = i64::try_from(lines_removed).unwrap_or(i64::MAX);
    let mut event = new_event("edit");
    event.path = Some(path.to_owned());
    event.lines_added = Some(lines_added);
    event.lines_removed = Some(lines_removed);
    event.net = Some(removed.saturating_sub(added));
    // Keep the established Solution Intelligence fields populated for consumers
    // that predate the explicit edit-event schema.
    event.loc_added = Some(lines_added);
    event.loc_removed = Some(lines_removed);
    append_with_unified(&ledger_path, event, 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);
    Some(compression_band(ratio).to_owned())
}

/// Band of the fraction of tokens removed, stored as `SavingsEvent::quality_signal`.
/// The single definition for every writer of that field; a compression measure, not
/// a quality one.
pub(crate) fn compression_band(removed_fraction: f64) -> &'static str {
    match removed_fraction {
        r if r >= 0.7 => "excellent",
        r if r >= 0.5 => "good",
        r if r >= 0.3 => "moderate",
        _ => "marginal",
    }
}

/// 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);
}

/// Best-effort append of one governor decision receipt (`hook govern`,
/// governor design v1 §5). `delivered_tokens` is what the model actually got:
/// the smaller result for an `applied` decision, the unchanged baseline for a
/// `shadow` one (so a shadow receipt saves nothing in the totals and carries
/// its would-save only in the receipt). Counts are o200k, as the hook measures.
pub fn record_governor_event(
    baseline_tokens: usize,
    delivered_tokens: usize,
    receipt: event::GovernorReceipt,
) {
    if !enabled() {
        return;
    }
    let Some(path) = store::default_path() else {
        return;
    };
    let saved = baseline_tokens.saturating_sub(delivered_tokens);
    let mut event = new_event("hook:govern");
    "o200k_base".clone_into(&mut event.tokenizer);
    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 = delivered_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.governor = Some(receipt);
    append_with_unified(&path, event, None);
}

/// 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 *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.
/// `project_key` is the project of the request (the folder its agent named);
/// without one the event carries the recording process's folder.
pub fn record_caching_event(
    model: &str,
    cache_read_tokens: u64,
    discount_usd: f64,
    project_key: Option<&str>,
) {
    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 = recorded_model(Some(model), &quote);
    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;
    if let Some(key) = project_key {
        key.clone_into(&mut event.repo_hash);
    }
    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()
}

/// [`summary`] over one project's events, or over the whole ledger for `None`.
pub fn summary_for(scope: Option<&ProjectScope>) -> LedgerSummary {
    match scope {
        None => summary(),
        Some(scope) => store::default_path()
            .map(|p| store::summarize_scoped(&p, scope))
            .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");
    }

    fn some(model: &str) -> Option<String> {
        Some(model.to_string())
    }

    #[test]
    fn ledger_model_prefers_explicit_then_configured_then_host_then_proxy() {
        let proxy = || some("claude-opus-5-5");
        let codex = || some("gpt-6.1-sol");
        assert_eq!(
            resolve_ledger_model(some("gpt-5"), some("x"), true, codex, proxy),
            some("gpt-5")
        );
        assert_eq!(
            resolve_ledger_model(some("  "), some("internal-llm"), true, codex, proxy),
            some("internal-llm"),
            "a blank override falls through to the declared model"
        );
        assert_eq!(
            resolve_ledger_model(None, None, true, codex, proxy),
            some("gpt-6.1-sol"),
            "Codex bypasses the proxy: its own configured model, not Claude's"
        );
        assert_eq!(
            resolve_ledger_model(None, None, false, codex, proxy),
            some("claude-opus-5-5"),
            "other hosts: the model the proxy measured"
        );
        assert_eq!(
            resolve_ledger_model(None, None, true, || None, proxy),
            some("claude-opus-5-5")
        );
        assert_eq!(
            resolve_ledger_model(None, None, false, codex, || None),
            None
        );
    }

    #[test]
    fn recorded_model_never_names_the_pricing_stand_in() {
        let pricing = crate::core::gain::model_pricing::ModelPricing::embedded();
        // Not in the embedded table: priced by the Opus family estimate, but the
        // event names the model the agent actually ran.
        let estimated = pricing.quote(Some("claude-opus-5-5"));
        assert!(estimated.match_kind.is_estimated());
        assert_eq!(
            recorded_model(Some("Claude-Opus-5-5"), &estimated),
            "claude-opus-5-5"
        );
        let exact = pricing.quote(Some("claude-sonnet-4-5"));
        assert!(!exact.match_kind.is_estimated());
        assert_eq!(
            recorded_model(Some("claude-sonnet-4-5"), &exact),
            exact.model_key
        );
        let unknown = pricing.quote(None);
        assert_eq!(recorded_model(None, &unknown), "fallback-blended");
    }

    #[test]
    fn codex_model_comes_from_its_profile_then_its_base_config() {
        let _lock = crate::core::data_dir::test_env_lock();
        let home = tempfile::tempdir().unwrap();
        std::fs::write(
            home.path().join("config.toml"),
            "model = \"gpt-6.1-sol\"\nmodel_reasoning_effort = \"high\"\n",
        )
        .unwrap();
        crate::test_env::set_var("CODEX_HOME", home.path());
        crate::test_env::remove_var(crate::core::home::LEAN_CTX_CODEX_PROFILE_ENV);
        crate::test_env::remove_var(crate::core::home::CODEX_PROFILE_ENV);
        assert_eq!(codex_configured_model(), some("gpt-6.1-sol"));
        std::fs::write(
            home.path().join("fast.config.toml"),
            "model = \"gpt-6-luna\"\n",
        )
        .unwrap();
        assert_eq!(
            codex_configured_model(),
            some("gpt-6-luna"),
            "the sole profile overlay wins"
        );
        crate::test_env::remove_var("CODEX_HOME");
    }

    #[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);
    }

    #[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"
        );
    }
}