lean-ctx 3.9.19

Context Runtime for AI Agents with CCP. 79 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%.
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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
//! `lean-ctx gain` — the savings dashboard and Wrapped share cards,
//! plus the `--opportunity` and `--raw` sub-views it absorbs.

use crate::{core, tools};

pub(in crate::cli::dispatch) fn cmd_gain(rest: &[String]) {
    // Keep the latest-version cache fresh (#563): non-blocking, 24h-TTL
    // guarded, opt-out respected. Without a CLI-side trigger the cache only
    // refreshes on MCP maintenance ticks and can freeze on old versions.
    core::version_check::check_background();
    if rest.iter().any(|a| a == "--reset") {
        core::stats::reset_all();
        println!("Stats reset. All token savings data cleared.");
        return;
    }
    if rest.iter().any(|a| a == "--live") {
        core::stats::gain_live();
        return;
    }
    let model = rest.iter().enumerate().find_map(|(i, a)| {
        if let Some(v) = a.strip_prefix("--model=") {
            return Some(v.to_string());
        }
        if a == "--model" {
            return rest.get(i + 1).cloned();
        }
        None
    });
    let period = rest
        .iter()
        .enumerate()
        .find_map(|(i, a)| {
            if let Some(v) = a.strip_prefix("--period=") {
                return Some(v.to_string());
            }
            if a == "--period" {
                return rest.get(i + 1).cloned();
            }
            None
        })
        .unwrap_or_else(|| "all".to_string());
    let limit = rest
        .iter()
        .enumerate()
        .find_map(|(i, a)| {
            if let Some(v) = a.strip_prefix("--limit=") {
                return v.parse::<usize>().ok();
            }
            if a == "--limit" {
                return rest.get(i + 1).and_then(|v| v.parse::<usize>().ok());
            }
            None
        })
        .unwrap_or(10);

    let copy = rest.iter().any(|a| a == "--copy");
    let open = rest.iter().any(|a| a == "--open");

    if rest.iter().any(|a| a == "--no-cache-adjust") {
        core::context_overhead::set_no_cache_adjust(true);
    }

    if let Some(req) = unpublish_request(rest) {
        let id = match &req {
            UnpublishReq::Id(s) => Some(s.as_str()),
            UnpublishReq::Latest => None,
        };
        crate::cli::wrapped_publish::unpublish(id);
        return;
    }
    if rest.iter().any(|a| a == "--publish") {
        let leaderboard = rest.iter().any(|a| a == "--leaderboard");
        crate::cli::wrapped_publish::publish(&period, name_arg(rest).as_deref(), leaderboard);
        return;
    }
    if let Some(req) = link_request(rest) {
        let code = match &req {
            LinkReq::Complete(c) => Some(c.as_str()),
            LinkReq::Start => None,
        };
        crate::cli::wrapped_publish::link(code);
        return;
    }

    if let Some(svg_path) = svg_target(rest) {
        let report = core::wrapped::WrappedReport::generate(&period);
        match std::fs::write(&svg_path, report.to_svg()) {
            Ok(()) => println!(
                "Wrapped card written to {svg_path}\n\
                 Share it directly, open it in a browser, or convert to PNG with any SVG tool."
            ),
            Err(e) => {
                eprintln!("Failed to write {svg_path}: {e}");
                std::process::exit(1);
            }
        }
        share_side_effects(&report, Some(&svg_path), copy, open);
        return;
    }

    if let Some(html_path) = share_target(rest) {
        let report = core::wrapped::WrappedReport::generate(&period);
        let base = base_url_arg(rest);
        match std::fs::write(&html_path, report.to_share_html(base.as_deref())) {
            Ok(()) => {
                println!("Share page written to {html_path}");
                if base.is_some() {
                    println!(
                        "Host it at your base URL; for social preview cards, place a PNG \
                         (rasterise the SVG) at <base>/lean-ctx-wrapped.png."
                    );
                } else {
                    println!(
                        "Self-contained (SVG embedded) — host it anywhere to get a permalink. \
                         Pass --base-url=https://… to emit social preview meta."
                    );
                }
            }
            Err(e) => {
                eprintln!("Failed to write {html_path}: {e}");
                std::process::exit(1);
            }
        }
        share_side_effects(&report, Some(&html_path), copy, open);
        return;
    }

    if copy {
        let report = core::wrapped::WrappedReport::generate(&period);
        share_side_effects(&report, None, true, false);
        return;
    }

    if rest.iter().any(|a| a == "--by-tool") {
        cmd_by_tool(rest, limit);
    } else if rest.iter().any(|a| a == "--graph") {
        println!("{}", core::stats::format_gain_graph());
    } else if rest.iter().any(|a| a == "--daily") {
        println!("{}", core::stats::format_gain_daily());
    } else if rest.iter().any(|a| a == "--json") {
        println!(
            "{}",
            tools::ctx_gain::handle("json", Some(&period), model.as_deref(), Some(limit))
        );
    } else if rest.iter().any(|a| a == "--score") {
        println!(
            "{}",
            tools::ctx_gain::handle("score", None, model.as_deref(), Some(limit))
        );
    } else if rest.iter().any(|a| a == "--cost") {
        println!(
            "{}",
            tools::ctx_gain::handle("cost", None, model.as_deref(), Some(limit))
        );
        print_measured_spend_hint();
    } else if rest.iter().any(|a| a == "--tasks") {
        println!(
            "{}",
            tools::ctx_gain::handle("tasks", None, None, Some(limit))
        );
    } else if rest.iter().any(|a| a == "--agents") {
        println!(
            "{}",
            tools::ctx_gain::handle("agents", None, None, Some(limit))
        );
    } else if rest.iter().any(|a| a == "--heatmap") {
        println!(
            "{}",
            tools::ctx_gain::handle("heatmap", None, None, Some(limit))
        );
    } else if rest.iter().any(|a| a == "--wrapped") {
        println!(
            "{}",
            tools::ctx_gain::handle("wrapped", Some(&period), model.as_deref(), Some(limit))
        );
        // Interactive publish prompt (if TTY and not already published)
        if !rest.iter().any(|a| a == "--publish")
            && std::io::IsTerminal::is_terminal(&std::io::stdin())
            && !crate::cli::wrapped_publish::has_published()
        {
            eprint!("\n  Publish this card? [y/N/leaderboard] ");
            let mut input = String::new();
            if std::io::stdin().read_line(&mut input).is_ok() {
                let answer = input.trim().to_lowercase();
                match answer.as_str() {
                    "y" | "yes" => {
                        let cfg = crate::core::config::Config::load();
                        crate::cli::wrapped_publish::publish(
                            &period,
                            cfg.gain.display_name.as_deref(),
                            cfg.gain.leaderboard,
                        );
                    }
                    "l" | "leaderboard" => {
                        let cfg = crate::core::config::Config::load();
                        crate::cli::wrapped_publish::publish(
                            &period,
                            cfg.gain.display_name.as_deref(),
                            true,
                        );
                    }
                    _ => {}
                }
            }
        } else {
            crate::cli::wrapped_publish::maybe_auto_publish(&period);
        }
    } else if rest.iter().any(|a| a == "--pipeline") {
        let stats_path = crate::core::paths::state_dir()
            .unwrap_or_else(|_| dirs::home_dir().unwrap_or_default().join(".lean-ctx"))
            .join("pipeline_stats.json");
        if let Ok(data) = std::fs::read_to_string(&stats_path) {
            if let Ok(stats) = serde_json::from_str::<core::pipeline::PipelineStats>(&data) {
                println!("{}", stats.format_summary());
            } else {
                println!("No pipeline stats available yet (corrupt data).");
            }
        } else {
            println!("No pipeline stats available yet. Use MCP tools to generate data.");
        }
    } else if rest.iter().any(|a| a == "--deep") {
        // Body first, then the extra themed sections, then the footer — so the
        // tips / Context OS panel land at the very end instead of mid-dashboard.
        println!("{}", core::stats::format_gain_body());
        print!(
            "{}",
            tools::ctx_gain::format_deep_themed(model.as_deref(), limit)
        );
        println!("{}", core::stats::format_gain_footer());
    } else if rest.iter().any(|a| a == "--opportunity") {
        cmd_opportunity();
    } else if rest.iter().any(|a| a == "--raw") {
        cmd_stats_raw(rest);
    } else {
        println!("{}", core::stats::format_gain_hero());
        print_solution_intelligence();
        // Surface available updates where users actually look (#563) — the
        // banner functions existed but had no caller, so terminals never
        // showed update hints at all.
        if let Some(banner) = core::version_check::get_update_banner() {
            println!("\n{banner}");
        }
        print_support_hint();
        print_cloud_sync_hint();
        print_bridge_warning();
        print_split_hint();
        crate::cli::wrapped_publish::maybe_auto_publish(&period);
        print_community_hint();
    }
}

