1use crate::core::config::Config;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum AutoSyncOutcome {
6 Synced,
8 Gated,
10 Unauthenticated,
14 NetworkFailure,
17}
18
19#[must_use]
22pub fn should_auto_sync(
23 auto_sync: bool,
24 logged_in: bool,
25 last_auto_sync: Option<&str>,
26 today: &str,
27) -> bool {
28 auto_sync && logged_in && last_auto_sync != Some(today)
29}
30
31#[must_use]
35pub fn should_auto_push_index(
36 auto_index: bool,
37 logged_in: bool,
38 local_index_exists: bool,
39 last_push_for_project: Option<&str>,
40 today: &str,
41) -> bool {
42 auto_index && logged_in && local_index_exists && last_push_for_project != Some(today)
43}
44
45#[must_use]
49pub fn consumes_daily_slot(outcome: AutoSyncOutcome) -> bool {
50 outcome != AutoSyncOutcome::NetworkFailure
51}
52
53#[must_use]
59pub fn classify_outcomes(results: &[Result<(), String>]) -> AutoSyncOutcome {
60 if results
61 .iter()
62 .any(|r| r.as_ref().is_err_and(|e| e.contains("401")))
63 {
64 return AutoSyncOutcome::Unauthenticated;
65 }
66 if results
67 .iter()
68 .any(|r| r.as_ref().is_err_and(|e| e.contains("402")))
69 {
70 return AutoSyncOutcome::Gated;
71 }
72 if !results.is_empty() && results.iter().all(Result::is_err) {
73 return AutoSyncOutcome::NetworkFailure;
74 }
75 AutoSyncOutcome::Synced
76}
77
78pub fn cloud_background_tasks() {
79 let mut config = Config::load_global();
82 let today = chrono::Local::now().format("%Y-%m-%d").to_string();
83
84 let already_heartbeated = config
85 .telemetry
86 .last_heartbeat
87 .as_deref()
88 .is_some_and(|d| d == today);
89 let already_synced = config
90 .cloud
91 .last_sync
92 .as_deref()
93 .is_some_and(|d| d == today);
94 let already_gain_synced = config
95 .cloud
96 .last_gain_sync
97 .as_deref()
98 .is_some_and(|d| d == today);
99 let already_pulled = config
100 .cloud
101 .last_model_pull
102 .as_deref()
103 .is_some_and(|d| d == today);
104
105 if config.telemetry.enabled && !already_heartbeated {
107 if let Ok(id) = crate::core::installation_id::get_or_create() {
108 let contribute = collect_contribute_entries();
109 let payload = serde_json::json!({
110 "installation_id": id,
111 "version": env!("CARGO_PKG_VERSION"),
112 "os": std::env::consts::OS,
113 "arch": std::env::consts::ARCH,
114 "contribute_entries": contribute,
115 });
116 if crate::cloud_client::heartbeat(&payload).is_ok() {
117 config.telemetry.last_heartbeat = Some(today.clone());
118 let record = crate::core::telemetry_ledger::HeartbeatRecord {
119 timestamp: chrono::Utc::now().to_rfc3339(),
120 installation_id: id.clone(),
121 version: env!("CARGO_PKG_VERSION").to_string(),
122 os: std::env::consts::OS.to_string(),
123 arch: std::env::consts::ARCH.to_string(),
124 };
125 let _ = crate::core::telemetry_ledger::append(&record);
126 }
127 }
128 }
129
130 if crate::cloud_client::is_logged_in() {
131 if config.cloud.sync_stats_enabled && !already_synced {
132 let store = crate::core::stats::load();
133 let entries = build_sync_entries(&store);
134 if !entries.is_empty() && crate::cloud_client::sync_stats(&entries).is_ok() {
135 config.cloud.last_sync = Some(today.clone());
136 }
137 }
138
139 if config.cloud.sync_gain_enabled && !already_gain_synced {
140 let engine = crate::core::gain::GainEngine::load();
141 let summary = engine.summary(None);
142 let trend = match summary.score.trend {
143 crate::core::gain::gain_score::Trend::Rising => "rising",
144 crate::core::gain::gain_score::Trend::Stable => "stable",
145 crate::core::gain::gain_score::Trend::Declining => "declining",
146 };
147 let entry = serde_json::json!({
148 "recorded_at": format!("{today}T00:00:00Z"),
149 "total": summary.score.total as f64,
150 "compression": summary.score.compression as f64,
151 "cost_efficiency": summary.score.cost_efficiency as f64,
152 "quality": summary.score.quality as f64,
153 "consistency": summary.score.consistency as f64,
154 "navigability": summary.score.navigability as f64,
155 "trend": trend,
156 "avoided_usd": summary.avoided_usd,
157 "tool_spend_usd": summary.tool_spend_usd,
158 "model_key": summary.model.model_key,
159 });
160 if crate::cloud_client::push_gain(&[entry]).is_ok() {
161 config.cloud.last_gain_sync = Some(today.clone());
162 }
163 }
164
165 if config.cloud.sync_models_enabled
166 && !already_pulled
167 && let Ok(data) = crate::cloud_client::pull_cloud_models()
168 {
169 let _ = crate::cloud_client::save_cloud_models(&data);
170 config.cloud.last_model_pull = Some(today.clone());
171 }
172
173 if should_auto_sync(
178 config.cloud.auto_sync,
179 true,
180 config.cloud.last_auto_sync.as_deref(),
181 &today,
182 ) && consumes_daily_slot(auto_sync_personal_cloud())
183 {
184 config.cloud.last_auto_sync = Some(today.clone());
185 }
186
187 if let Ok(root) = std::env::current_dir() {
191 let project_hash = crate::core::index_namespace::namespace_hash(&root);
192 if should_auto_push_index(
193 config.cloud.auto_index,
194 true,
195 crate::core::index_bundle::local_index_present(&root),
196 config
197 .cloud
198 .last_index_push
199 .get(&project_hash)
200 .map(String::as_str),
201 &today,
202 ) {
203 match crate::cloud_client::push_index_bundle(&root) {
204 Ok((hash, bytes)) => {
205 tracing::debug!(project = %hash, bytes, "auto-index: pushed");
206 config
207 .cloud
208 .last_index_push
209 .insert(project_hash, today.clone());
210 }
211 Err(e) if e.contains("Pro") || e.contains("Quota") => {
212 tracing::debug!(error = %e, "auto-index: gated, retry tomorrow");
213 config
214 .cloud
215 .last_index_push
216 .insert(project_hash, today.clone());
217 }
218 Err(e) => {
219 tracing::debug!(error = %e, "auto-index: push failed, slot stays open");
220 }
221 }
222 }
223 }
224 }
225
226 if let Err(e) = config.save() {
227 tracing::warn!("could not persist cloud background state: {e}");
228 }
229}
230
231fn auto_sync_personal_cloud() -> AutoSyncOutcome {
234 let store = crate::core::stats::load();
235 let mut results: Vec<Result<(), String>> = Vec::new();
236
237 let mut push = |label: &str, result: Result<String, String>| match result {
238 Ok(_) => {
239 tracing::debug!(surface = label, "auto-sync: pushed");
240 results.push(Ok(()));
241 }
242 Err(e) => {
243 tracing::debug!(surface = label, error = %e, "auto-sync: push failed");
244 results.push(Err(e));
245 }
246 };
247
248 let commands = collect_command_entries(&store);
249 if !commands.is_empty() {
250 push("commands", crate::cloud_client::push_commands(&commands));
251 }
252 let cep = collect_cep_entries(&store);
253 if !cep.is_empty() {
254 push("cep", crate::cloud_client::push_cep(&cep));
255 }
256 let knowledge = collect_knowledge_entries();
257 if !knowledge.is_empty() {
258 push("knowledge", crate::cloud_client::push_knowledge(&knowledge));
259 }
260 let gotchas = collect_gotcha_entries();
261 if !gotchas.is_empty() {
262 push("gotchas", crate::cloud_client::push_gotchas(&gotchas));
263 }
264 let feedback = collect_feedback_entries();
265 if !feedback.is_empty() {
266 push("feedback", crate::cloud_client::push_feedback(&feedback));
267 }
268
269 let outcome = classify_outcomes(&results);
270 tracing::info!(
271 ?outcome,
272 surfaces = results.len(),
273 "personal-cloud auto-sync done"
274 );
275
276 static GATE_WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
277 if outcome == AutoSyncOutcome::Gated
278 && !GATE_WARNED.swap(true, std::sync::atomic::Ordering::Relaxed)
279 {
280 eprintln!(
281 "\n \x1b[33m⚠\x1b[0m Personal Cloud sync requires Pro. \
282 Your local data is safe.\n \
283 Unlock: lean-ctx cloud upgrade --plan pro ($9/mo)\n"
284 );
285 }
286
287 static AUTH_WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
290 if outcome == AutoSyncOutcome::Unauthenticated
291 && !AUTH_WARNED.swap(true, std::sync::atomic::Ordering::Relaxed)
292 {
293 eprintln!(
294 "\n \x1b[33m⚠\x1b[0m Personal Cloud sync is signed out on this machine \
295 — the server rejected this device's key.\n \
296 Your local data is safe, and nothing on the server was lost.\n \
297 Sign in again to resume syncing: lean-ctx login\n"
298 );
299 }
300
301 outcome
302}
303
304pub fn build_sync_entries(store: &crate::core::stats::StatsStore) -> Vec<serde_json::Value> {
305 let mut entries = Vec::new();
306 let cep = &store.cep;
307 let today = chrono::Local::now().format("%Y-%m-%d").to_string();
308
309 let mut cep_cache_by_day: std::collections::HashMap<String, (u64, u64)> =
310 std::collections::HashMap::new();
311 for s in &cep.scores {
312 if let Some(date) = s.timestamp.get(..10) {
313 let entry = cep_cache_by_day.entry(date.to_string()).or_default();
314 let calls = s.tool_calls.max(1);
315 let hits = (calls as f64 * s.cache_hit_rate as f64 / 100.0).round() as u64;
316 entry.0 += calls;
317 entry.1 += hits;
318 }
319 }
320
321 let mut mcp_saved_total = 0u64;
322 for (cmd, s) in &store.commands {
323 if cmd.starts_with("ctx_") {
324 mcp_saved_total += s.input_tokens.saturating_sub(s.output_tokens);
325 }
326 }
327 let global_saved = store
328 .total_input_tokens
329 .saturating_sub(store.total_output_tokens)
330 .max(1);
331 let mcp_ratio = mcp_saved_total as f64 / global_saved as f64;
332
333 for day in &store.daily {
334 let tokens_original = day.input_tokens;
335 let tokens_compressed = day.output_tokens;
336 let tokens_saved = tokens_original.saturating_sub(tokens_compressed);
337 let (day_calls, day_hits) = cep_cache_by_day.get(&day.date).copied().unwrap_or((0, 0));
338 let day_mcp_saved = (tokens_saved as f64 * mcp_ratio).round() as u64;
339 let day_hook_saved = tokens_saved.saturating_sub(day_mcp_saved);
340 entries.push(serde_json::json!({
341 "date": day.date,
342 "tokens_original": tokens_original,
343 "tokens_compressed": tokens_compressed,
344 "tokens_saved": tokens_saved,
345 "mcp_tokens_saved": day_mcp_saved,
346 "hook_tokens_saved": day_hook_saved,
347 "tool_calls": day.commands,
348 "cache_hits": day_hits,
349 "cache_misses": day_calls.saturating_sub(day_hits),
350 }));
351 }
352
353 let has_today = entries.iter().any(|e| e["date"].as_str() == Some(&today));
354 if !has_today && (cep.total_tokens_original > 0 || store.total_commands > 0) {
355 let today_saved = cep
356 .total_tokens_original
357 .saturating_sub(cep.total_tokens_compressed);
358 let today_mcp = (today_saved as f64 * mcp_ratio).round() as u64;
359 entries.push(serde_json::json!({
360 "date": today,
361 "tokens_original": cep.total_tokens_original,
362 "tokens_compressed": cep.total_tokens_compressed,
363 "tokens_saved": today_saved,
364 "mcp_tokens_saved": today_mcp,
365 "hook_tokens_saved": today_saved.saturating_sub(today_mcp),
366 "tool_calls": store.total_commands,
367 "cache_hits": cep.total_cache_hits,
368 "cache_misses": cep.total_cache_reads.saturating_sub(cep.total_cache_hits),
369 }));
370 }
371
372 entries
373}
374
375pub fn collect_knowledge_entries() -> Vec<serde_json::Value> {
380 let Ok(data_dir) = crate::core::paths::data_dir() else {
381 return Vec::new();
382 };
383 let knowledge_dir = data_dir.join("knowledge");
384 if !knowledge_dir.is_dir() {
385 return Vec::new();
386 }
387
388 let mut entries = Vec::new();
389
390 for project_entry in std::fs::read_dir(&knowledge_dir).into_iter().flatten() {
391 let Ok(project_entry) = project_entry else {
392 continue;
393 };
394 let project_path = project_entry.path();
395 if !project_path.is_dir() {
396 continue;
397 }
398
399 for file_entry in std::fs::read_dir(&project_path).into_iter().flatten() {
400 let Ok(file_entry) = file_entry else { continue };
401 let file_path = file_entry.path();
402 if file_path.extension().and_then(|e| e.to_str()) != Some("json") {
403 continue;
404 }
405 let Ok(data) = std::fs::read_to_string(&file_path) else {
406 continue;
407 };
408 let parsed: serde_json::Value = match serde_json::from_str(&data) {
409 Ok(v) => v,
410 Err(_) => continue,
411 };
412
413 if let Some(facts) = parsed["facts"].as_array() {
414 for fact in facts {
415 let cat = fact["category"].as_str().unwrap_or("general");
416 let key = fact["key"].as_str().unwrap_or("");
417 let val = fact["value"]
418 .as_str()
419 .or_else(|| fact["description"].as_str())
420 .unwrap_or("");
421 if !key.is_empty() {
422 entries.push(serde_json::json!({
423 "category": cat,
424 "key": key,
425 "value": val,
426 }));
427 }
428 }
429 }
430
431 if let Some(gotchas) = parsed["gotchas"].as_array() {
432 for g in gotchas {
433 let pattern = g["pattern"].as_str().unwrap_or("");
434 let fix = g["fix"].as_str().unwrap_or("");
435 if !pattern.is_empty() {
436 entries.push(serde_json::json!({
437 "category": "gotcha",
438 "key": pattern,
439 "value": fix,
440 }));
441 }
442 }
443 }
444 }
445 }
446
447 entries
448}
449
450pub fn collect_command_entries(store: &crate::core::stats::StatsStore) -> Vec<serde_json::Value> {
451 store
452 .commands
453 .iter()
454 .map(|(name, stats)| {
455 let tokens_saved = stats.input_tokens.saturating_sub(stats.output_tokens);
456 serde_json::json!({
457 "command": name,
458 "source": if name.starts_with("ctx_") { "mcp" } else { "hook" },
459 "count": stats.count,
460 "input_tokens": stats.input_tokens,
461 "output_tokens": stats.output_tokens,
462 "tokens_saved": tokens_saved,
463 })
464 })
465 .collect()
466}
467
468fn complexity_to_float(s: &str) -> f64 {
469 match s.to_lowercase().as_str() {
470 "trivial" => 0.1,
471 "simple" => 0.3,
472 "moderate" => 0.5,
473 "complex" => 0.7,
474 "architectural" => 0.9,
475 other => other.parse::<f64>().unwrap_or(0.5),
476 }
477}
478
479pub fn collect_cep_entries(store: &crate::core::stats::StatsStore) -> Vec<serde_json::Value> {
480 store
481 .cep
482 .scores
483 .iter()
484 .map(|s| {
485 serde_json::json!({
486 "recorded_at": s.timestamp,
487 "score": s.score as f64 / 100.0,
488 "cache_hit_rate": s.cache_hit_rate as f64 / 100.0,
489 "mode_diversity": s.mode_diversity as f64 / 100.0,
490 "compression_rate": s.compression_rate as f64 / 100.0,
491 "tool_calls": s.tool_calls,
492 "tokens_saved": s.tokens_saved,
493 "complexity": complexity_to_float(&s.complexity),
494 })
495 })
496 .collect()
497}
498
499pub fn collect_gotcha_entries() -> Vec<serde_json::Value> {
500 let mut all_gotchas = crate::core::gotcha_tracker::load_universal_gotchas();
501
502 if let Ok(knowledge_dir) = crate::core::paths::data_dir().map(|d| d.join("knowledge"))
503 && let Ok(entries) = std::fs::read_dir(&knowledge_dir)
504 {
505 for entry in entries.flatten() {
506 let gotcha_path = entry.path().join("gotchas.json");
507 if gotcha_path.exists()
508 && let Ok(content) = std::fs::read_to_string(&gotcha_path)
509 && let Ok(store) =
510 serde_json::from_str::<crate::core::gotcha_tracker::GotchaStore>(&content)
511 {
512 for g in store.gotchas {
513 if !all_gotchas
514 .iter()
515 .any(|existing| existing.trigger == g.trigger)
516 {
517 all_gotchas.push(g);
518 }
519 }
520 }
521 }
522 }
523
524 all_gotchas
525 .iter()
526 .map(|g| {
527 serde_json::json!({
528 "pattern": g.trigger,
529 "fix": g.resolution,
530 "severity": format!("{:?}", g.severity).to_lowercase(),
531 "category": format!("{:?}", g.category).to_lowercase(),
532 "occurrences": g.occurrences,
533 "prevented_count": g.prevented_count,
534 "confidence": g.confidence,
535 })
536 })
537 .collect()
538}
539
540pub fn collect_feedback_entries() -> Vec<serde_json::Value> {
541 let store = crate::core::feedback::FeedbackStore::load();
542 store
543 .learned_thresholds
544 .iter()
545 .map(|(lang, thresholds)| {
546 serde_json::json!({
547 "language": lang,
548 "entropy": thresholds.entropy,
549 "jaccard": thresholds.jaccard,
550 "sample_count": thresholds.sample_count,
551 "avg_efficiency": thresholds.avg_efficiency,
552 })
553 })
554 .collect()
555}
556
557pub fn collect_contribute_entries() -> Vec<serde_json::Value> {
558 let mut entries = Vec::new();
559
560 if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
561 let mode_stats_path = data_dir.join("mode_stats.json");
562 if let Ok(data) = std::fs::read_to_string(&mode_stats_path)
563 && let Ok(predictor) = serde_json::from_str::<serde_json::Value>(&data)
564 && let Some(history) = predictor["history"].as_object()
565 {
566 for (_key, outcomes) in history {
567 if let Some(arr) = outcomes.as_array() {
568 for outcome in arr.iter().rev().take(3) {
569 let ext = outcome["ext"].as_str().unwrap_or("unknown");
570 let mode = outcome["mode"].as_str().unwrap_or("full");
571 let t_in = outcome["tokens_in"].as_u64().unwrap_or(0);
572 let t_out = outcome["tokens_out"].as_u64().unwrap_or(0);
573 let ratio = if t_in > 0 {
574 1.0 - t_out as f64 / t_in as f64
575 } else {
576 0.0
577 };
578 let bucket = match t_in {
579 0..=500 => "0-500",
580 501..=2000 => "500-2k",
581 2001..=10000 => "2k-10k",
582 _ => "10k+",
583 };
584 entries.push(serde_json::json!({
585 "file_ext": format!(".{ext}"),
586 "size_bucket": bucket,
587 "best_mode": mode,
588 "compression_ratio": (ratio * 100.0).round() / 100.0,
589 }));
590 if entries.len() >= 200 {
591 return entries;
592 }
593 }
594 }
595 }
596 }
597 }
598
599 if entries.is_empty() {
600 let stats_data = crate::core::stats::format_gain_json();
601 if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&stats_data) {
602 let original = parsed["cep"]["total_tokens_original"].as_u64().unwrap_or(0);
603 let compressed = parsed["cep"]["total_tokens_compressed"]
604 .as_u64()
605 .unwrap_or(0);
606 let ratio = if original > 0 {
607 1.0 - compressed as f64 / original as f64
608 } else {
609 0.0
610 };
611 if let Some(modes) = parsed["cep"]["modes"].as_object() {
612 let read_modes = [
613 "full",
614 "map",
615 "signatures",
616 "auto",
617 "aggressive",
618 "entropy",
619 "diff",
620 "lines",
621 "task",
622 "reference",
623 ];
624 for (mode, count) in modes {
625 if !read_modes.contains(&mode.as_str()) || count.as_u64().unwrap_or(0) == 0 {
626 continue;
627 }
628 entries.push(serde_json::json!({
629 "file_ext": "mixed",
630 "size_bucket": "mixed",
631 "best_mode": mode,
632 "compression_ratio": (ratio * 100.0).round() / 100.0,
633 }));
634 }
635 }
636 }
637 }
638
639 entries
640}
641
642#[cfg(test)]
643mod tests {
644 use super::*;
645
646 #[test]
647 fn auto_sync_requires_flag_login_and_unused_slot() {
648 assert!(!should_auto_sync(false, true, None, "2026-06-10"));
650 assert!(!should_auto_sync(true, false, None, "2026-06-10"));
652 assert!(should_auto_sync(true, true, None, "2026-06-10"));
654 assert!(!should_auto_sync(
656 true,
657 true,
658 Some("2026-06-10"),
659 "2026-06-10"
660 ));
661 assert!(should_auto_sync(
663 true,
664 true,
665 Some("2026-06-09"),
666 "2026-06-10"
667 ));
668 }
669
670 #[test]
671 fn auto_index_push_needs_flag_login_index_and_fresh_slot() {
672 let t = "2026-06-10";
673 assert!(should_auto_push_index(true, true, true, None, t));
675 assert!(!should_auto_push_index(false, true, true, None, t));
677 assert!(!should_auto_push_index(true, false, true, None, t));
679 assert!(!should_auto_push_index(true, true, false, None, t));
680 assert!(!should_auto_push_index(true, true, true, Some(t), t));
682 assert!(should_auto_push_index(
683 true,
684 true,
685 true,
686 Some("2026-06-09"),
687 t
688 ));
689 }
690
691 #[test]
692 fn outcome_classification_is_auth_then_gate_then_network_then_synced() {
693 assert_eq!(classify_outcomes(&[]), AutoSyncOutcome::Synced);
695 assert_eq!(
698 classify_outcomes(&[
699 Err("Push failed: http status: 401".into()),
700 Err("HTTP 402: upgrade required".into()),
701 Err("connection refused".into()),
702 ]),
703 AutoSyncOutcome::Unauthenticated
704 );
705 assert_eq!(
708 classify_outcomes(&[Ok(()), Err("Push failed: http status: 401".into())]),
709 AutoSyncOutcome::Unauthenticated
710 );
711 assert_eq!(
713 classify_outcomes(&[
714 Err("HTTP 402: upgrade required".into()),
715 Err("connection refused".into()),
716 ]),
717 AutoSyncOutcome::Gated
718 );
719 assert_eq!(
721 classify_outcomes(&[Err("connection refused".into()), Err("timeout".into()),]),
722 AutoSyncOutcome::NetworkFailure
723 );
724 assert_eq!(
726 classify_outcomes(&[Ok(()), Err("timeout".into())]),
727 AutoSyncOutcome::Synced
728 );
729 }
730
731 #[test]
732 fn only_a_network_failure_leaves_the_daily_slot_open() {
733 assert!(consumes_daily_slot(AutoSyncOutcome::Unauthenticated));
737 assert!(consumes_daily_slot(AutoSyncOutcome::Gated));
738 assert!(consumes_daily_slot(AutoSyncOutcome::Synced));
739 assert!(!consumes_daily_slot(AutoSyncOutcome::NetworkFailure));
740 }
741}