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