/// Nudge free/unauthenticated users toward Personal Cloud sync when they
/// have meaningful local context worth backing up.
fn print_solution_intelligence() {
    if !core::config::Config::load().solution.enabled {
        return;
    }

    println!(
        "\nSolution Intelligence: {}",
        core::solution_tracker::gain_summary()
    );

    let solution = core::solution_tracker::snapshot();
    let output_saved = solution
        .output_tokens_baseline
        .saturating_sub(solution.output_tokens_actual);
    let loc_delta = match solution.loc_net_saved {
        0 => "0".to_string(),
        saved if saved > 0 => format!("-{}", format_thousands(saved.unsigned_abs())),
        added => format!("+{}", format_thousands(added.unsigned_abs())),
    };
    let mut decisions: Vec<_> = solution.decisions_by_kind.iter().collect();
    decisions.sort_unstable_by_key(|(k, _)| (*k).clone());
    let breakdown = if decisions.is_empty() {
        "none".to_string()
    } else {
        decisions
            .into_iter()
            .map(|(kind, count)| format!("{kind}: {}", format_thousands(*count)))
            .collect::<Vec<_>>()
            .join(", ")
    };

    let token_savings = core::savings_ledger::summary().net_saved_tokens();
    let token_baseline = core::stats::load_for_display().total_input_tokens;
    let combined_saved = token_savings.saturating_add(output_saved);
    let combined_baseline = token_baseline.saturating_add(solution.output_tokens_baseline);
    let combined_reduction = if combined_baseline == 0 {
        0.0
    } else {
        combined_saved as f64 * 100.0 / combined_baseline as f64
    };

    println!(
        "\nSolution Efficiency: {} output tokens saved ({}% reduction)",
        format_thousands(output_saved),
        solution.output_reduction_pct,
    );
    println!(
        "  LOC: {loc_delta} net lines | Decisions: {} ({breakdown})",
        format_thousands(solution.decisions_total),
    );
    println!(
        "Combined: {} total tokens saved ({combined_reduction:.1}% total reduction)",
        format_thousands(combined_saved),
    );
}

