lean-ctx-cloud 3.12.10

The LeanCTX connector: enrollment, bus, knowledge sync, tasks and policy on top of LeanCTX | OSS.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
// SPDX-License-Identifier: Apache-2.0
//! Background Cloud work, started once at MCP startup.
//!
//! The scheduler never runs inside a tool call and never blocks one: it is a
//! low-priority thread that renews the lease when due (and, with later
//! packages, drains the outbox and pulls knowledge). Offline or a lapsed
//! lease only pauses Cloud traffic; local tools are unaffected.

use std::sync::{Condvar, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};

use lean_ctx_time::UtcDateTime;

use super::CloudError;
use super::auth::Session;
use super::config::CloudConfig;
use super::state::CloudStore;
use lean_ctx_protocol::cloud::lease::LeaseState;

/// Time between passes: `[cloud] pull_interval_minutes` (SPEC-ENGINE ยง3.16).
fn tick_every(config: &CloudConfig) -> Duration {
    Duration::from_secs(u64::from(config.pull_interval()) * 60)
}

/// What one scheduler pass did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TickOutcome {
    Idle,
    Renewed,
    /// Nothing to do any more (not connected, disabled, lapsed): stop.
    Stop(String),
    /// A failure that may pass (Cloud offline, a lease renewal refused);
    /// try again next tick.
    Retry(String),
}

/// One pass at local time `now`. A pass that stops (disabled, not
/// connected, revoked, lapsed, โ€ฆ) also stops every local recording for
/// Cloud (K2 review 2, N1): nothing is collected while no pass runs.
pub fn tick(store: &CloudStore, config: &CloudConfig) -> TickOutcome {
    let outcome = tick_once(store, config);
    if matches!(outcome, TickOutcome::Stop(_)) {
        super::receipts::stop_local_recording(store.data_dir());
    }
    outcome
}

