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