fn format_thousands(value: u64) -> String {
    let digits = value.to_string();
    let mut formatted = String::with_capacity(digits.len() + digits.len() / 3);

    for (index, digit) in digits.chars().enumerate() {
        if index > 0 && (digits.len() - index).is_multiple_of(3) {
            formatted.push(',');
        }
        formatted.push(digit);
    }

    formatted
}

fn print_cloud_sync_hint() {
    if crate::cloud_client::is_logged_in() {
        let plan = crate::cloud_client::resolve_effective_plan_cached();
        if plan.plan == crate::core::billing::Plan::Free {
            let facts = count_local_knowledge_facts();
            if facts > 0 {
                eprintln!(
                    "\n  \x1b[2m\u{1f517} {facts} knowledge facts \u{2014} local only.\n     Back them up + sync across devices: lean-ctx cloud upgrade --plan pro\x1b[0m"
                );
            }
        }
    } else {
        let facts = count_local_knowledge_facts();
        let store = core::stats::load();
        if store.total_input_tokens > 100_000 || facts > 10 {
            eprintln!(
                "\n  \x1b[2m\u{1f517} Your context runs on this machine only.\n     Sync it everywhere: lean-ctx cloud upgrade --plan pro ($9/mo)\x1b[0m"
            );
        }
    }
}