fn tick_once(store: &CloudStore, config: &CloudConfig) -> TickOutcome {
    if config.enabled == Some(false) {
        return TickOutcome::Stop("disabled by [cloud] enabled = false".into());
    }
    let Ok(Some(instance)) = store.instance() else {
        return TickOutcome::Stop("not connected".into());
    };
    // A disconnect Cloud has not confirmed yet: finish it, sync nothing.
    match super::disconnect::retry_pending(store, config, &instance) {
        None => {}
        Some(Ok(done)) => return TickOutcome::Stop(done),
        Some(Err(error)) if error.is_transient() => {
            return TickOutcome::Retry(format!("pending disconnect: {error}"));
        }
        Some(Err(error)) => {
            store.record_error(&format!("pending disconnect: {error}"));
            return TickOutcome::Stop(format!("pending disconnect: {error}"));
        }
    }
    // Upgrade duties of the first 3.12 start (local, once; ยง3.16).
    if let Err(error) = super::migrate::run(store, config) {
        store.record_error(&format!("upgrade: {error}"));
    }
    let session = super::root_cert::trust_root(store, config, &instance.url)
        .and_then(|root| Session::load(store.clone(), root));
    let mut session = match session {
        Ok(session) => session,
        Err(error) => {
            store.record_error(&error.to_string());
            return TickOutcome::Stop(error.to_string());
        }
    };
    let now = UtcDateTime::now();
    if session.lease.state_at(now) == LeaseState::Lapsed {
        store.record_error(&CloudError::LeaseLapsed.to_string());
        return TickOutcome::Stop(CloudError::LeaseLapsed.to_string());
    }
    let mut outcome = TickOutcome::Idle;
    if session.lease.renew_due(now) {
        match session.renew() {
            Ok(_) => {
                outcome = TickOutcome::Renewed;
                // A self-hosted Cloud' root certificate is refreshed with the lease.
                if let Ok(client) = session.client() {
                    super::root_cert::refresh(store, &client, &instance.url);
                }
            }
            // A revoked instance or a lapsed lease ends the scheduler. Any
            // other refusal (a key this engine does not hold yet, a damaged
            // answer, Cloud offline) is tried again next pass, one
            // `pull_interval` later, and the pass goes on under the lease
            // still in force: a scheduler that stopped here also stopped the
            // pulls, metrics and receipts until the next restart. The reason
            // stays in `cloud status` until a renewal succeeds.
            Err(error @ (CloudError::Revoked(_) | CloudError::LeaseLapsed)) => {
                store.record_error(&error.to_string());
                return TickOutcome::Stop(error.to_string());
            }
            Err(error) => {
                store.record_error(&error.to_string());
                store.record_renew_error(Some(&error.to_string()));
                outcome = TickOutcome::Retry(error.to_string());
            }
        }
    }
    // A vault a checkout left (pulled link file, identity change) leaves
    // projects.json first, whatever pauses below: metrics and receipts
    // read the map too and are never filed under it.
    if let Err(error) = crate::resolution::load_current(store.data_dir(), None) {
        store.record_error(&format!("vault map: {error}"));
    }
    // A local screening rule that does not compile pauses every content
    // channel (fails closed) and says so each pass; the policy pull that
    // may bring fixed rules goes on.
    let screen_problem = super::knowledge::screening::Screen::for_installation().problem();
    if let Some(problem) = &screen_problem {
        store.record_error(problem);
    } else {
        if due(store, config, "knowledge", now) {
            crate::knowledge::pull::sync(&session, config, None);
        }
        for problem in crate::tasks::propose::drain(&session).problems {
            store.record_error(&format!("tasks: {problem}"));
        }
    }
    if due(store, config, "policy", now)
        && session
            .lease
            .lease
            .grants(lean_ctx_protocol::cloud::lease::CloudRight::PolicyPull)
    {
        match crate::policy::pull(&session) {
            Ok(_) => crate::policy::note_pull(store.data_dir(), crate::policy::PulledVia::Poll),
            Err(error) => store.record_error(&format!("policy: {error}")),
        }
    }
    // Engine metrics v2 (hourly, per vault); held back until released.
    use crate::metrics_v2::upload::{self as hours, MetricsV2Run};
    match hours::run(&session, config, now, false) {
        Ok(MetricsV2Run::Sent { .. } | MetricsV2Run::Empty) => store.record_success(
            "metrics_v2",
            &now.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true),
        ),
        Ok(_) => {}
        Err(error) => store.record_error(&format!("instance metrics: {error}")),
    }
    match crate::receipts::run(&session, config, now) {
        Ok(crate::receipts::ReceiptsRun::Sent { accepted, .. }) if accepted > 0 => {
            store.record_success(
                "receipts",
                &now.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true),
            );
        }
        Ok(_) => {}
        Err(error) => store.record_error(&format!("receipts: {error}")),
    }
    // The team stop for `cloud status`, which reads only this cache; a
    // failed read keeps the last answer, which status then shows as stale.
    let _ = crate::team_stop::refresh_with(store, &session);
    outcome
}

/// Whether the last success on `channel` is older than `pull_interval_minutes`.
fn due(
    store: &CloudStore,
    config: &CloudConfig,
    channel: &str,
    now: lean_ctx_time::UtcDateTime,
) -> bool {
    let interval = lean_ctx_time::Duration::minutes(i64::from(config.pull_interval()));
    store
        .activity()
        .last_success
        .get(channel)
        .and_then(|t| lean_ctx_time::OffsetDateTime::parse_from_rfc3339(t).ok())
        .is_none_or(|last| now - last.to_utc() >= interval)
}

/// One pending policy nudge.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Nudge {
    /// The version the hint named; `None` (a reconnect): pull regardless.
    version: Option<u64>,
}

impl Nudge {
    /// Two nudges as one: a pull regardless wins, else the newer version.
    fn merge(self, other: Self) -> Self {
        Self {
            version: self.version.zip(other.version).map(|(a, b)| a.max(b)),
        }
    }
}

/// The pending policy nudge, and when the last nudged pull ran.
struct Nudges {
    policy: Option<Nudge>,
    last_run: Option<Instant>,
}

