Skip to main content

lean_ctx/cli/
cloud.rs

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