fn count_local_knowledge_facts() -> usize {
    let Ok(data_dir) = crate::core::paths::data_dir() else {
        return 0;
    };
    let knowledge_dir = data_dir.join("knowledge");
    if !knowledge_dir.is_dir() {
        return 0;
    }
    std::fs::read_dir(&knowledge_dir)
        .into_iter()
        .flatten()
        .filter_map(Result::ok)
        .filter(|e| e.path().is_dir())
        .flat_map(|project| {
            std::fs::read_dir(project.path())
                .into_iter()
                .flatten()
                .filter_map(Result::ok)
                .filter(|f| f.path().extension().is_some_and(|ext| ext == "json"))
        })
        .count()
}

/// `gain --cost` values savings with a *resolved* model (estimated). When the
/// proxy has recorded real provider usage, point at the measured `spend` view so
/// the user knows the exact bill is one command away.
fn print_measured_spend_hint() {
    if !crate::proxy::usage_meter::persisted_snapshot().is_empty() {
        eprintln!(
            "\n  \x1b[2m💡 Measured provider spend available — run `lean-ctx spend` for the real per-model bill.\x1b[0m"
        );
    }
}

/// When the bridge is not engaged, the proxy is no longer feeding live request
/// stats. Surface that caveat so `gain` never implies savings it cannot measure
/// (GitHub #361/#271) — **but only when there are genuinely no savings to show**.
///
/// `gain` also measures MCP-tool savings directly (reads/search/shell via the
/// savings ledger + stats), which need no proxy at all. Emitting a "proxy down —
/// savings cannot be measured" line above a real, MCP-measured headline wrongly
/// told MCP-only users their numbers were untrustworthy (#500). Gate on the
/// displayed total so the warning fires only for a true zero.
fn print_bridge_warning() {
    use crate::core::gain::bridge_status::{BridgeEngagement, BridgeStatus};
    let store = core::stats::load_for_display();
    let saved = store
        .total_input_tokens
        .saturating_sub(store.total_output_tokens);
    if saved > 0 {
        return;
    }
    let bridge = BridgeStatus::detect();
    if bridge.engagement != BridgeEngagement::Engaged {
        eprintln!("\n  \x1b[33m⚠ {}\x1b[0m", bridge.summary_line());
    }
}

/// When stats live in more than one auto-resolved data dir, `gain` now sums them
/// for display (#500) — but each process still *writes* to its own dir, so the
/// split persists. Nudge toward consolidation once, non-alarmingly, since the
/// headline is already correct. Suppressed when `LEAN_CTX_DATA_DIR` pins one dir.
fn print_split_hint() {
    if std::env::var_os("LEAN_CTX_DATA_DIR").is_some() {
        return;
    }
    let dirs = core::data_dir::all_data_dirs_with_stats();
    if dirs.len() >= 2 {
        eprintln!(
            "\n  \x1b[2m💡 Stats span {} data dirs (summed above). Consolidate them with `lean-ctx doctor`.\x1b[0m",
            dirs.len()
        );
    }
}

fn print_community_hint() {
    let s = core::savings_ledger::summary();
    if s.total_events == 0 {
        return;
    }

    let on_board = crate::cli::wrapped_publish::has_leaderboard_entry();
    let published = crate::cli::wrapped_publish::has_published();
    let has_name = crate::core::config::Config::load()
        .gain
        .display_name
        .is_some();

    // State-aware nudge so the path to https://leanctx.com/metrics — and how to set a
    // display name or unpublish — is always one copy-pasteable line away. Every state
    // names both the public command and the way back out (community ask: a clear
    // "how to publish/unpublish" line in the normal `gain` output).
    let body = if on_board && has_name {
        "💡 On the public leaderboard (https://leanctx.com/metrics).\n     \
         Refresh:  lean-ctx gain --publish --leaderboard\n     \
         Multiple machines?  lean-ctx gain --link  (combine into one entry)\n     \
         Remove:  lean-ctx gain --unpublish"
            .to_string()
    } else if on_board {
        "💡 You're on the leaderboard as \"anonymous\". Claim your handle:\n     \
         lean-ctx gain --publish --leaderboard --name=\"your handle\"\n     \
         Multiple machines?  lean-ctx gain --link  (combine into one entry)"
            .to_string()
    } else if published {
        "💡 You're published privately. List on the public leaderboard at https://leanctx.com/metrics:\n     \
         lean-ctx gain --publish --leaderboard --name=\"your handle\"   ·   Remove:  lean-ctx gain --unpublish"
            .to_string()
    } else {
        "💡 Join the public leaderboard at https://leanctx.com/metrics (opt-in — shares only 4 aggregate totals, never your code):\n     \
         Publish:  lean-ctx gain --publish --leaderboard --name=\"your handle\"   ·   Remove:  lean-ctx gain --unpublish"
            .to_string()
    };
    eprintln!("\n  \x1b[2m{body}\x1b[0m");
}

