Skip to main content

lean_ctx/
cloud_sync.rs

1use crate::core::config::Config;
2
3/// Outcome of one background Personal-Cloud auto-push (GL #384).
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum AutoSyncOutcome {
6    /// At least one surface pushed (or there was nothing to push).
7    Synced,
8    /// The server gated sync behind Pro (HTTP 402) — stop for today.
9    Gated,
10    /// The server rejected our credential (HTTP 401) — the key this machine
11    /// holds is gone. Retrying cannot fix it, so this is the one outcome that
12    /// must be *said out loud*: the user has to log in again.
13    Unauthenticated,
14    /// Every push failed without a 402 or 401 (offline / server down) — try
15    /// again at the next opportunity, do not consume today's slot.
16    NetworkFailure,
17}
18
19/// Whether the auto-sync should run now: opt-in flag, logged in, and not
20/// already synced today (the debounce). Pure for unit testing.
21#[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/// Whether the background index push should run for this project (GL #392):
32/// separate opt-in, logged in, a local index actually exists, and this
33/// project hasn't pushed today. Pure for unit testing.
34#[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/// Whether an outcome should consume today's auto-sync slot. Only a network
46/// failure leaves it open — a Pro gate or a dead credential will not resolve
47/// by retrying in ten minutes, and each is announced once per process.
48#[must_use]
49pub fn consumes_daily_slot(outcome: AutoSyncOutcome) -> bool {
50    outcome != AutoSyncOutcome::NetworkFailure
51}
52
53/// Classify per-surface push results into one [`AutoSyncOutcome`]. A 401
54/// anywhere wins — a revoked credential makes every other signal moot and is
55/// the only failure the user must act on. Then a 402 (the account is gated);
56/// otherwise total failure means the network is down; anything else counts as
57/// synced.
58#[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
78/// The only state `cloud_background_tasks` persists: the per-surface "last
79/// done" stamps produced during this run.
80///
81/// Collected while the network work happens **outside** any lock, then applied
82/// to a freshly loaded config inside one short locked closure. Keeping this a
83/// delta instead of a mutated full `Config` is what stops the background task
84/// from writing back a snapshot taken before the network I/O and thereby
85/// reverting a telemetry preference the user changed in the meantime
86/// (LR-TEL-01).
87#[derive(Debug, Default, Clone)]
88pub(crate) struct CloudBackgroundDelta {
89    pub(crate) last_heartbeat: Option<String>,
90    pub(crate) last_sync: Option<String>,
91    pub(crate) last_gain_sync: Option<String>,
92    pub(crate) last_model_pull: Option<String>,
93    pub(crate) last_auto_sync: Option<String>,
94    pub(crate) last_index_push: Vec<(String, String)>,
95}
96
97impl CloudBackgroundDelta {
98    /// Nothing was produced this run, so skip the write — and the lock — entirely.
99    pub(crate) fn is_empty(&self) -> bool {
100        self.last_heartbeat.is_none()
101            && self.last_sync.is_none()
102            && self.last_gain_sync.is_none()
103            && self.last_model_pull.is_none()
104            && self.last_auto_sync.is_none()
105            && self.last_index_push.is_empty()
106    }
107
108    /// Applies only the stamps this run produced. Every other field of `config`
109    /// — notably the whole `telemetry` preference triple — is left exactly as it
110    /// was loaded from disk, so a concurrent opt-out survives.
111    pub(crate) fn apply(&self, config: &mut Config) {
112        // Pure field assignment: this runs while the config write lock is held.
113        if let Some(bucket) = &self.last_heartbeat {
114            config.telemetry.last_heartbeat = Some(bucket.clone());
115        }
116        if let Some(day) = &self.last_sync {
117            config.cloud.last_sync = Some(day.clone());
118        }
119        if let Some(day) = &self.last_gain_sync {
120            config.cloud.last_gain_sync = Some(day.clone());
121        }
122        if let Some(day) = &self.last_model_pull {
123            config.cloud.last_model_pull = Some(day.clone());
124        }
125        if let Some(day) = &self.last_auto_sync {
126            config.cloud.last_auto_sync = Some(day.clone());
127        }
128        for (project_hash, day) in &self.last_index_push {
129            config
130                .cloud
131                .last_index_push
132                .insert(project_hash.clone(), day.clone());
133        }
134    }
135}
136
137/// Network budget for the send that runs as the MCP server exits.
138pub const EXIT_TELEMETRY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(3);
139const BACKGROUND_TELEMETRY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
140
141/// Whether this process may collect and send telemetry right now. Fails closed:
142/// an unreadable config never counts as consent.
143fn telemetry_send_eligible() -> bool {
144    let Ok(config) = Config::try_load_global() else {
145        return false;
146    };
147    let do_not_track = crate::core::host_env::var("DO_NOT_TRACK");
148    let telemetry_override = crate::core::host_env::var("LEAN_CTX_TELEMETRY");
149    config
150        .telemetry
151        .send_eligible(do_not_track.as_deref(), telemetry_override.as_deref())
152}
153
154/// Send the cumulative telemetry totals if the aggregate admits a send now.
155/// Returns the acknowledged bucket. Admission (daily cap, spacing, "nothing
156/// new") is decided under the aggregate lock, so callers may call freely.
157pub fn send_telemetry(trigger: crate::core::telemetry_aggregate::SendTrigger) -> Option<String> {
158    if !telemetry_send_eligible() {
159        return None;
160    }
161    // Persist first so the counters survive even when no send is admitted.
162    if let Err(error) = crate::core::telemetry_aggregate::persist_process_counters() {
163        tracing::debug!("telemetry counters not persisted: {error}");
164    }
165    let lease = match crate::core::telemetry_aggregate::begin_send(trigger) {
166        Ok(lease) => lease,
167        Err(reason) => {
168            tracing::debug!("telemetry send skipped: {reason}");
169            return None;
170        }
171    };
172    let batch = lease.batch().clone();
173    let timeout = match trigger {
174        crate::core::telemetry_aggregate::SendTrigger::Exit => EXIT_TELEMETRY_TIMEOUT,
175        crate::core::telemetry_aggregate::SendTrigger::Periodic => BACKGROUND_TELEMETRY_TIMEOUT,
176    };
177    if let Err(error) = crate::cloud_client::telemetry_v2_batch_with_timeout(&batch, timeout) {
178        tracing::debug!("telemetry send failed, batch kept for retry: {error}");
179        return None;
180    }
181    let installation_id = batch.events.first()?.installation_id.clone();
182    let payload = serde_json::to_vec(&batch).ok()?;
183    use sha2::Digest;
184    let record = crate::core::telemetry_ledger::HeartbeatRecord {
185        timestamp: chrono::Utc::now().to_rfc3339(),
186        installation_id,
187        version: env!("CARGO_PKG_VERSION").to_string(),
188        os: std::env::consts::OS.to_string(),
189        arch: std::env::consts::ARCH.to_string(),
190        schema_version: batch.schema_version,
191        event_names: batch
192            .events
193            .iter()
194            .map(|event| event.event.name().to_string())
195            .collect(),
196        payload_hash: hex::encode(sha2::Sha256::digest(payload)),
197        endpoint: telemetry_ledger_endpoint(),
198        status: "success".to_string(),
199    };
200    // Without a ledger entry the send stays pending and is retried with the
201    // same bytes; the server replaces per-day rows, so that is harmless.
202    if let Err(error) = crate::core::telemetry_ledger::append(&record) {
203        tracing::debug!("telemetry ledger append failed: {error}");
204        return None;
205    }
206    if let Err(error) = lease.commit() {
207        tracing::debug!("telemetry acknowledgement failed: {error}");
208        return None;
209    }
210    batch
211        .events
212        .first()
213        .map(|event| event.timestamp_bucket.clone())
214}
215
216/// How often the daemon offers the day's totals. The aggregate's admission
217/// (daily cap, growing spacing, "nothing new") decides whether a send happens.
218const DAEMON_TELEMETRY_INTERVAL: std::time::Duration = std::time::Duration::from_hours(1);
219/// Delay before the daemon's first offer so its startup stays light.
220const DAEMON_TELEMETRY_INITIAL_DELAY: std::time::Duration = std::time::Duration::from_mins(2);
221
222/// Spawn the daemon's telemetry loop (must run inside a Tokio runtime).
223///
224/// Without it, sends happen only inside an MCP server (tool-call ticks and
225/// exit), so installs that use lean-ctx through hooks, the CLI or the proxy
226/// were never counted. The daemon is the one long-lived process setup starts;
227/// it also forwards the counters other processes persisted. Eligibility is
228/// re-checked on every tick, so an opt-out takes effect without a restart.
229pub(crate) fn spawn_daemon_telemetry() {
230    tokio::spawn(async {
231        tokio::time::sleep(DAEMON_TELEMETRY_INITIAL_DELAY).await;
232        loop {
233            let _ = tokio::task::spawn_blocking(daemon_telemetry_tick).await;
234            tokio::time::sleep(DAEMON_TELEMETRY_INTERVAL).await;
235        }
236    });
237}
238
239fn daemon_telemetry_tick() {
240    if !telemetry_send_eligible() {
241        return;
242    }
243    if let Err(error) = crate::core::telemetry_aggregate::record_current_version() {
244        tracing::debug!("telemetry version aggregate unavailable: {error}");
245    }
246    send_telemetry(crate::core::telemetry_aggregate::SendTrigger::Periodic);
247}
248
249pub fn cloud_background_tasks() {
250    // Decision snapshot only. Read global-only so the daily background save
251    // never leaks a project-local override into the global config (#443), and
252    // never written back: the persist below re-loads under the lock and applies
253    // `delta` instead (LR-TEL-01). This also keeps edits made while the pass is
254    // busy on the network (#1934).
255    let config = Config::load_global();
256    let mut delta = CloudBackgroundDelta::default();
257    let today = chrono::Local::now().format("%Y-%m-%d").to_string();
258
259    let already_synced = config
260        .cloud
261        .last_sync
262        .as_deref()
263        .is_some_and(|d| d == today);
264    let already_gain_synced = config
265        .cloud
266        .last_gain_sync
267        .as_deref()
268        .is_some_and(|d| d == today);
269    let already_pulled = config
270        .cloud
271        .last_model_pull
272        .as_deref()
273        .is_some_and(|d| d == today);
274
275    // Anonymous usage telemetry: cumulative daily totals, resent as they grow.
276    // The acknowledged bucket goes into `delta`, never into this snapshot, so
277    // a concurrent opt-out is not reverted by the persist below (LR-TEL-01).
278    if telemetry_send_eligible() {
279        if let Err(error) = crate::core::telemetry_aggregate::record_current_version() {
280            tracing::debug!("telemetry version aggregate unavailable: {error}");
281        }
282        if let Some(bucket) =
283            send_telemetry(crate::core::telemetry_aggregate::SendTrigger::Periodic)
284        {
285            delta.last_heartbeat = Some(bucket);
286        }
287    }
288
289    if crate::cloud_client::is_logged_in() {
290        if config.cloud.sync_stats_enabled && !already_synced {
291            let store = crate::core::stats::load();
292            let entries = build_sync_entries(&store);
293            if !entries.is_empty() {
294                let result = crate::cloud_client::sync_stats(&entries);
295                record_sync_telemetry(&result);
296                if result.is_ok() {
297                    delta.last_sync = Some(today.clone());
298                }
299            }
300        }
301
302        if config.cloud.sync_gain_enabled && !already_gain_synced {
303            let engine = crate::core::gain::GainEngine::load();
304            let summary = engine.summary(None);
305            let trend = match summary.score.trend {
306                crate::core::gain::gain_score::Trend::Rising => "rising",
307                crate::core::gain::gain_score::Trend::Stable => "stable",
308                crate::core::gain::gain_score::Trend::Declining => "declining",
309            };
310            let entry = serde_json::json!({
311                "recorded_at": format!("{today}T00:00:00Z"),
312                "total": summary.score.total as f64,
313                "compression": summary.score.compression as f64,
314                "cost_efficiency": summary.score.cost_efficiency as f64,
315                "quality": summary.score.quality as f64,
316                "consistency": summary.score.consistency as f64,
317                "navigability": summary.score.navigability as f64,
318                "trend": trend,
319                "avoided_usd": summary.avoided_usd,
320                "tool_spend_usd": summary.tool_spend_usd,
321                "model_key": summary.model.model_key,
322            });
323            let result = crate::cloud_client::push_gain(&[entry]);
324            record_sync_telemetry(&result);
325            if result.is_ok() {
326                delta.last_gain_sync = Some(today.clone());
327            }
328        }
329
330        if config.cloud.sync_models_enabled && !already_pulled {
331            let result = crate::cloud_client::pull_cloud_models().and_then(|data| {
332                crate::cloud_client::save_cloud_models(&data).map_err(|error| error.to_string())
333            });
334            record_sync_telemetry(&result);
335            if result.is_ok() {
336                delta.last_model_pull = Some(today.clone());
337            }
338        }
339
340        // Opt-in Personal-Cloud auto-push (GL #384): silent, once per day,
341        // offline-tolerant. A network failure leaves the slot open so the
342        // next background cycle retries; a Pro gate consumes it (one quiet
343        // attempt per day on a Community account, never error spam).
344        if should_auto_sync(
345            config.cloud.auto_sync,
346            true,
347            config.cloud.last_auto_sync.as_deref(),
348            &today,
349        ) && consumes_daily_slot(auto_sync_personal_cloud())
350        {
351            delta.last_auto_sync = Some(today.clone());
352        }
353
354        // Opt-in hosted-index auto-push (GL #392): once per project per day,
355        // only when a local index exists. Quota/Pro rejections consume the
356        // slot (one quiet attempt per day); network failures leave it open.
357        if let Ok(root) = std::env::current_dir() {
358            let project_hash = crate::core::index_namespace::namespace_hash(&root);
359            if should_auto_push_index(
360                config.cloud.auto_index,
361                true,
362                crate::core::index_bundle::local_index_present(&root),
363                config
364                    .cloud
365                    .last_index_push
366                    .get(&project_hash)
367                    .map(String::as_str),
368                &today,
369            ) {
370                let result = crate::cloud_client::push_index_bundle(&root);
371                record_sync_telemetry(&result);
372                match result {
373                    Ok((hash, bytes)) => {
374                        tracing::debug!(project = %hash, bytes, "auto-index: pushed");
375                        delta.last_index_push.push((project_hash, today.clone()));
376                    }
377                    Err(e) if e.contains("Pro") || e.contains("Quota") => {
378                        tracing::debug!(error = %e, "auto-index: gated, retry tomorrow");
379                        delta.last_index_push.push((project_hash, today.clone()));
380                    }
381                    Err(e) => {
382                        tracing::debug!(error = %e, "auto-index: push failed, slot stays open");
383                    }
384                }
385            }
386        }
387    }
388
389    if let Err(e) = persist_background_delta(&delta) {
390        tracing::warn!("could not persist cloud background state: {e}");
391    }
392}
393
394/// Persist step of [`cloud_background_tasks`]: resolves the global config path
395/// and delegates to [`persist_background_delta_at`].
396fn persist_background_delta(
397    delta: &CloudBackgroundDelta,
398) -> Result<(), crate::core::error::LeanCtxError> {
399    let path = Config::path().ok_or_else(|| {
400        crate::core::error::LeanCtxError::Config("cannot determine home directory".to_string())
401    })?;
402    persist_background_delta_at(&path, delta)
403}
404
405/// Path-parameterized core of the persist step — the production code path,
406/// shared with its regression test.
407///
408/// Re-loads the config from disk under the write lock and applies only the
409/// stamps this run produced, so a telemetry choice committed during the network
410/// work above is the base we mutate rather than something we overwrite. All
411/// network work has already finished; nothing here does I/O beyond the guarded
412/// config write.
413pub(crate) fn persist_background_delta_at(
414    path: &std::path::Path,
415    delta: &CloudBackgroundDelta,
416) -> Result<(), crate::core::error::LeanCtxError> {
417    if delta.is_empty() {
418        return Ok(());
419    }
420    Config::update_global_at(path, |on_disk| delta.apply(on_disk)).map(|_| ())
421}
422
423fn telemetry_ledger_endpoint() -> String {
424    let raw =
425        std::env::var("LEAN_CTX_API_URL").unwrap_or_else(|_| "https://api.leanctx.com".to_string());
426    sanitized_telemetry_endpoint(&raw)
427}
428
429fn sanitized_telemetry_endpoint(raw: &str) -> String {
430    let Ok(mut url) = reqwest::Url::parse(raw) else {
431        return "https://api.leanctx.com/api/telemetry/v2/batch".to_string();
432    };
433    if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
434        return "https://api.leanctx.com/api/telemetry/v2/batch".to_string();
435    }
436    let _ = url.set_username("");
437    let _ = url.set_password(None);
438    url.set_query(None);
439    url.set_fragment(None);
440    url.set_path("/api/telemetry/v2/batch");
441    url.to_string()
442}
443
444/// Push every Personal-Cloud surface silently (background variant of
445/// `lean-ctx sync`'s interactive flow — tracing instead of stdout).
446fn auto_sync_personal_cloud() -> AutoSyncOutcome {
447    let store = crate::core::stats::load();
448    let mut results: Vec<Result<(), String>> = Vec::new();
449
450    let mut push = |label: &str, result: Result<String, String>| {
451        record_sync_telemetry(&result);
452        match result {
453            Ok(_) => {
454                tracing::debug!(surface = label, "auto-sync: pushed");
455                results.push(Ok(()));
456            }
457            Err(e) => {
458                tracing::debug!(surface = label, error = %e, "auto-sync: push failed");
459                results.push(Err(e));
460            }
461        }
462    };
463
464    let commands = collect_command_entries(&store);
465    if !commands.is_empty() {
466        push("commands", crate::cloud_client::push_commands(&commands));
467    }
468    let cep = collect_cep_entries(&store);
469    if !cep.is_empty() {
470        push("cep", crate::cloud_client::push_cep(&cep));
471    }
472    let knowledge = collect_knowledge_entries();
473    if !knowledge.is_empty() {
474        push("knowledge", crate::cloud_client::push_knowledge(&knowledge));
475    }
476    let gotchas = collect_gotcha_entries();
477    if !gotchas.is_empty() {
478        push("gotchas", crate::cloud_client::push_gotchas(&gotchas));
479    }
480    let feedback = collect_feedback_entries();
481    if !feedback.is_empty() {
482        push("feedback", crate::cloud_client::push_feedback(&feedback));
483    }
484
485    let outcome = classify_outcomes(&results);
486    tracing::info!(
487        ?outcome,
488        surfaces = results.len(),
489        "personal-cloud auto-sync done"
490    );
491
492    static GATE_WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
493    if outcome == AutoSyncOutcome::Gated
494        && !GATE_WARNED.swap(true, std::sync::atomic::Ordering::Relaxed)
495    {
496        eprintln!(
497            "\n  \x1b[33m⚠\x1b[0m  Personal Cloud sync requires Pro. \
498             Your local data is safe.\n  \
499             Unlock: lean-ctx cloud upgrade --plan pro ($9/mo)\n"
500        );
501    }
502
503    // A dead credential used to look exactly like being offline: silent, and
504    // retried forever. Say it once, and say what fixes it.
505    static AUTH_WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
506    if outcome == AutoSyncOutcome::Unauthenticated
507        && !AUTH_WARNED.swap(true, std::sync::atomic::Ordering::Relaxed)
508    {
509        eprintln!(
510            "\n  \x1b[33m⚠\x1b[0m  Personal Cloud sync is signed out on this machine \
511             — the server rejected this device's key.\n  \
512             Your local data is safe, and nothing on the server was lost.\n  \
513             Sign in again to resume syncing: lean-ctx login\n"
514        );
515    }
516
517    outcome
518}
519
520fn record_sync_telemetry<T>(result: &Result<T, String>) {
521    if let Err(error) = crate::core::telemetry_aggregate::record_sync_result(result.is_ok()) {
522        tracing::debug!("telemetry sync aggregate unavailable: {error}");
523    }
524}
525
526pub fn build_sync_entries(store: &crate::core::stats::StatsStore) -> Vec<serde_json::Value> {
527    let mut entries = Vec::new();
528    let cep = &store.cep;
529    let today = chrono::Local::now().format("%Y-%m-%d").to_string();
530
531    let mut cep_cache_by_day: std::collections::HashMap<String, (u64, u64)> =
532        std::collections::HashMap::new();
533    for s in &cep.scores {
534        if let Some(date) = s.timestamp.get(..10) {
535            let entry = cep_cache_by_day.entry(date.to_string()).or_default();
536            let calls = s.tool_calls.max(1);
537            let hits = (calls as f64 * s.cache_hit_rate as f64 / 100.0).round() as u64;
538            entry.0 += calls;
539            entry.1 += hits;
540        }
541    }
542
543    let mut mcp_saved_total = 0u64;
544    for (cmd, s) in &store.commands {
545        if cmd.starts_with("ctx_") {
546            mcp_saved_total += s.input_tokens.saturating_sub(s.output_tokens);
547        }
548    }
549    let global_saved = store
550        .total_input_tokens
551        .saturating_sub(store.total_output_tokens)
552        .max(1);
553    let mcp_ratio = mcp_saved_total as f64 / global_saved as f64;
554
555    for day in &store.daily {
556        let tokens_original = day.input_tokens;
557        let tokens_compressed = day.output_tokens;
558        let tokens_saved = tokens_original.saturating_sub(tokens_compressed);
559        let (day_calls, day_hits) = cep_cache_by_day.get(&day.date).copied().unwrap_or((0, 0));
560        let day_mcp_saved = (tokens_saved as f64 * mcp_ratio).round() as u64;
561        let day_hook_saved = tokens_saved.saturating_sub(day_mcp_saved);
562        entries.push(serde_json::json!({
563            "date": day.date,
564            "tokens_original": tokens_original,
565            "tokens_compressed": tokens_compressed,
566            "tokens_saved": tokens_saved,
567            "mcp_tokens_saved": day_mcp_saved,
568            "hook_tokens_saved": day_hook_saved,
569            "tool_calls": day.commands,
570            "cache_hits": day_hits,
571            "cache_misses": day_calls.saturating_sub(day_hits),
572        }));
573    }
574
575    let has_today = entries.iter().any(|e| e["date"].as_str() == Some(&today));
576    if !has_today && (cep.total_tokens_original > 0 || store.total_commands > 0) {
577        let today_saved = cep
578            .total_tokens_original
579            .saturating_sub(cep.total_tokens_compressed);
580        let today_mcp = (today_saved as f64 * mcp_ratio).round() as u64;
581        entries.push(serde_json::json!({
582            "date": today,
583            "tokens_original": cep.total_tokens_original,
584            "tokens_compressed": cep.total_tokens_compressed,
585            "tokens_saved": today_saved,
586            "mcp_tokens_saved": today_mcp,
587            "hook_tokens_saved": today_saved.saturating_sub(today_mcp),
588            "tool_calls": store.total_commands,
589            "cache_hits": cep.total_cache_hits,
590            "cache_misses": cep.total_cache_reads.saturating_sub(cep.total_cache_hits),
591        }));
592    }
593
594    entries
595}
596
597// ── Personal-Cloud surface collectors ────────────────────────────────────────
598// Shared by the interactive `lean-ctx sync` flow and the background auto-sync
599// (GL #384): pure local reads, no network, no stdout.
600
601pub fn collect_knowledge_entries() -> Vec<serde_json::Value> {
602    let Ok(data_dir) = crate::core::paths::data_dir() else {
603        return Vec::new();
604    };
605    let knowledge_dir = data_dir.join("knowledge");
606    if !knowledge_dir.is_dir() {
607        return Vec::new();
608    }
609
610    let mut entries = Vec::new();
611
612    for project_entry in std::fs::read_dir(&knowledge_dir).into_iter().flatten() {
613        let Ok(project_entry) = project_entry else {
614            continue;
615        };
616        let project_path = project_entry.path();
617        if !project_path.is_dir() {
618            continue;
619        }
620
621        for file_entry in std::fs::read_dir(&project_path).into_iter().flatten() {
622            let Ok(file_entry) = file_entry else { continue };
623            let file_path = file_entry.path();
624            if file_path.extension().and_then(|e| e.to_str()) != Some("json") {
625                continue;
626            }
627            let Ok(data) = std::fs::read_to_string(&file_path) else {
628                continue;
629            };
630            let parsed: serde_json::Value = match serde_json::from_str(&data) {
631                Ok(v) => v,
632                Err(_) => continue,
633            };
634
635            if let Some(facts) = parsed["facts"].as_array() {
636                for fact in facts {
637                    let cat = fact["category"].as_str().unwrap_or("general");
638                    let key = fact["key"].as_str().unwrap_or("");
639                    let val = fact["value"]
640                        .as_str()
641                        .or_else(|| fact["description"].as_str())
642                        .unwrap_or("");
643                    if !key.is_empty() {
644                        entries.push(serde_json::json!({
645                            "category": cat,
646                            "key": key,
647                            "value": val,
648                        }));
649                    }
650                }
651            }
652
653            if let Some(gotchas) = parsed["gotchas"].as_array() {
654                for g in gotchas {
655                    let pattern = g["pattern"].as_str().unwrap_or("");
656                    let fix = g["fix"].as_str().unwrap_or("");
657                    if !pattern.is_empty() {
658                        entries.push(serde_json::json!({
659                            "category": "gotcha",
660                            "key": pattern,
661                            "value": fix,
662                        }));
663                    }
664                }
665            }
666        }
667    }
668
669    entries
670}
671
672pub fn collect_command_entries(store: &crate::core::stats::StatsStore) -> Vec<serde_json::Value> {
673    store
674        .commands
675        .iter()
676        .map(|(name, stats)| {
677            let tokens_saved = stats.input_tokens.saturating_sub(stats.output_tokens);
678            serde_json::json!({
679                "command": name,
680                "source": if name.starts_with("ctx_") { "mcp" } else { "hook" },
681                "count": stats.count,
682                "input_tokens": stats.input_tokens,
683                "output_tokens": stats.output_tokens,
684                "tokens_saved": tokens_saved,
685            })
686        })
687        .collect()
688}
689
690fn complexity_to_float(s: &str) -> f64 {
691    match s.to_lowercase().as_str() {
692        "trivial" => 0.1,
693        "simple" => 0.3,
694        "moderate" => 0.5,
695        "complex" => 0.7,
696        "architectural" => 0.9,
697        other => other.parse::<f64>().unwrap_or(0.5),
698    }
699}
700
701pub fn collect_cep_entries(store: &crate::core::stats::StatsStore) -> Vec<serde_json::Value> {
702    store
703        .cep
704        .scores
705        .iter()
706        .map(|s| {
707            serde_json::json!({
708                "recorded_at": s.timestamp,
709                "score": s.score as f64 / 100.0,
710                "cache_hit_rate": s.cache_hit_rate as f64 / 100.0,
711                "mode_diversity": s.mode_diversity as f64 / 100.0,
712                "compression_rate": s.compression_rate as f64 / 100.0,
713                "tool_calls": s.tool_calls,
714                "tokens_saved": s.tokens_saved,
715                "complexity": complexity_to_float(&s.complexity),
716            })
717        })
718        .collect()
719}
720
721pub fn collect_gotcha_entries() -> Vec<serde_json::Value> {
722    let mut all_gotchas = crate::core::gotcha_tracker::load_universal_gotchas();
723
724    if let Ok(knowledge_dir) = crate::core::paths::data_dir().map(|d| d.join("knowledge"))
725        && let Ok(entries) = std::fs::read_dir(&knowledge_dir)
726    {
727        for entry in entries.flatten() {
728            let gotcha_path = entry.path().join("gotchas.json");
729            if gotcha_path.exists()
730                && let Ok(content) = std::fs::read_to_string(&gotcha_path)
731                && let Ok(store) =
732                    serde_json::from_str::<crate::core::gotcha_tracker::GotchaStore>(&content)
733            {
734                for g in store.gotchas {
735                    if !all_gotchas
736                        .iter()
737                        .any(|existing| existing.trigger == g.trigger)
738                    {
739                        all_gotchas.push(g);
740                    }
741                }
742            }
743        }
744    }
745
746    all_gotchas
747        .iter()
748        .map(|g| {
749            serde_json::json!({
750                "pattern": g.trigger,
751                "fix": g.resolution,
752                "severity": format!("{:?}", g.severity).to_lowercase(),
753                "category": format!("{:?}", g.category).to_lowercase(),
754                "occurrences": g.occurrences,
755                "prevented_count": g.prevented_count,
756                "confidence": g.confidence,
757            })
758        })
759        .collect()
760}
761
762pub fn collect_feedback_entries() -> Vec<serde_json::Value> {
763    let store = crate::core::feedback::FeedbackStore::load();
764    store
765        .learned_thresholds
766        .iter()
767        .map(|(lang, thresholds)| {
768            serde_json::json!({
769                "language": lang,
770                "entropy": thresholds.entropy,
771                "jaccard": thresholds.jaccard,
772                "sample_count": thresholds.sample_count,
773                "avg_efficiency": thresholds.avg_efficiency,
774            })
775        })
776        .collect()
777}
778
779pub fn collect_contribute_entries() -> Vec<serde_json::Value> {
780    let mut entries = Vec::new();
781
782    if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
783        let mode_stats_path = data_dir.join("mode_stats.json");
784        if let Ok(data) = std::fs::read_to_string(&mode_stats_path)
785            && let Ok(predictor) = serde_json::from_str::<serde_json::Value>(&data)
786            && let Some(history) = predictor["history"].as_object()
787        {
788            for (_key, outcomes) in history {
789                if let Some(arr) = outcomes.as_array() {
790                    for outcome in arr.iter().rev().take(3) {
791                        let ext = outcome["ext"].as_str().unwrap_or("unknown");
792                        let mode = outcome["mode"].as_str().unwrap_or("full");
793                        let t_in = outcome["tokens_in"].as_u64().unwrap_or(0);
794                        let t_out = outcome["tokens_out"].as_u64().unwrap_or(0);
795                        let ratio = if t_in > 0 {
796                            1.0 - t_out as f64 / t_in as f64
797                        } else {
798                            0.0
799                        };
800                        let bucket = match t_in {
801                            0..=500 => "0-500",
802                            501..=2000 => "500-2k",
803                            2001..=10000 => "2k-10k",
804                            _ => "10k+",
805                        };
806                        entries.push(serde_json::json!({
807                            "file_ext": format!(".{ext}"),
808                            "size_bucket": bucket,
809                            "best_mode": mode,
810                            "compression_ratio": (ratio * 100.0).round() / 100.0,
811                        }));
812                        if entries.len() >= 200 {
813                            return entries;
814                        }
815                    }
816                }
817            }
818        }
819    }
820
821    if entries.is_empty() {
822        let stats_data = crate::core::stats::format_gain_json();
823        if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&stats_data) {
824            let original = parsed["cep"]["total_tokens_original"].as_u64().unwrap_or(0);
825            let compressed = parsed["cep"]["total_tokens_compressed"]
826                .as_u64()
827                .unwrap_or(0);
828            let ratio = if original > 0 {
829                1.0 - compressed as f64 / original as f64
830            } else {
831                0.0
832            };
833            if let Some(modes) = parsed["cep"]["modes"].as_object() {
834                let read_modes = [
835                    "full",
836                    "map",
837                    "signatures",
838                    "auto",
839                    "aggressive",
840                    "entropy",
841                    "diff",
842                    "lines",
843                    "task",
844                    "reference",
845                ];
846                for (mode, count) in modes {
847                    if !read_modes.contains(&mode.as_str()) || count.as_u64().unwrap_or(0) == 0 {
848                        continue;
849                    }
850                    entries.push(serde_json::json!({
851                        "file_ext": "mixed",
852                        "size_bucket": "mixed",
853                        "best_mode": mode,
854                        "compression_ratio": (ratio * 100.0).round() / 100.0,
855                    }));
856                }
857            }
858        }
859    }
860
861    entries
862}
863
864#[cfg(test)]
865mod tests {
866    use super::*;
867
868    /// #1934: the background pass must not revert config edits made while it
869    /// was busy on the network — it writes back only the stamps it set.
870    #[test]
871    fn background_pass_keeps_edits_made_while_it_ran() {
872        let _iso = crate::core::data_dir::isolated_data_dir();
873        let delta = CloudBackgroundDelta {
874            last_sync: Some("2026-09-30".into()),
875            ..CloudBackgroundDelta::default()
876        };
877
878        // Meanwhile the user turns a setting on.
879        Config::update_global(|c| c.proxy.ccr_inband = Some(true)).unwrap();
880        persist_background_delta(&delta).unwrap();
881
882        let on_disk = Config::load_global();
883        assert_eq!(on_disk.proxy.ccr_inband, Some(true), "the edit survived");
884        assert_eq!(on_disk.cloud.last_sync.as_deref(), Some("2026-09-30"));
885    }
886
887    #[test]
888    fn telemetry_ledger_endpoint_removes_credentials_query_and_fragment() {
889        assert_eq!(
890            sanitized_telemetry_endpoint("https://user:secret@example.test/base?token=x#private"),
891            "https://example.test/api/telemetry/v2/batch"
892        );
893        assert_eq!(
894            sanitized_telemetry_endpoint("file:///private/path"),
895            "https://api.leanctx.com/api/telemetry/v2/batch"
896        );
897    }
898
899    #[test]
900    fn auto_sync_requires_flag_login_and_unused_slot() {
901        // Disabled flag blocks everything else.
902        assert!(!should_auto_sync(false, true, None, "2026-06-10"));
903        // Logged out never syncs.
904        assert!(!should_auto_sync(true, false, None, "2026-06-10"));
905        // Fresh slot + flag + login → go.
906        assert!(should_auto_sync(true, true, None, "2026-06-10"));
907        // Already synced today → debounced.
908        assert!(!should_auto_sync(
909            true,
910            true,
911            Some("2026-06-10"),
912            "2026-06-10"
913        ));
914        // Synced yesterday → today's slot is free.
915        assert!(should_auto_sync(
916            true,
917            true,
918            Some("2026-06-09"),
919            "2026-06-10"
920        ));
921    }
922
923    #[test]
924    fn auto_index_push_needs_flag_login_index_and_fresh_slot() {
925        let t = "2026-06-10";
926        // All preconditions met → push.
927        assert!(should_auto_push_index(true, true, true, None, t));
928        // Separate opt-in: auto_sync users are NOT auto-enrolled.
929        assert!(!should_auto_push_index(false, true, true, None, t));
930        // Logged out / no local index → silently skip, no error path.
931        assert!(!should_auto_push_index(true, false, true, None, t));
932        assert!(!should_auto_push_index(true, true, false, None, t));
933        // Per-project debounce: today consumed, yesterday frees the slot.
934        assert!(!should_auto_push_index(true, true, true, Some(t), t));
935        assert!(should_auto_push_index(
936            true,
937            true,
938            true,
939            Some("2026-06-09"),
940            t
941        ));
942    }
943
944    #[test]
945    fn outcome_classification_is_auth_then_gate_then_network_then_synced() {
946        // Nothing to push counts as synced (slot consumed, no retry storm).
947        assert_eq!(classify_outcomes(&[]), AutoSyncOutcome::Synced);
948        // A 401 outranks everything: the credential is gone, so the gate and
949        // the network tell us nothing useful.
950        assert_eq!(
951            classify_outcomes(&[
952                Err("Push failed: http status: 401".into()),
953                Err("HTTP 402: upgrade required".into()),
954                Err("connection refused".into()),
955            ]),
956            AutoSyncOutcome::Unauthenticated
957        );
958        // A lone 401 among successes still has to surface — one revoked
959        // machine is exactly the case that used to stay silent.
960        assert_eq!(
961            classify_outcomes(&[Ok(()), Err("Push failed: http status: 401".into())]),
962            AutoSyncOutcome::Unauthenticated
963        );
964        // Any 402 means the account is gated, even with other failures.
965        assert_eq!(
966            classify_outcomes(&[
967                Err("HTTP 402: upgrade required".into()),
968                Err("connection refused".into()),
969            ]),
970            AutoSyncOutcome::Gated
971        );
972        // All failed without a 401 or 402 → offline, keep the slot open.
973        assert_eq!(
974            classify_outcomes(&[Err("connection refused".into()), Err("timeout".into()),]),
975            AutoSyncOutcome::NetworkFailure
976        );
977        // Partial success is success.
978        assert_eq!(
979            classify_outcomes(&[Ok(()), Err("timeout".into())]),
980            AutoSyncOutcome::Synced
981        );
982    }
983
984    #[test]
985    fn only_a_network_failure_leaves_the_daily_slot_open() {
986        // A dead credential consumes the slot: retrying cannot fix it, and the
987        // warning is printed once per process either way. Leaving the slot
988        // open here is what turned one revoked key into a silent daily retry.
989        assert!(consumes_daily_slot(AutoSyncOutcome::Unauthenticated));
990        assert!(consumes_daily_slot(AutoSyncOutcome::Gated));
991        assert!(consumes_daily_slot(AutoSyncOutcome::Synced));
992        assert!(!consumes_daily_slot(AutoSyncOutcome::NetworkFailure));
993    }
994
995    #[test]
996    #[serial_test::serial]
997    fn daemon_tick_honours_an_explicit_opt_out() {
998        let _iso = crate::core::data_dir::isolated_data_dir();
999        let config = Config::path().expect("config path");
1000        std::fs::create_dir_all(config.parent().expect("config dir")).expect("config dir");
1001        std::fs::write(&config, "[telemetry]\nenabled = false\n").expect("write opt-out");
1002        daemon_telemetry_tick();
1003        let state = crate::core::paths::state_dir().expect("state dir");
1004        assert!(!state.join("telemetry_v2_aggregate.json").exists());
1005        assert!(!state.join("telemetry_v2_one_shots.json").exists());
1006    }
1007
1008    #[test]
1009    #[serial_test::serial]
1010    fn daemon_tick_attempts_a_send_for_a_default_install() {
1011        // No config file: the default-on install the daemon exists to cover.
1012        // The test guard sends to a discard port, so the batch stays pending,
1013        // which proves the tick reached the send path.
1014        let _iso = crate::core::data_dir::isolated_data_dir();
1015        daemon_telemetry_tick();
1016        let state = crate::core::paths::state_dir().expect("state dir");
1017        assert!(state.join("telemetry_v2_aggregate.json").exists());
1018    }
1019}