Skip to main content

lean_ctx/cli/
cloud.rs

1use crate::{cloud_client, core};
2
3fn hosted_research_enabled() -> bool {
4    std::env::var("LEAN_CTX_EXPERIMENTAL_HOSTED").as_deref() == Ok("1")
5}
6
7fn require_hosted_research() -> bool {
8    if hosted_research_enabled() {
9        return true;
10    }
11
12    eprintln!(
13        "Hosted account operations are Research and unavailable in the public LeanCTX Runtime. \\
14         Local context tooling continues to work without an account. Set LEAN_CTX_EXPERIMENTAL_HOSTED=1 only for a local development evaluation."
15    );
16    false
17}
18
19fn mask_email(email: &str) -> String {
20    match email.split_once('@') {
21        Some((local, domain)) if local.len() > 2 => {
22            format!("{}...@{domain}", &local[..local.floor_char_boundary(2)])
23        }
24        _ => "***".to_string(),
25    }
26}
27
28fn parse_auth_args(args: &[String]) -> (String, Option<String>) {
29    let mut email = String::new();
30    let mut password: Option<String> = None;
31    let mut i = 0;
32    while i < args.len() {
33        match args[i].as_str() {
34            "--password" | "-p" => {
35                i += 1;
36                if i < args.len() {
37                    password = Some(args[i].clone());
38                }
39            }
40            _ => {
41                if email.is_empty() {
42                    email = args[i].trim().to_lowercase();
43                }
44            }
45        }
46        i += 1;
47    }
48    (email, password)
49}
50
51fn require_email_and_password(args: &[String], usage: &str) -> (String, String) {
52    let (email, password) = parse_auth_args(args);
53
54    if email.is_empty() {
55        eprintln!("Usage: {usage}");
56        std::process::exit(1);
57    }
58    if !email.contains('@') || !email.contains('.') {
59        tracing::error!("Invalid email address: {email}");
60        std::process::exit(1);
61    }
62
63    let pw = match password {
64        Some(p) => p,
65        None => match rpassword::prompt_password("Password: ") {
66            Ok(p) => p,
67            Err(e) => {
68                tracing::error!("Could not read password: {e}");
69                std::process::exit(1);
70            }
71        },
72    };
73    if pw.len() < 8 {
74        tracing::error!("Password must be at least 8 characters.");
75        std::process::exit(1);
76    }
77    (email, pw)
78}
79
80fn save_and_report(r: &cloud_client::RegisterResult, email: &str) {
81    if let Err(e) = cloud_client::save_credentials(&r.api_key, &r.user_id, email) {
82        tracing::warn!("Could not save credentials: {e}");
83        eprintln!("Please try again.");
84        return;
85    }
86    if let Ok(plan) = cloud_client::fetch_plan() {
87        let _ = cloud_client::save_plan(&plan);
88    }
89    // Upgrade remote auth to OAuth2 client_credentials when supported by the API.
90    match cloud_client::oauth_register_client(Some("lean-ctx-cli")) {
91        Ok(msg) => tracing::info!("{msg}"),
92        Err(e) => tracing::warn!("OAuth upgrade skipped: {e}"),
93    }
94
95    println!("Cloud credentials saved (see ~/.lean-ctx/cloud/credentials.json)");
96    if r.verification_sent {
97        println!("Verification email sent — please check your inbox.");
98    }
99    if !r.email_verified {
100        println!("Note: Your email is not yet verified.");
101    }
102}
103
104pub fn cmd_login(args: &[String]) {
105    if !require_hosted_research() {
106        return;
107    }
108    let (email, pw) = require_email_and_password(args, "lean-ctx login <email> [--password <pw>]");
109
110    println!("Logging in to LeanCTX Cloud...");
111
112    match cloud_client::login(&email, &pw) {
113        Ok(r) => {
114            save_and_report(&r, &email);
115            println!("Logged in as {}", mask_email(&email));
116        }
117        Err(e) if e.contains("403") => {
118            tracing::error!("Please verify your email first. Check your inbox.");
119            std::process::exit(1);
120        }
121        Err(e) if e.contains("Invalid email or password") => {
122            tracing::error!("Invalid email or password.");
123            eprintln!("Forgot your password? Run: lean-ctx forgot-password <email>");
124            eprintln!("No account yet? Run: lean-ctx register <email>");
125            std::process::exit(1);
126        }
127        Err(e) => {
128            tracing::error!("Login failed: {e}");
129            eprintln!("If you don't have an account yet, run: lean-ctx register <email>");
130            std::process::exit(1);
131        }
132    }
133}
134
135pub fn cmd_forgot_password(args: &[String]) {
136    if !require_hosted_research() {
137        return;
138    }
139    let (email, _) = parse_auth_args(args);
140
141    if email.is_empty() {
142        eprintln!("Usage: lean-ctx forgot-password <email>");
143        std::process::exit(1);
144    }
145
146    println!("Sending password reset email...");
147
148    match cloud_client::forgot_password(&email) {
149        Ok(_msg) => {
150            println!("Password reset email sent to {}.", mask_email(&email));
151            println!("Check your inbox and follow the reset link.");
152        }
153        Err(e) => {
154            tracing::error!("Failed: {e}");
155            std::process::exit(1);
156        }
157    }
158}
159
160pub fn cmd_register(args: &[String]) {
161    if !require_hosted_research() {
162        return;
163    }
164    let (email, pw) =
165        require_email_and_password(args, "lean-ctx register <email> [--password <pw>]");
166
167    println!("Creating LeanCTX Cloud account...");
168
169    match cloud_client::register(&email, Some(&pw)) {
170        Ok(r) => {
171            save_and_report(&r, &email);
172            println!("Account created for {}", mask_email(&email));
173        }
174        Err(e) if e.contains("409") || e.contains("already exists") => {
175            tracing::error!("An account with this email already exists.");
176            eprintln!("Run: lean-ctx login <email>");
177            std::process::exit(1);
178        }
179        Err(e) => {
180            tracing::error!("Registration failed: {e}");
181            std::process::exit(1);
182        }
183    }
184}
185
186pub fn cmd_sync(rest: &[String]) {
187    if !require_hosted_research() {
188        return;
189    }
190    if rest.first().map(String::as_str) == Some("index") {
191        cmd_sync_index(&rest[1..]);
192        return;
193    }
194    if !cloud_client::is_logged_in() {
195        tracing::error!("Not logged in. Run: lean-ctx login <email>");
196        std::process::exit(1);
197    }
198
199    // Stats roll-up is account-level and stays free for everyone.
200    println!("Syncing stats...");
201    let store = core::stats::load();
202    let entries = build_sync_entries(&store);
203    if entries.is_empty() {
204        println!("No stats to sync yet.");
205    } else {
206        match cloud_client::sync_stats(&entries) {
207            Ok(_) => println!("  Stats: synced"),
208            Err(e) => tracing::error!("Stats sync failed: {e}"),
209        }
210    }
211
212    // Everything below is the Pro "Personal Cloud" (cross-device sync of your own
213    // context). On a Free account the server returns 402; detect it once and show
214    // a friendly upgrade hint instead of one failure per surface.
215    if sync_personal_cloud(&store) == CloudSyncOutcome::Gated {
216        print_pro_upgrade_hint();
217        return;
218    }
219
220    if let Ok(plan) = cloud_client::fetch_plan() {
221        let _ = cloud_client::save_plan(&plan);
222    }
223
224    println!("Sync complete.");
225}
226
227/// `lean-ctx sync index <push|pull|status>` — the hosted Personal Index
228/// (GL #392): encrypted cross-device sync of the project's retrieval index.
229fn cmd_sync_index(args: &[String]) {
230    let sub = args.first().map_or("help", String::as_str);
231    let root = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
232
233    match sub {
234        "push" => match cloud_client::push_index_bundle(&root) {
235            Ok((project_hash, bytes)) => {
236                println!(
237                    "\x1b[32m✓\x1b[0m Index pushed ({:.1} MB encrypted, project {})",
238                    bytes as f64 / 1_048_576.0,
239                    &project_hash[..12.min(project_hash.len())]
240                );
241                println!("  Pull on any device: lean-ctx sync index pull");
242            }
243            Err(e) => {
244                eprintln!("\x1b[31m✗\x1b[0m {e}");
245                std::process::exit(1);
246            }
247        },
248        "pull" => match cloud_client::pull_index_bundle(&root) {
249            Ok(manifest) => {
250                println!(
251                    "\x1b[32m✓\x1b[0m Index restored ({} files, built {} by v{})",
252                    manifest.files.len(),
253                    manifest.created_at,
254                    manifest.engine_version
255                );
256                println!("  Semantic search is ready — no local re-index needed.");
257            }
258            Err(e) => {
259                eprintln!("\x1b[31m✗\x1b[0m {e}");
260                std::process::exit(1);
261            }
262        },
263        "status" => match cloud_client::index_bundle_status() {
264            Ok(v) => {
265                let used_mb = v["used_bytes"].as_u64().unwrap_or(0) as f64 / 1_048_576.0;
266                let quota_mb = v["quota_mb"].as_u64().unwrap_or(0);
267                println!("Hosted Personal Index");
268                println!("  Usage: {used_mb:.1} MB / {quota_mb} MB");
269                if let Some(line) = render_quota_state(&v["storage"]) {
270                    println!("  {line}");
271                }
272                if let Some(buckets) = v["projects"].as_array() {
273                    if buckets.is_empty() {
274                        println!("  No project bundles yet. Push one: lean-ctx sync index push");
275                    }
276                    for b in buckets {
277                        println!(
278                            "  • {}  {:.1} MB  (updated {})",
279                            b["project_hash"].as_str().unwrap_or("?"),
280                            b["size_bytes"].as_u64().unwrap_or(0) as f64 / 1_048_576.0,
281                            b["updated_at"].as_str().unwrap_or("?")
282                        );
283                    }
284                }
285            }
286            Err(e) => {
287                eprintln!("\x1b[31m✗\x1b[0m {e}");
288                std::process::exit(1);
289            }
290        },
291        _ => {
292            println!("Usage: lean-ctx sync index <push|pull|status>");
293            println!("  push    Pack, encrypt and upload this project's retrieval index");
294            println!("  pull    Download and restore the hosted index on this device");
295            println!("  status  Show hosted buckets and quota usage");
296        }
297    }
298}
299
300/// One human line for the server's billing-plane-v2 `storage` block (GL #392):
301/// green/yellow/red by threshold state, with the headroom or overage spelled
302/// out. `None` when the server (older deploy) sent no block — print nothing
303/// rather than guessing.
304fn render_quota_state(storage: &serde_json::Value) -> Option<String> {
305    let state = storage["state"].as_str()?;
306    let percent = storage["percent"].as_f64();
307    let pct = percent.map_or(String::new(), |p| format!(" ({p:.0}% of quota)"));
308    Some(match state {
309        "ok" => format!("State: \x1b[32mok\x1b[0m{pct}"),
310        "warn" => format!("State: \x1b[33mwarn\x1b[0m{pct} — consider pruning old buckets"),
311        "critical" => {
312            format!("State: \x1b[31mcritical\x1b[0m{pct} — next push may exceed the quota")
313        }
314        "over" => {
315            let over_mb = storage["overage_bytes"].as_u64().unwrap_or(0) as f64 / 1_000_000.0;
316            format!(
317                "State: \x1b[31mover\x1b[0m{pct} — {over_mb:.1} MB over; pushes are blocked (nothing is billed). Free space: lean-ctx sync index status / delete"
318            )
319        }
320        // "none" (no entitlement) and future states: the usage line above
321        // already says everything actionable.
322        _ => return None,
323    })
324}
325
326/// Whether a `cloud_client` error string is the server's Pro gate (HTTP 402),
327/// mirroring the existing 403 string-match in `cloud_client::pull_cloud_models`.
328fn pro_gate_hit(err: &str) -> bool {
329    err.contains("402")
330}
331
332#[derive(PartialEq, Eq)]
333enum CloudSyncOutcome {
334    Done,
335    Gated,
336}
337
338/// Push the Pro-gated "Personal Cloud" surfaces. Returns [`CloudSyncOutcome::Gated`]
339/// at the first 402 (a Free account) so the caller shows a single upgrade hint
340/// rather than one error per surface. A self-hosted backend with the gate open
341/// (billing unset / `LEANCTX_CLOUD_SYNC_OPEN`) never returns 402, so all sync.
342fn sync_personal_cloud(store: &core::stats::StatsStore) -> CloudSyncOutcome {
343    println!("Syncing commands...");
344    let command_entries = collect_command_entries(store);
345    if command_entries.is_empty() {
346        println!("  No command data to sync.");
347    } else {
348        match cloud_client::push_commands(&command_entries) {
349            Ok(_) => println!("  Commands: synced"),
350            Err(e) if pro_gate_hit(&e) => return CloudSyncOutcome::Gated,
351            Err(e) => tracing::error!("Commands sync failed: {e}"),
352        }
353    }
354
355    println!("Syncing CEP scores...");
356    let cep_entries = collect_cep_entries(store);
357    if cep_entries.is_empty() {
358        println!("  No CEP sessions to sync.");
359    } else {
360        match cloud_client::push_cep(&cep_entries) {
361            Ok(_) => println!("  CEP: synced"),
362            Err(e) if pro_gate_hit(&e) => return CloudSyncOutcome::Gated,
363            Err(e) => tracing::error!("CEP sync failed: {e}"),
364        }
365    }
366
367    println!("Syncing knowledge...");
368    let knowledge_entries = collect_knowledge_entries();
369    if knowledge_entries.is_empty() {
370        println!("  No knowledge to sync.");
371    } else {
372        match cloud_client::push_knowledge(&knowledge_entries) {
373            Ok(_) => println!("  Knowledge: synced"),
374            Err(e) if pro_gate_hit(&e) => return CloudSyncOutcome::Gated,
375            Err(e) => tracing::error!("Knowledge sync failed: {e}"),
376        }
377    }
378
379    println!("Syncing gotchas...");
380    let gotcha_entries = collect_gotcha_entries();
381    if gotcha_entries.is_empty() {
382        println!("  No gotchas to sync.");
383    } else {
384        match cloud_client::push_gotchas(&gotcha_entries) {
385            Ok(_) => println!("  Gotchas: synced"),
386            Err(e) if pro_gate_hit(&e) => return CloudSyncOutcome::Gated,
387            Err(e) => tracing::error!("Gotchas sync failed: {e}"),
388        }
389    }
390
391    println!("Syncing feedback thresholds...");
392    let feedback_entries = collect_feedback_entries();
393    if feedback_entries.is_empty() {
394        println!("  No feedback thresholds to sync.");
395    } else {
396        match cloud_client::push_feedback(&feedback_entries) {
397            Ok(_) => println!("  Feedback: synced"),
398            Err(e) if pro_gate_hit(&e) => return CloudSyncOutcome::Gated,
399            Err(e) => tracing::error!("Feedback sync failed: {e}"),
400        }
401    }
402
403    CloudSyncOutcome::Done
404}
405
406/// Friendly, non-error hint shown when the server gates cloud sync behind Pro.
407/// Delegates to the central, entitlement-aware hint helper (#346) so the message
408/// reflects the user's actual plan and the cheapest unlocking tier.
409fn print_pro_upgrade_hint() {
410    super::upgrade_hint::hint_for("cloud_sync");
411}
412
413fn build_sync_entries(store: &core::stats::StatsStore) -> Vec<serde_json::Value> {
414    crate::cloud_sync::build_sync_entries(store)
415}
416
417fn collect_knowledge_entries() -> Vec<serde_json::Value> {
418    crate::cloud_sync::collect_knowledge_entries()
419}
420
421fn collect_command_entries(store: &core::stats::StatsStore) -> Vec<serde_json::Value> {
422    crate::cloud_sync::collect_command_entries(store)
423}
424
425fn collect_cep_entries(store: &core::stats::StatsStore) -> Vec<serde_json::Value> {
426    crate::cloud_sync::collect_cep_entries(store)
427}
428
429fn collect_gotcha_entries() -> Vec<serde_json::Value> {
430    crate::cloud_sync::collect_gotcha_entries()
431}
432
433fn collect_feedback_entries() -> Vec<serde_json::Value> {
434    crate::cloud_sync::collect_feedback_entries()
435}
436
437pub fn cmd_contribute() {
438    if !require_hosted_research() {
439        return;
440    }
441    let mut entries = Vec::new();
442
443    // GH #439: mode_stats.json lives in the data dir — read it through the typed
444    // resolver (matching cloud_sync) instead of a stale ~/.lean-ctx path.
445    if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
446        let mode_stats_path = data_dir.join("mode_stats.json");
447        if let Ok(data) = std::fs::read_to_string(&mode_stats_path)
448            && let Ok(predictor) = serde_json::from_str::<serde_json::Value>(&data)
449            && let Some(history) = predictor["history"].as_object()
450        {
451            for (_sig_key, outcomes) in history {
452                if let Some(arr) = outcomes.as_array() {
453                    for outcome in arr.iter().rev().take(5) {
454                        let ext = outcome["ext"].as_str().unwrap_or("unknown");
455                        let mode = outcome["mode"].as_str().unwrap_or("full");
456                        let tokens_in = outcome["tokens_in"].as_u64().unwrap_or(0);
457                        let tokens_out = outcome["tokens_out"].as_u64().unwrap_or(0);
458                        let ratio = if tokens_in > 0 {
459                            1.0 - tokens_out as f64 / tokens_in as f64
460                        } else {
461                            0.0
462                        };
463                        let bucket = match tokens_in {
464                            0..=500 => "0-500",
465                            501..=2000 => "500-2k",
466                            2001..=10000 => "2k-10k",
467                            _ => "10k+",
468                        };
469                        entries.push(serde_json::json!({
470                            "file_ext": format!(".{ext}"),
471                            "size_bucket": bucket,
472                            "best_mode": mode,
473                            "compression_ratio": (ratio * 100.0).round() / 100.0,
474                        }));
475                        if entries.len() >= 500 {
476                            break;
477                        }
478                    }
479                }
480                if entries.len() >= 500 {
481                    break;
482                }
483            }
484        }
485    }
486
487    if entries.is_empty() {
488        let stats_data = core::stats::format_gain_json();
489        if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&stats_data) {
490            let original = parsed["cep"]["total_tokens_original"].as_u64().unwrap_or(0);
491            let compressed = parsed["cep"]["total_tokens_compressed"]
492                .as_u64()
493                .unwrap_or(0);
494            let overall_ratio = if original > 0 {
495                1.0 - compressed as f64 / original as f64
496            } else {
497                0.0
498            };
499
500            if let Some(modes) = parsed["cep"]["modes"].as_object() {
501                let read_modes = ["full", "map", "signatures", "auto", "aggressive", "entropy"];
502                for (mode, count) in modes {
503                    if !read_modes.contains(&mode.as_str()) || count.as_u64().unwrap_or(0) == 0 {
504                        continue;
505                    }
506                    entries.push(serde_json::json!({
507                        "file_ext": "mixed",
508                        "size_bucket": "mixed",
509                        "best_mode": mode,
510                        "compression_ratio": (overall_ratio * 100.0).round() / 100.0,
511                    }));
512                }
513            }
514        }
515    }
516
517    if entries.is_empty() {
518        println!("No compression data to contribute yet. Use lean-ctx for a while first.");
519        return;
520    }
521
522    println!("Contributing {} data points...", entries.len());
523    match cloud_client::contribute(&entries) {
524        Ok(msg) => println!("{msg}"),
525        Err(e) => {
526            tracing::error!("Contribute failed: {e}");
527            std::process::exit(1);
528        }
529    }
530}
531
532pub fn cmd_cloud(args: &[String]) {
533    if !require_hosted_research() {
534        return;
535    }
536    let action = args.first().map_or("help", std::string::String::as_str);
537
538    match action {
539        "pull-models" => {
540            println!("Updating adaptive models...");
541            match cloud_client::pull_cloud_models() {
542                Ok(data) => {
543                    let count = data
544                        .get("models")
545                        .and_then(|v| v.as_array())
546                        .map_or(0, std::vec::Vec::len);
547
548                    if let Err(e) = cloud_client::save_cloud_models(&data) {
549                        tracing::warn!("Could not save models: {e}");
550                        return;
551                    }
552                    println!("{count} adaptive models updated.");
553                    if let Some(est) = data
554                        .get("improvement_estimate")
555                        .and_then(serde_json::Value::as_f64)
556                    {
557                        println!("Estimated compression improvement: +{:.0}%", est * 100.0);
558                    }
559                }
560                Err(e) => {
561                    tracing::error!("{e}");
562                    std::process::exit(1);
563                }
564            }
565        }
566        "status" => cmd_cloud_status(),
567        "pull" => cmd_cloud_pull(),
568        "autosync" => cmd_cloud_autosync(args.get(1).map(String::as_str)),
569        "autoindex" => cmd_cloud_autoindex(args.get(1).map(String::as_str)),
570        "upgrade" | "subscribe" => cloud_upgrade(&args[1..]),
571        _ => {
572            println!("Usage: lean-ctx cloud <command>");
573            println!("  pull-models — Update adaptive compression models");
574            println!("  pull        — Restore your Personal Cloud knowledge onto this machine");
575            println!("  autosync    — on|off|status: daily background Personal Cloud push (Pro)");
576            println!("  autoindex   — on|off|status: daily background hosted-index push (Pro)");
577            println!("  status      — Show cloud connection status");
578            println!(
579                "  upgrade     — Subscribe to Pro (Personal Cloud) or Team \
580                 [--plan pro|team] [--interval monthly|yearly]"
581            );
582        }
583    }
584}
585
586/// `lean-ctx cloud status` — your Personal Cloud, from the terminal. Shows the
587/// same privacy-preserving footprint as leanctx.com/account/cloud: per-bucket
588/// `lean-ctx cloud autosync <on|off|status>` — toggle the daily background
589/// Personal-Cloud push (GL #384). The flag lives in `[cloud] auto_sync`.
590fn cmd_cloud_autosync(arg: Option<&str>) {
591    let mut config = core::config::Config::load_global();
592    match arg {
593        Some("on") => {
594            config.cloud.auto_sync = true;
595            if let Err(e) = config.save() {
596                tracing::error!("Could not save config: {e}");
597                std::process::exit(1);
598            }
599            println!(
600                "Auto-sync enabled — your Personal Cloud (knowledge, commands, CEP, gotchas, buddy, feedback)"
601            );
602            println!(
603                "is pushed silently once per day at session end. Requires Pro and an active login."
604            );
605            if !cloud_client::is_logged_in() {
606                println!("Note: you are not logged in yet. Run: lean-ctx login <email>");
607            }
608        }
609        Some("off") => {
610            config.cloud.auto_sync = false;
611            if let Err(e) = config.save() {
612                tracing::error!("Could not save config: {e}");
613                std::process::exit(1);
614            }
615            println!("Auto-sync disabled. Manual sync stays available via: lean-ctx sync");
616        }
617        Some("status") | None => {
618            let state = if config.cloud.auto_sync { "on" } else { "off" };
619            println!("Auto-sync: {state}");
620            match config.cloud.last_auto_sync.as_deref() {
621                Some(date) => println!("Last auto-sync: {date}"),
622                None => println!("Last auto-sync: never"),
623            }
624            if !config.cloud.auto_sync {
625                println!("Enable with: lean-ctx cloud autosync on");
626            }
627        }
628        Some(other) => {
629            tracing::error!("Unknown autosync action: {other}. Use on|off|status.");
630            std::process::exit(1);
631        }
632    }
633}
634
635/// `lean-ctx cloud autoindex <on|off|status>` — toggle the daily background
636/// hosted-index push (GL #392). Separate flag from `autosync` because index
637/// bundles are megabytes, not kilobytes. The flag lives in `[cloud] auto_index`.
638fn cmd_cloud_autoindex(arg: Option<&str>) {
639    let mut config = core::config::Config::load_global();
640    match arg {
641        Some("on") => {
642            config.cloud.auto_index = true;
643            if let Err(e) = config.save() {
644                tracing::error!("Could not save config: {e}");
645                std::process::exit(1);
646            }
647            println!(
648                "Auto-index enabled — this project's encrypted retrieval index is pushed \
649                 silently once per day when it changes. Requires Pro and an active login."
650            );
651            if !cloud_client::is_logged_in() {
652                println!("Note: you are not logged in yet. Run: lean-ctx login <email>");
653            }
654        }
655        Some("off") => {
656            config.cloud.auto_index = false;
657            if let Err(e) = config.save() {
658                tracing::error!("Could not save config: {e}");
659                std::process::exit(1);
660            }
661            println!(
662                "Auto-index disabled. Manual push stays available via: lean-ctx sync index push"
663            );
664        }
665        Some("status") | None => {
666            let state = if config.cloud.auto_index { "on" } else { "off" };
667            println!("Auto-index: {state}");
668            let root = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
669            let hash = core::index_namespace::namespace_hash(&root);
670            match config.cloud.last_index_push.get(&hash) {
671                Some(date) => println!("Last push (this project): {date}"),
672                None => println!("Last push (this project): never"),
673            }
674            if !config.cloud.auto_index {
675                println!("Enable with: lean-ctx cloud autoindex on");
676            }
677        }
678        Some(other) => {
679            tracing::error!("Unknown autoindex action: {other}. Use on|off|status.");
680            std::process::exit(1);
681        }
682    }
683}
684
685/// counts + last sync, buddy, and the all-time usage totals. Free accounts see
686/// the connection state plus what upgrading unlocks.
687fn cmd_cloud_status() {
688    if !cloud_client::is_logged_in() {
689        println!("Not connected to LeanCTX Cloud.");
690        println!("Get started: lean-ctx login <email>");
691        return;
692    }
693    let email = cloud_client::account_email().unwrap_or_default();
694    println!("Connected to the development-only hosted evaluation as {email}.");
695
696    let d = match cloud_client::fetch_account_cloud() {
697        Ok(d) => d,
698        Err(e) => {
699            tracing::warn!("Could not fetch cloud status: {e}");
700            return;
701        }
702    };
703
704    let plan = d.get("plan").and_then(|v| v.as_str()).unwrap_or("free");
705    println!("Plan: {plan}");
706
707    if d.get("cloud_sync").and_then(serde_json::Value::as_bool) != Some(true) {
708        println!("Personal Cloud sync: locked on this plan.");
709        super::upgrade_hint::hint_for("cloud_sync");
710        return;
711    }
712
713    match d.get("last_synced_at").and_then(|v| v.as_str()) {
714        Some(ts) => println!("Last synced: {ts}"),
715        None => println!("Last synced: never — run `lean-ctx sync` on this machine."),
716    }
717
718    // Mirror the website's bucket order and labels.
719    const BUCKETS: [(&str, &str, &str); 6] = [
720        ("knowledge", "Knowledge & memory", "facts"),
721        ("commands", "Learned shell patterns", "patterns"),
722        ("cep", "CEP score history", "snapshots"),
723        ("gain", "GAIN score history", "snapshots"),
724        ("gotchas", "Gotchas", "fixes"),
725        ("feedback", "Feedback thresholds", "languages"),
726    ];
727    println!("\nSynced to your Personal Cloud:");
728    for (key, label, unit) in BUCKETS {
729        let count = d
730            .get("buckets")
731            .and_then(|b| b.get(key))
732            .and_then(|b| b.get("count"))
733            .and_then(serde_json::Value::as_i64)
734            .unwrap_or(0);
735        if count > 0 {
736            println!("  {label:<24} {count} {unit}");
737        } else {
738            println!("  {label:<24} —");
739        }
740    }
741
742    if let Some(buddy) = d
743        .get("buddy")
744        .filter(|b| b.get("present").and_then(serde_json::Value::as_bool) == Some(true))
745    {
746        let name = buddy
747            .get("name")
748            .and_then(|v| v.as_str())
749            .unwrap_or("Buddy");
750        let level = buddy
751            .get("level")
752            .and_then(serde_json::Value::as_i64)
753            .unwrap_or(1);
754        println!("  {:<24} {name} (level {level})", "Buddy");
755    }
756
757    if let Some(totals) = d.get("usage").and_then(|u| u.get("totals")) {
758        let tokens = totals
759            .get("tokens_saved")
760            .and_then(serde_json::Value::as_i64)
761            .unwrap_or(0);
762        let sessions = totals
763            .get("sessions")
764            .and_then(serde_json::Value::as_i64)
765            .unwrap_or(0);
766        if sessions > 0 {
767            println!("\nAll-time: {tokens} tokens saved across {sessions} synced sessions.");
768        }
769    }
770    println!("\nFull dashboard: https://leanctx.com/account/cloud/");
771}
772
773/// `lean-ctx cloud pull` — the read side of the Pro "Personal Cloud". `lean-ctx
774/// sync` pushes your knowledge to the account; this restores it onto the current
775/// machine, so your context follows you across devices. Facts are merged into the
776/// current project's local store with skip-existing semantics, so a local fact is
777/// never clobbered and re-running is idempotent. A Free account hits the 402 gate
778/// and gets the same upgrade hint as `sync`.
779fn cmd_cloud_pull() {
780    if !cloud_client::is_logged_in() {
781        eprintln!("Not logged in. Run: lean-ctx login <email>");
782        std::process::exit(1);
783    }
784
785    let project_root = std::env::current_dir()
786        .map_or_else(|_| ".".to_string(), |p| p.to_string_lossy().to_string());
787
788    println!("Pulling knowledge from LeanCTX Cloud...");
789    let entries = match cloud_client::pull_knowledge() {
790        Ok(e) => e,
791        Err(e) if pro_gate_hit(&e) => {
792            print_pro_upgrade_hint();
793            std::process::exit(1);
794        }
795        Err(e) => {
796            tracing::error!("Pull failed: {e}");
797            std::process::exit(1);
798        }
799    };
800
801    if entries.is_empty() {
802        println!(
803            "No cloud knowledge to restore yet. Run `lean-ctx sync` on another machine first."
804        );
805        return;
806    }
807
808    let facts = match parse_pulled_knowledge(&entries) {
809        Ok(f) => f,
810        Err(e) => {
811            tracing::error!("Could not parse pulled knowledge: {e}");
812            std::process::exit(1);
813        }
814    };
815
816    let policy = match crate::tools::knowledge_shared::load_policy_or_error() {
817        Ok(p) => p,
818        Err(e) => {
819            eprintln!("{e}");
820            std::process::exit(1);
821        }
822    };
823
824    // #326/#594-A4: import under the project lock so a cloud-pull cannot clobber
825    // a concurrent foreground remember/import. The closure reloads the latest
826    // on-disk state inside the lock before merging.
827    match core::knowledge::ProjectKnowledge::mutate_locked(&project_root, |knowledge| {
828        knowledge.import_facts(
829            facts,
830            core::knowledge::ImportMerge::SkipExisting,
831            "cloud-pull",
832            &policy,
833        )
834    }) {
835        Ok((_, result)) => {
836            println!(
837                "  Knowledge: {} restored, {} already present (into {project_root})",
838                result.added, result.skipped
839            );
840            println!("Pull complete.");
841        }
842        Err(e) => {
843            tracing::error!("Knowledge restore failed: {e}");
844            std::process::exit(1);
845        }
846    }
847}
848
849/// Map the server's `{category, key, value, updated_by, updated_at}` rows onto the
850/// import schema (`value` + `source`/`timestamp` provenance) and reuse the
851/// battle-tested [`parse_import_data`] importer rather than re-deriving the
852/// `KnowledgeFact` shape here.
853fn parse_pulled_knowledge(
854    entries: &[serde_json::Value],
855) -> Result<Vec<core::knowledge::KnowledgeFact>, String> {
856    let str_field = |e: &serde_json::Value, k: &str| {
857        e.get(k)
858            .and_then(serde_json::Value::as_str)
859            .unwrap_or_default()
860            .to_string()
861    };
862    let simple: Vec<serde_json::Value> = entries
863        .iter()
864        .map(|e| {
865            serde_json::json!({
866                "category": str_field(e, "category"),
867                "key": str_field(e, "key"),
868                "value": str_field(e, "value"),
869                "source": e.get("updated_by").and_then(serde_json::Value::as_str),
870                "timestamp": e.get("updated_at").and_then(serde_json::Value::as_str),
871            })
872        })
873        .collect();
874    let data = serde_json::to_string(&simple).map_err(|e| e.to_string())?;
875    core::knowledge::parse_import_data(&data)
876}
877
878/// `lean-ctx cloud upgrade [--plan pro|team] [--interval monthly|yearly]`
879/// — start a hosted Stripe Checkout for the logged-in account and print the URL
880/// to open. Defaults to Pro monthly (the self-serve Personal Cloud tier).
881fn cloud_upgrade(args: &[String]) {
882    if !cloud_client::is_logged_in() {
883        eprintln!("Not logged in. Run: lean-ctx login <email>");
884        std::process::exit(1);
885    }
886    let (plan, interval) = match parse_upgrade_args(args) {
887        Ok(pi) => pi,
888        Err(e) => {
889            eprintln!("{e}");
890            eprintln!(
891                "Usage: lean-ctx cloud upgrade [--plan pro|team] [--interval monthly|yearly]"
892            );
893            std::process::exit(1);
894        }
895    };
896
897    println!("Starting {plan} checkout ({interval})...");
898    match cloud_client::start_checkout(&plan, &interval) {
899        Ok(url) => {
900            println!();
901            println!("Open this link to complete your subscription:");
902            println!("  {url}");
903        }
904        Err(e) => {
905            tracing::error!("Could not start checkout: {e}");
906            std::process::exit(1);
907        }
908    }
909}
910
911/// Parse the optional `--plan` / `--interval` flags for `cloud upgrade`. Defaults
912/// are Pro + monthly. Only `pro`/`team` and `monthly`/`yearly` are accepted; an
913/// unknown value is an error (so a typo never silently buys the wrong plan).
914/// Enterprise stays sales-assisted and is deliberately absent.
915fn parse_upgrade_args(args: &[String]) -> Result<(String, String), String> {
916    let mut plan = "pro".to_string();
917    let mut interval = "monthly".to_string();
918    let mut i = 0;
919    while i < args.len() {
920        match args[i].as_str() {
921            "--plan" => {
922                i += 1;
923                let v = args.get(i).ok_or("--plan needs a value (pro|team)")?;
924                if !matches!(v.as_str(), "pro" | "team") {
925                    return Err(format!("unknown plan '{v}' (use pro or team)"));
926                }
927                plan.clone_from(v);
928            }
929            "--interval" => {
930                i += 1;
931                let v = args
932                    .get(i)
933                    .ok_or("--interval needs a value (monthly|yearly)")?;
934                if !matches!(v.as_str(), "monthly" | "yearly") {
935                    return Err(format!("unknown interval '{v}' (use monthly or yearly)"));
936                }
937                interval.clone_from(v);
938            }
939            "--yearly" => interval = "yearly".to_string(),
940            "--monthly" => interval = "monthly".to_string(),
941            other => return Err(format!("unknown option '{other}'")),
942        }
943        i += 1;
944    }
945    Ok((plan, interval))
946}
947
948pub fn cmd_gotchas(args: &[String]) {
949    let action = args.first().map_or("list", std::string::String::as_str);
950    let project_root = std::env::current_dir()
951        .map_or_else(|_| ".".to_string(), |p| p.to_string_lossy().to_string());
952
953    match action {
954        "list" | "ls" => {
955            let store = core::gotcha_tracker::GotchaStore::load(&project_root);
956            println!("{}", store.format_list());
957        }
958        "clear" => {
959            let mut store = core::gotcha_tracker::GotchaStore::load(&project_root);
960            let count = store.gotchas.len();
961            store.clear();
962            let _ = store.save(&project_root);
963            println!("Cleared {count} gotchas.");
964        }
965        "export" => {
966            let store = core::gotcha_tracker::GotchaStore::load(&project_root);
967            match serde_json::to_string_pretty(&store.gotchas) {
968                Ok(json) => println!("{json}"),
969                Err(e) => tracing::error!("Export failed: {e}"),
970            }
971        }
972        "stats" => {
973            let store = core::gotcha_tracker::GotchaStore::load(&project_root);
974            println!("Bug Memory Stats:");
975            println!("  Active gotchas:      {}", store.gotchas.len());
976            println!(
977                "  Errors detected:     {}",
978                store.stats.total_errors_detected
979            );
980            println!(
981                "  Fixes correlated:    {}",
982                store.stats.total_fixes_correlated
983            );
984            println!("  Bugs prevented:      {}", store.stats.total_prevented);
985            println!("  Promoted to knowledge: {}", store.stats.gotchas_promoted);
986            println!("  Decayed/archived:    {}", store.stats.gotchas_decayed);
987            println!("  Session logs:        {}", store.error_log.len());
988        }
989        "reflect" | "ledger" => {
990            let store = core::gotcha_tracker::GotchaStore::load(&project_root);
991            println!("{}", core::gotcha_tracker::format_ledger(&store));
992        }
993        _ => {
994            println!("Usage: lean-ctx gotchas [list|clear|export|stats|reflect]");
995        }
996    }
997}
998
999pub fn cmd_buddy(_args: &[String]) {
1000    println!("Buddy has been removed.");
1001}
1002
1003pub fn cmd_upgrade() {
1004    println!("'upgrade' has been renamed to 'update'. Running 'lean-ctx update' instead.\n");
1005    core::updater::run(&[]);
1006}
1007
1008#[cfg(test)]
1009mod tests {
1010    use super::*;
1011
1012    #[test]
1013    fn pro_gate_hit_detects_402_only() {
1014        // The server's Pro gate surfaces as a 402 inside the error string.
1015        assert!(pro_gate_hit(
1016            "Push failed: http status 402 Payment Required"
1017        ));
1018        // Other failures must NOT be treated as the gate (they stay errors).
1019        assert!(!pro_gate_hit("Push failed: http status 500"));
1020        assert!(!pro_gate_hit("Push failed: connection refused"));
1021        assert!(!pro_gate_hit("401 Unauthorized"));
1022    }
1023
1024    fn s(args: &[&str]) -> Vec<String> {
1025        args.iter().map(|a| (*a).to_string()).collect()
1026    }
1027
1028    #[test]
1029    fn upgrade_args_default_to_pro_monthly() {
1030        assert_eq!(
1031            parse_upgrade_args(&[]).unwrap(),
1032            ("pro".to_string(), "monthly".to_string())
1033        );
1034    }
1035
1036    #[test]
1037    fn upgrade_args_accept_team_and_yearly() {
1038        assert_eq!(
1039            parse_upgrade_args(&s(&["--plan", "team", "--interval", "yearly"])).unwrap(),
1040            ("team".to_string(), "yearly".to_string())
1041        );
1042        // Shorthand cadence flags.
1043        assert_eq!(
1044            parse_upgrade_args(&s(&["--yearly"])).unwrap(),
1045            ("pro".to_string(), "yearly".to_string())
1046        );
1047        // Legacy "business" is no longer accepted (merged into team).
1048        assert!(parse_upgrade_args(&s(&["--plan", "business"])).is_err());
1049    }
1050
1051    #[test]
1052    fn upgrade_args_reject_unknown_values() {
1053        // A typo'd plan must error, never silently fall back to a purchase.
1054        assert!(parse_upgrade_args(&s(&["--plan", "enterprise"])).is_err());
1055        assert!(parse_upgrade_args(&s(&["--interval", "weekly"])).is_err());
1056        assert!(parse_upgrade_args(&s(&["--plan"])).is_err());
1057        assert!(parse_upgrade_args(&s(&["--bogus"])).is_err());
1058    }
1059
1060    #[test]
1061    fn parse_pulled_knowledge_maps_server_rows() {
1062        // The GET /api/sync/knowledge contract: {category, key, value,
1063        // updated_by, updated_at}. The pull path must map these onto facts and
1064        // carry provenance (updated_by -> source_session).
1065        let rows = vec![
1066            serde_json::json!({
1067                "category": "architecture",
1068                "key": "db",
1069                "value": "PostgreSQL 16 with pgvector",
1070                "updated_by": "me@example.com",
1071                "updated_at": "2026-01-02T03:04:05Z"
1072            }),
1073            serde_json::json!({
1074                "category": "decision",
1075                "key": "auth",
1076                "value": "JWT RS256"
1077            }),
1078        ];
1079        let facts = parse_pulled_knowledge(&rows).expect("rows must parse");
1080        assert_eq!(facts.len(), 2);
1081        assert_eq!(facts[0].category, "architecture");
1082        assert_eq!(facts[0].key, "db");
1083        assert_eq!(facts[0].value, "PostgreSQL 16 with pgvector");
1084        assert_eq!(facts[0].source_session, "me@example.com");
1085        // Rows without updated_by fall back to the importer's default source.
1086        assert_eq!(facts[1].value, "JWT RS256");
1087    }
1088
1089    #[test]
1090    fn parse_pulled_knowledge_handles_empty() {
1091        assert!(parse_pulled_knowledge(&[]).unwrap().is_empty());
1092    }
1093}