/// A prominent, friendly nudge to support lean-ctx financially. The engine is
/// free and never gated — this is the single place the default `gain` view asks
/// for support, rendered right under the savings hero so the people who benefit
/// most see the most natural moment to give back.
fn print_support_hint() {
    use crate::core::theme;
    let t = theme::load_theme(&crate::core::config::Config::load().theme);
    let rst = theme::rst();
    let bold = theme::bold();
    let dim = theme::dim();
    let acc = t.accent.fg();
    let heart = t.danger.fg();
    let w = 57;
    let side = t.box_side();
    let row = |content: &str| -> String {
        let padded = theme::pad_right(content, w);
        format!("  {side}{padded}{side}")
    };

    println!();
    println!("  {}", t.box_top(w));
    println!(
        "{}",
        row(&format!(
            "  {heart}\u{2665}{rst}  {bold}Enjoying lean-ctx? Keep it free & independent.{rst}"
        ))
    );
    println!("{}", row(""));
    println!(
        "{}",
        row(&format!(
            "  {dim}Back development for the price of a coffee \u{2192}{rst}"
        ))
    );
    println!(
        "{}",
        row(&format!("  {acc}{bold}https://leanctx.com/support{rst}"))
    );
    println!("  {}", t.box_bottom(w));
}

/// Resolves the output path for the shareable SVG Wrapped card, or `None` when no
/// card was requested. Accepts `--svg`, `--svg=<path>`, `--card`, `--card=<path>`;
/// a bare flag falls back to `lean-ctx-wrapped.svg` in the current directory.
/// A requested `--unpublish`: either an explicit card id, or the most recent published card.
enum UnpublishReq {
    Latest,
    Id(String),
}

/// Parses `--unpublish[=<id>]`. `None` means it was not requested at all.
fn unpublish_request(rest: &[String]) -> Option<UnpublishReq> {
    for a in rest {
        if let Some(v) = a.strip_prefix("--unpublish=") {
            return Some(UnpublishReq::Id(v.to_string()));
        }
        if a == "--unpublish" {
            return Some(UnpublishReq::Latest);
        }
    }
    None
}

/// A requested `--link`: start a pairing (mint a code) or complete one with a code.
enum LinkReq {
    Start,
    Complete(String),
}

/// Parses `--link[=CODE]` / `--link CODE` (GH #736). `None` = not requested.
fn link_request(rest: &[String]) -> Option<LinkReq> {
    for (i, a) in rest.iter().enumerate() {
        if let Some(v) = a.strip_prefix("--link=") {
            return Some(LinkReq::Complete(v.to_string()));
        }
        if a == "--link" {
            return Some(match rest.get(i + 1) {
                Some(next) if !next.starts_with('-') => LinkReq::Complete(next.clone()),
                _ => LinkReq::Start,
            });
        }
    }
    None
}

/// Parses `--name=<display>` / `--name <display>` for the optional publish display label.
fn name_arg(rest: &[String]) -> Option<String> {
    rest.iter().enumerate().find_map(|(i, a)| {
        if let Some(v) = a.strip_prefix("--name=") {
            return Some(v.to_string());
        }
        if a == "--name" {
            return rest.get(i + 1).cloned();
        }
        None
    })
}

fn svg_target(rest: &[String]) -> Option<String> {
    let mut requested = false;
    let mut path: Option<String> = None;
    for (i, a) in rest.iter().enumerate() {
        if let Some(v) = a
            .strip_prefix("--svg=")
            .or_else(|| a.strip_prefix("--card="))
        {
            requested = true;
            path = Some(v.to_string());
        } else if a == "--svg" || a == "--card" {
            requested = true;
            if let Some(next) = rest.get(i + 1)
                && !next.starts_with('-')
            {
                path = Some(next.clone());
            }
        }
    }
    requested.then(|| path.unwrap_or_else(|| "lean-ctx-wrapped.svg".to_string()))
}