static NUDGES: Mutex<Nudges> = Mutex::new(Nudges {
    policy: None,
    last_run: None,
});
static NUDGE_WAKE: Condvar = Condvar::new();
/// At most one nudged policy pull per this interval (a burst of frames is
/// one pull).
const NUDGE_SPACING: Duration = Duration::from_secs(10);

fn nudges() -> MutexGuard<'static, Nudges> {
    NUDGES.lock().unwrap_or_else(PoisonError::into_inner)
}

/// Ask the scheduler to pull the policy now: Cloud announced `version`
/// (`policy.advanced`), or the bus reconnected (`None`). A hint only: the
/// pull verifies the signed bundle before anything applies, and acks it.
pub fn nudge_policy(version: Option<u64>) {
    {
        let mut pending = nudges();
        let nudge = Nudge { version };
        pending.policy = Some(pending.policy.map_or(nudge, |held| held.merge(nudge)));
    }
    NUDGE_WAKE.notify_all();
}

/// Wait until `deadline` or a policy nudge that may run (spaced by
/// [`NUDGE_SPACING`]). The nudge when nudged, `None` at `deadline`.
fn wait_nudge(deadline: Instant) -> Option<Nudge> {
    let mut pending = nudges();
    loop {
        let now = Instant::now();
        let until = match pending.policy {
            Some(nudge) => {
                let ready = pending.last_run.map_or(now, |last| last + NUDGE_SPACING);
                if ready <= now {
                    pending.policy = None;
                    pending.last_run = Some(now);
                    return Some(nudge);
                }
                ready.min(deadline)
            }
            None => deadline,
        };
        if until <= now {
            return None;
        }
        pending = NUDGE_WAKE
            .wait_timeout(pending, until - now)
            .unwrap_or_else(PoisonError::into_inner)
            .0;
    }
}

/// Whether a nudge for `requested` needs a pull with `installed` in force.
fn nudge_needed(requested: Option<u64>, installed: Option<u64>) -> bool {
    match requested {
        None => true,
        Some(version) => installed.is_none_or(|have| have < version),
    }
}

/// The Cloud session of this connected machine under a lease still in
/// force, for work off the tick (nudged pulls, background sync). The tick
/// alone renews the lease and finishes a pending disconnect.
pub(crate) fn connected_session(
    store: &CloudStore,
    config: &CloudConfig,
) -> Result<Session, CloudError> {
    if config.enabled == Some(false) {
        return Err(CloudError::NotConnected);
    }
    let instance = store.instance()?.ok_or(CloudError::NotConnected)?;
    let root = super::root_cert::trust_root(store, config, &instance.url)?;
    let session = Session::load(store.clone(), root)?;
    if session.lease.state_at(UtcDateTime::now()) == LeaseState::Lapsed {
        return Err(CloudError::LeaseLapsed);
    }
    Ok(session)
}

/// The nudged pull: verify, apply and ack the policy now (the same
/// [`crate::policy::pull`] the tick runs), outside the tick.
fn policy_now(store: &CloudStore, config: &CloudConfig, requested: Option<u64>) {
    let installed = crate::policy::load_state(store.data_dir())
        .effective
        .map(|effective| effective.version);
    if config.enabled == Some(false) || !nudge_needed(requested, installed) {
        return;
    }
    let session = match connected_session(store, config) {
        Ok(session) => session,
        Err(error) => {
            store.record_error(&format!("policy nudge: {error}"));
            return;
        }
    };
    if !session
        .lease
        .lease
        .grants(lean_ctx_protocol::cloud::lease::CloudRight::PolicyPull)
    {
        return;
    }
    match crate::policy::pull(&session) {
        Ok(_) => crate::policy::note_pull(store.data_dir(), crate::policy::PulledVia::Nudge),
        Err(error) => store.record_error(&format!("policy: {error}")),
    }
}

/// How often a daemon that started before `cloud connect` looks for the
/// connection (#1314): one file read.
pub(crate) const CONNECT_POLL: Duration = Duration::from_secs(15);

/// The longest wait after a connection whose first pass stopped at once.
const STOPPED_BACKOFF_MAX: Duration = Duration::from_secs(3600);

/// Whether this machine is enrolled with a Cloud (an instance record).
pub(crate) fn is_connected(store: &CloudStore) -> bool {
    matches!(store.instance(), Ok(Some(_)))
}

/// Block until this machine is enrolled, looking every `poll` (#1314).
pub(crate) fn wait_until_connected(store: &CloudStore, poll: Duration) {
    wait_until(poll, || is_connected(store).then_some(()));
}

/// Block until `ready` gives a value, asking every `poll`.
fn wait_until<T>(poll: Duration, mut ready: impl FnMut() -> Option<T>) -> T {
    loop {
        if let Some(value) = ready() {
            return value;
        }
        std::thread::sleep(poll);
    }
}

/// Start the scheduler thread unless Cloud is disabled. The thread runs the
/// passes while this machine has a usable session and waits for one (a
/// `cloud connect`) before and after (#1314). Returns `None` when Cloud is
/// disabled at start.
pub fn spawn(config: &CloudConfig) -> Option<std::thread::JoinHandle<()>> {
    let store = CloudStore::open().ok()?;
    if config.enabled == Some(false) {
        // Disabled: nothing records for Cloud (N1).
        super::receipts::stop_local_recording(store.data_dir());
        return None;
    }
    if connected_session(&store, config).is_err() {
        // Not connected (or not usable) yet: nothing records for Cloud (N1)
        // until the first pass after `cloud connect` turns it on again.
        super::receipts::stop_local_recording(store.data_dir());
    }
    std::thread::Builder::new()
        .name("cloud-scheduler".into())
        .spawn(move || {
            // #1314: a daemon running before `cloud connect` is not always
            // restarted by it (the app supervises its own daemon), and a
            // pass that stopped (a disconnect, a lapsed lease) may see a new
            // connection later: wait for a session that loads, so a connect
            // half written (instance before lease) is not a final Stop.
            serve(
                CONNECT_POLL,
                STOPPED_BACKOFF_MAX,
                || {
                    let config = lean_ctx::core::config::Config::load().cloud.clone();
                    connected_session(&store, &config).is_ok().then_some(config)
                },
                |config| run_passes(&store, config),
                std::thread::sleep,
                usize::MAX,
            );
        })
        .ok()
}

/// The scheduler's life over connections: wait (every `poll`) until `ready`
/// gives a config, `run` the passes until a Stop, and again, `rounds`
/// times. A connection whose first pass stops at once (a pending
/// disconnect the Cloud refuses, a state the session check does not see)
/// waits longer each time, doubling from `poll` to `max`, so it never
/// spins or floods the Cloud; one that ran waits `poll` again.
fn serve<C>(
    poll: Duration,
    max: Duration,
    mut ready: impl FnMut() -> Option<C>,
    mut run: impl FnMut(C) -> bool,
    mut sleep: impl FnMut(Duration),
    rounds: usize,
) {
    let mut backoff = poll;
    for _ in 0..rounds {
        let config = loop {
            if let Some(config) = ready() {
                break config;
            }
            sleep(poll);
        };
        if run(config) {
            backoff = poll;
            sleep(poll);
        } else {
            sleep(backoff);
            backoff = backoff.saturating_mul(2).min(max);
        }
    }
}