/// Resolves the output path for the self-hostable HTML share page, or `None` when not
/// requested. Accepts `--share`, `--share=<path>`, `--page`, `--page=<path>`; a bare flag
/// falls back to `lean-ctx-wrapped.html`.
fn share_target(rest: &[String]) -> Option<String> {
    let mut requested = false;
    let mut path: Option<String> = None;
    for (i, a) in rest.iter().enumerate() {
        if let Some(v) = a
            .strip_prefix("--share=")
            .or_else(|| a.strip_prefix("--page="))
        {
            requested = true;
            path = Some(v.to_string());
        } else if a == "--share" || a == "--page" {
            requested = true;
            if let Some(next) = rest.get(i + 1)
                && !next.starts_with('-')
            {
                path = Some(next.clone());
            }
        }
    }
    requested.then(|| path.unwrap_or_else(|| "lean-ctx-wrapped.html".to_string()))
}

/// Reads `--base-url=<url>` / `--base-url <url>` (the location the share page will be
/// hosted at, used for absolute social-preview image meta).
fn base_url_arg(rest: &[String]) -> Option<String> {
    rest.iter().enumerate().find_map(|(i, a)| {
        if let Some(v) = a.strip_prefix("--base-url=") {
            return Some(v.to_string());
        }
        if a == "--base-url" {
            return rest.get(i + 1).cloned();
        }
        None
    })
}

/// Applies the optional `--copy` (clipboard) and `--open` (browser) side effects for a
/// Wrapped artifact. `path` is the just-written file to open, when one exists. Both
/// degrade gracefully: a clipboard miss falls back to printing the share line.
fn share_side_effects(
    report: &core::wrapped::WrappedReport,
    path: Option<&str>,
    copy: bool,
    open: bool,
) {
    if copy {
        let text = report.share_text(None);
        if core::share::copy_to_clipboard(&text) {
            println!("Copied to clipboard:  {text}");
        } else {
            println!("Share text (copy it): {text}");
        }
    }
    if open && let Some(p) = path {
        if core::share::open_in_browser(p) {
            println!("Opened {p}");
        } else {
            println!("Could not open {p} automatically — open it manually.");
        }
    }
}

/// `gain --opportunity` — merged discover + ghost (opportunity report).
fn cmd_opportunity() {
    use crate::core::theme;

    let t = {
        let cfg = crate::core::config::Config::load();
        theme::load_theme(&cfg.theme)
    };
    let rst = theme::rst();
    let bold = theme::bold();
    let dim = theme::dim();
    let w = 57;

    let history = crate::cli::common::load_shell_history();
    let result = crate::tools::ctx_discover::analyze_history(&history, 10);

    let store = core::stats::load_for_display();
    let optimized_cmds = store.total_commands;

    if result.missed_commands.is_empty() {
        println!(
            "\n  {sc}{bold}All compressible commands are already using lean-ctx!{rst}\n  {dim}{optimized_cmds} commands optimized.{rst}\n",
            sc = t.success.fg(),
        );
        return;
    }

    let total_missed: u64 = result
        .missed_commands
        .iter()
        .map(|c| c.estimated_tokens as u64)
        .sum();
    let total_count: u64 = result.missed_commands.iter().map(|c| c.count as u64).sum();

    println!();
    println!("  {}", t.box_top(w));
    let side = t.box_side();
    let padded = |s: &str| -> String {
        let p = theme::pad_right(s, w);
        format!("  {side}{p}{side}")
    };
    println!(
        "{}",
        padded(&format!("  {bold}{}Opportunity Report{rst}", t.accent.fg()))
    );
    println!("{}", padded(""));
    println!(
        "{}",
        padded(&format!(
            "  {bold}~{}{rst} {dim}tokens/month going uncompressed{rst}",
            crate::core::wrapped::format_tokens(total_missed),
        ))
    );
    println!("{}", padded(""));

    for entry in result.missed_commands.iter().take(8) {
        let line = format!(
            "  {dim}{:<12}{rst} {:>4}x   {bold}~{}{rst} {dim}tokens recoverable{rst}",
            entry.prefix,
            entry.count,
            crate::core::wrapped::format_tokens(entry.estimated_tokens as u64),
        );
        println!("{}", padded(&line));
    }

    println!("{}", padded(""));
    let opt_line = format!(
        "  {dim}Already optimized: {optimized_cmds} commands ({pct}%){rst}",
        pct = total_count
            .checked_add(optimized_cmds)
            .and_then(|total| optimized_cmds.checked_mul(100)?.checked_div(total))
            .unwrap_or(100)
    );
    println!("{}", padded(&opt_line));
    println!("  {}", t.box_bottom(w));
    println!();
    let sec = t.secondary.fg();
    println!("  {sec}lean-ctx init --global{rst}   {dim}Compress everything{rst}");
    println!();
}