/// The passes of one connection, until a pass stops (disconnected,
/// disabled, revoked, lapsed). Vault sync runs beside them (gap 2 A).
/// Whether a pass ran before the Stop.
fn run_passes(store: &CloudStore, mut config: CloudConfig) -> bool {
    super::sync::auto::spawn(store.clone(), config.clone());
    let mut ran = false;
    loop {
        if let TickOutcome::Stop(_) = tick(store, &config) {
            super::sync::auto::stop();
            return ran;
        }
        ran = true;
        // Sleep until the next tick; a policy nudge (bus frame
        // `policy.advanced`, a reconnect) pulls the policy at once.
        let next = Instant::now() + tick_every(&config);
        while let Some(nudge) = wait_nudge(next) {
            policy_now(store, &config, nudge.version);
        }
        // K2 review 3 (NEW-2): `config set cloud.metrics_upload false`
        // or `cloud.enabled false` applies on the next tick, not only
        // after a restart of this long-lived process.
        config = lean_ctx::core::config::Config::load().cloud.clone();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_nudge_pulls_only_a_newer_version_or_after_a_reconnect() {
        assert!(nudge_needed(None, Some(9)));
        assert!(nudge_needed(Some(3), None));
        assert!(nudge_needed(Some(4), Some(3)));
        assert!(!nudge_needed(Some(3), Some(3)));
        assert!(!nudge_needed(Some(2), Some(3)));
    }

    /// #1314 (bd 41427): a connection whose pass stops at once (revoked,
    /// a refused pending disconnect) is asked again only after a wait that
    /// doubles up to the maximum, never in a hot loop; one that ran waits
    /// the poll again; an unready one is asked every poll.
    #[test]
    fn a_pass_that_stops_at_once_backs_off() {
        let poll = Duration::from_secs(15);
        let max = Duration::from_secs(60);
        let mut asked = 0;
        let mut runs = 0;
        let mut slept = Vec::new();
        serve(
            poll,
            max,
            || {
                asked += 1;
                (asked != 2).then_some(())
            },
            |()| {
                runs += 1;
                runs == 4
            },
            |d| slept.push(d.as_secs()),
            6,
        );
        assert_eq!(runs, 6);
        // Stopped at once: 15; not ready: 15; stopped: 30, 60 (the
        // maximum); ran: 15 (reset); stopped: 15, 30.
        assert_eq!(slept, [15, 15, 30, 60, 15, 15, 30]);
    }

    /// #1314: the wait for `cloud connect` ends as soon as the instance
    /// record is there.
    #[test]
    fn the_wait_ends_once_the_machine_is_connected() {
        let tmp = tempfile::tempdir().unwrap();
        let store = CloudStore::at(tmp.path().join("config"), tmp.path().join("data"));
        assert!(!is_connected(&store));
        let waiting = {
            let store = store.clone();
            std::thread::spawn(move || wait_until_connected(&store, Duration::from_millis(5)))
        };
        std::thread::sleep(Duration::from_millis(30));
        assert!(!waiting.is_finished(), "no instance record: still waiting");
        let record = crate::state::InstanceRecord {
            instance_id: "inst_8e3c0d5f2b4e4f609b8c1d2e3f4a5b6c".into(),
            org_id: "org_ada".into(),
            org_name: "ada".into(),
            label: "laptop".into(),
            url: "https://cloud.example".into(),
            org_salt_id: "s".into(),
            enrolled_at: "2026-11-26T10:00:00Z".into(),
            web_url: None,
            org_kind: None,
            company_name: None,
        };
        store
            .write_config(crate::state::INSTANCE_FILE, &record)
            .unwrap();
        waiting.join().unwrap();
        assert!(is_connected(&store));
    }

    /// One test owns the process-wide nudge state (nextest runs each test
    /// in its own process).
    #[test]
    fn nudges_coalesce_and_are_spaced() {
        let soon = || Instant::now() + Duration::from_millis(50);
        assert_eq!(wait_nudge(soon()), None, "no nudge: the deadline");
        nudge_policy(Some(4));
        nudge_policy(None);
        nudge_policy(Some(6));
        assert_eq!(
            wait_nudge(soon()),
            Some(Nudge { version: None }),
            "one pull for the burst; the reconnect pulls regardless"
        );
        // The next nudge within the spacing waits past a short deadline.
        nudge_policy(Some(7));
        assert_eq!(wait_nudge(soon()), None);
        nudges().last_run = Instant::now().checked_sub(NUDGE_SPACING);
        assert_eq!(wait_nudge(soon()), Some(Nudge { version: Some(7) }));
    }
}