/// `gain --by-tool` — per-tool savings breakdown from the verified savings
/// ledger (calls, tokens saved, USD, compression %). The aggregate `gain`
/// headline hides which tool earned the savings; this surfaces it. Honors
/// `--limit` and `--json`.
fn cmd_by_tool(rest: &[String], limit: usize) {
    use std::collections::HashMap;

    #[derive(Default)]
    struct Agg {
        calls: u64,
        saved_tokens: u64,
        saved_usd: f64,
        baseline_tokens: u64,
    }

    let mut by_tool: HashMap<String, Agg> = HashMap::new();
    for e in core::savings_ledger::all_events() {
        let a = by_tool.entry(e.tool).or_default();
        a.calls += 1;
        a.saved_tokens += e.saved_tokens;
        a.saved_usd += e.saved_usd;
        a.baseline_tokens += e.baseline_tokens;
    }

    let mut rows: Vec<(String, Agg)> = by_tool.into_iter().collect();
    // Heaviest saver first; tie-break by name so the view is deterministic.
    rows.sort_by(|a, b| {
        b.1.saved_tokens
            .cmp(&a.1.saved_tokens)
            .then_with(|| a.0.cmp(&b.0))
    });
    rows.truncate(limit);

    let pct = |a: &Agg| -> f64 {
        if a.baseline_tokens > 0 {
            a.saved_tokens as f64 / a.baseline_tokens as f64 * 100.0
        } else {
            0.0
        }
    };

    if rest.iter().any(|a| a == "--json") {
        let arr: Vec<_> = rows
            .iter()
            .map(|(tool, a)| {
                serde_json::json!({
                    "tool": tool,
                    "calls": a.calls,
                    "saved_tokens": a.saved_tokens,
                    "saved_usd": a.saved_usd,
                    "baseline_tokens": a.baseline_tokens,
                    "saved_pct": pct(a),
                })
            })
            .collect();
        println!(
            "{}",
            serde_json::to_string_pretty(&arr).unwrap_or_else(|_| "[]".to_string())
        );
        return;
    }

    if rows.is_empty() {
        println!(
            "No per-tool savings recorded yet. Use lean-ctx-backed tools (ctx_read, \
             ctx_search, ctx_shell) to populate the ledger."
        );
        return;
    }

    println!("Savings by tool (most saved first):\n");
    println!(
        "  {:<16} {:>8} {:>12} {:>10} {:>7}",
        "TOOL", "CALLS", "SAVED", "USD", "SAVED%"
    );
    for (tool, a) in &rows {
        println!(
            "  {:<16} {:>8} {:>12} {:>10} {:>6.1}%",
            tool,
            a.calls,
            core::wrapped::format_tokens(a.saved_tokens),
            format!("${:.2}", a.saved_usd),
            pct(a),
        );
    }
}

/// `gain --raw` — plain stats (absorbs former `lean-ctx stats` command).
fn cmd_stats_raw(rest: &[String]) {
    if rest.iter().any(|a| a == "--json" || a == "json") {
        let store = core::stats::load();
        println!(
            "{}",
            serde_json::to_string_pretty(&store).unwrap_or_else(|_| "{}".to_string())
        );
    } else {
        let store = core::stats::load();
        let input_saved = store
            .total_input_tokens
            .saturating_sub(store.total_output_tokens);
        let pct = if store.total_input_tokens > 0 {
            input_saved as f64 / store.total_input_tokens as f64 * 100.0
        } else {
            0.0
        };
        println!("Commands:    {}", store.total_commands);
        println!("Input:       {} tokens", store.total_input_tokens);
        println!("Output:      {} tokens", store.total_output_tokens);
        println!("Saved:       {input_saved} tokens ({pct:.1}%)");
        println!();

        // Solution Intelligence metrics
        let sol = crate::core::solution_tracker::snapshot();
        if sol.decisions_total > 0 || sol.loc_added > 0 || sol.loc_removed > 0 {
            let sol_pct = sol.output_reduction_pct;
            println!("Solution Efficiency:");
            if sol.output_tokens_baseline > 0 {
                let sol_saved = sol
                    .output_tokens_baseline
                    .saturating_sub(sol.output_tokens_actual);
                println!("  Output:    {sol_saved} tokens saved ({sol_pct}% reduction)");
            }
            println!(
                "  LOC:       {} net lines saved | {} decisions ({} stdlib, {} reuse, {} native, {} yagni)",
                sol.loc_net_saved,
                sol.decisions_total,
                sol.decisions_by_kind.get("stdlib").unwrap_or(&0),
                sol.decisions_by_kind.get("reuse").unwrap_or(&0),
                sol.decisions_by_kind.get("native").unwrap_or(&0),
                sol.decisions_by_kind.get("yagni").unwrap_or(&0),
            );
            if input_saved > 0 || sol.output_tokens_baseline > 0 {
                let combined = input_saved
                    + sol
                        .output_tokens_baseline
                        .saturating_sub(sol.output_tokens_actual);
                println!("  Combined:  {combined} total tokens saved");
            }
            println!();
        }

        println!("CEP sessions:  {}", store.cep.sessions);
        println!(
            "CEP tokens:    {}{}",
            store.cep.total_tokens_original, store.cep.total_tokens_compressed
        );
    }
}

#[cfg(test)]
mod tests {
    use super::{base_url_arg, share_target, svg_target};

    fn args(xs: &[&str]) -> Vec<String> {
        xs.iter().map(|s| (*s).to_string()).collect()
    }

    #[test]
    fn no_flag_means_no_card() {
        assert_eq!(svg_target(&args(&["--wrapped", "--period=month"])), None);
    }

    #[test]
    fn bare_flag_uses_default_path() {
        assert_eq!(
            svg_target(&args(&["--svg"])).as_deref(),
            Some("lean-ctx-wrapped.svg")
        );
        assert_eq!(
            svg_target(&args(&["--card"])).as_deref(),
            Some("lean-ctx-wrapped.svg")
        );
    }

    #[test]
    fn explicit_path_is_used() {
        assert_eq!(
            svg_target(&args(&["--svg=out.svg"])).as_deref(),
            Some("out.svg")
        );
        assert_eq!(
            svg_target(&args(&["--card=c.svg"])).as_deref(),
            Some("c.svg")
        );
        assert_eq!(
            svg_target(&args(&["--svg", "chosen.svg"])).as_deref(),
            Some("chosen.svg")
        );
    }

    #[test]
    fn following_flag_is_not_consumed_as_path() {
        assert_eq!(
            svg_target(&args(&["--svg", "--period=week"])).as_deref(),
            Some("lean-ctx-wrapped.svg")
        );
    }

    #[test]
    fn share_target_resolves_paths() {
        assert_eq!(share_target(&args(&["--wrapped"])), None);
        assert_eq!(
            share_target(&args(&["--share"])).as_deref(),
            Some("lean-ctx-wrapped.html")
        );
        assert_eq!(
            share_target(&args(&["--page=out.html"])).as_deref(),
            Some("out.html")
        );
        assert_eq!(
            share_target(&args(&["--share", "--base-url=https://x"])).as_deref(),
            Some("lean-ctx-wrapped.html"),
            "a following flag must not be eaten as the path"
        );
    }

    #[test]
    fn base_url_is_parsed_both_forms() {
        assert_eq!(
            base_url_arg(&args(&["--base-url=https://me.dev"])).as_deref(),
            Some("https://me.dev")
        );
        assert_eq!(
            base_url_arg(&args(&["--base-url", "https://me.dev"])).as_deref(),
            Some("https://me.dev")
        );
        assert_eq!(base_url_arg(&args(&["--share"])), None);
    }
}