Skip to main content

lean_ctx_cloud/bus/
leases.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Cross-instance leases through Cloud (C5c).
3//!
4//! `ctx_agent lease_acquire` takes the local lease first (same-machine
5//! contention needs no network), then asks Cloud off the tool call
6//! ([`acquire`], connector rule "Cloud never blocks a tool call"): one
7//! request of at most [`BUDGET`] in the in-process queue
8//! ([`crate::background`]), only while this machine is
9//! enrolled with a Valid or Grace lease that has `bus.relay` and the project
10//! is linked. Otherwise the answer is [`Outcome::Local`] at once, and the
11//! agent is told the lease does not exclude other machines.
12//!
13//! Until Cloud answered `granted` the Cloud side is pending
14//! ([`Outcome::Pending`]): no fencing token, nothing bound or announced.
15//! What Cloud answered (granted, held by another agent, vetoed, unreachable)
16//! comes with the agent's next `ctx_agent` call, and a refusal releases the
17//! local lease. A renewal or release needs Cloud's `lease_id`, so it is
18//! queued behind the grant. `POST /v1/bus/leases` is idempotent for the
19//! holder (a re-acquire extends the same lease and token).
20//!
21//! The Cloud side of a local lease is kept in `<data>/cloud/bus/leases.json`
22//! (beside, not inside, the machine-wide lease store, whose schema other
23//! processes read strictly). Releases are queued there and sent by the relay;
24//! a lost release is covered by the service's own expiry. Tool calls and the
25//! relay change it only through [`Bindings::mutate`], under `leases.json.lock`,
26//! and never hold that lock across a request (RB8 E5): read, ask Cloud,
27//! then apply the answer to what is on disk by then.
28
29use crate::CloudConfigExt as _;
30use std::collections::{BTreeMap, BTreeSet};
31use std::path::Path;
32use std::sync::{Mutex, MutexGuard, PoisonError};
33use std::time::{Duration, Instant};
34
35use serde::{Deserialize, Serialize};
36use serde_json::json;
37use sha2::{Digest, Sha256};
38
39use crate::CloudError;
40use crate::auth::Session;
41use crate::config::{CloudBusMode, CloudConfig};
42use crate::state::{CloudStore, load_or_quarantine, lock_state, write_private};
43use lean_ctx_protocol::cloud::bus::{
44    BUS_LEASE_RENEW_REQUEST_SCHEMA, BUS_LEASE_REQUEST_SCHEMA, BusLeaseV1, MAX_BUS_LEASE_MS,
45};
46use lean_ctx_protocol::cloud::lease::{CloudRight, LeaseState};
47
48/// Whole budget of one acquire or renew a tool call queued.
49pub const BUDGET: Duration = Duration::from_secs(3);
50const LEASES_FILE: &str = "leases.json";
51/// Queued releases kept at most; the oldest go first, the service lets
52/// their leases expire (RB8 M14).
53const MAX_RELEASES: usize = 256;
54/// A binding this long past its expiry is dropped: Cloud forgot it too.
55const STALE_BINDING: lean_ctx_time::Duration = lean_ctx_time::Duration::days(1);
56
57/// What Cloud answered, or why it was not asked.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub enum Outcome {
60    Granted {
61        lease_id: String,
62        fencing_token: u64,
63        expires_at: String,
64    },
65    /// Another agent (possibly on another machine) holds it.
66    Held {
67        agent_id: String,
68        instance_id: String,
69        expires_at: String,
70    },
71    /// An organization veto bars this agent from the resource.
72    Vetoed,
73    /// Cloud no longer knows the lease (expired on the service clock or superseded).
74    Superseded,
75    /// Cloud was not asked or did not answer in time: local only.
76    Local(String),
77    /// Cloud is being asked off the tool call; its answer comes with the
78    /// agent's next `ctx_agent` call. No fencing token yet.
79    Pending,
80}
81
82/// Local lease refs whose Cloud acquire is queued or running in this
83/// process: their renewal and release wait behind it.
84static PENDING: Mutex<BTreeSet<String>> = Mutex::new(BTreeSet::new());
85
86fn pending() -> MutexGuard<'static, BTreeSet<String>> {
87    PENDING.lock().unwrap_or_else(PoisonError::into_inner)
88}
89
90/// The queue caller of `agent_id`'s `ctx_agent` calls
91/// ([`crate::background::with_answers`]).
92pub fn caller(agent_id: &str) -> String {
93    format!("ctx_agent:{agent_id}")
94}
95
96/// The Cloud lease behind a local one.
97#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
98pub struct Binding {
99    pub lease_id: String,
100    pub fencing_token: u64,
101    /// On disk as `project_id` (pre-VA name) for downgrades and mixed-version teams.
102    #[serde(rename = "project_id", alias = "vault_id")]
103    pub vault_id: String,
104    pub expires_at: String,
105}
106
107/// A release still to send.
108#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
109pub struct Release {
110    pub lease_id: String,
111    pub fencing_token: u64,
112}
113
114/// `leases.json`: local `lease_ref` → Cloud lease, plus queued releases.
115#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
116pub struct Bindings {
117    #[serde(default)]
118    pub leases: BTreeMap<String, Binding>,
119    #[serde(default)]
120    pub releases: Vec<Release>,
121}
122
123impl Bindings {
124    /// The bindings on disk. A damaged file is moved aside (RB8 M12) and the
125    /// bindings start empty: the service expires what this machine forgot.
126    pub fn load(data_dir: &Path) -> Self {
127        load_or_quarantine(&data_dir.join("bus").join(LEASES_FILE), |_: &Self| true)
128            .unwrap_or_else(|error| {
129                tracing::warn!("cloud lease bindings: {error}");
130                None
131            })
132            .unwrap_or_default()
133    }
134
135    fn save(&self, data_dir: &Path) -> Result<(), CloudError> {
136        let bytes = serde_json::to_vec(self).map_err(|e| CloudError::Local(e.to_string()))?;
137        write_private(&data_dir.join("bus"), LEASES_FILE, &bytes)
138    }
139
140    /// Load, change and save under the bindings lock (RB8 E5). Stale
141    /// bindings and releases past `MAX_RELEASES` go (M14). Never call it
142    /// around a request.
143    pub fn mutate<T>(
144        data_dir: &Path,
145        change: impl FnOnce(&mut Self) -> T,
146    ) -> Result<T, CloudError> {
147        let _lock = lock_state(&data_dir.join("bus"), LEASES_FILE)?;
148        let mut bindings = Self::load(data_dir);
149        let before = bindings.clone();
150        let out = change(&mut bindings);
151        bindings.prune(lean_ctx_time::UtcDateTime::now());
152        if bindings != before {
153            bindings.save(data_dir)?;
154        }
155        Ok(out)
156    }
157
158    fn prune(&mut self, now: lean_ctx_time::UtcDateTime) {
159        self.leases.retain(|_, b| {
160            lean_ctx_time::OffsetDateTime::parse_from_rfc3339(&b.expires_at)
161                .map_or(true, |at| at.to_utc() + STALE_BINDING > now)
162        });
163        let excess = self.releases.len().saturating_sub(MAX_RELEASES);
164        self.releases.drain(..excess);
165    }
166}
167
168/// The machine-independent Cloud `resource_ref` of a lease target in a
169/// project: no path leaves the engine, and every checkout of the project
170/// names a file the same way.
171pub fn resource_ref(vault_id: &str, kind: &str, target: &str) -> String {
172    let digest = Sha256::digest(
173        format!("leanctx.cloud.bus-lease.v1\n{vault_id}\n{kind}\n{target}").as_bytes(),
174    );
175    hex::encode(digest)
176}
177
178/// `(kind, normalized target)` of a `ctx_agent` lease target: `symbol:<name>`
179/// or a path inside `project_root` (repo-relative, `/`-separated). `None`
180/// for a path outside the project.
181pub fn normalize_target(project_root: &Path, raw: &str) -> Option<(&'static str, String)> {
182    let raw = raw.trim();
183    if let Some(symbol) = raw.strip_prefix("symbol:") {
184        let symbol = symbol.trim();
185        return (!symbol.is_empty()).then(|| ("symbol", symbol.to_string()));
186    }
187    let path = Path::new(raw);
188    // Anchored, not only `is_absolute`: on Windows a rooted path without a
189    // drive (`/home/ada/x`, as another checkout reports it) is not absolute,
190    // yet it names a place below its root, never a relative target.
191    let anchored = path.has_root()
192        || matches!(
193            path.components().next(),
194            Some(std::path::Component::Prefix(_))
195        );
196    let relative = if anchored {
197        path.strip_prefix(project_root).ok()?
198    } else {
199        path
200    };
201    let mut parts: Vec<String> = Vec::new();
202    for component in relative.components() {
203        match component {
204            std::path::Component::Normal(part) => parts.push(part.to_string_lossy().into_owned()),
205            std::path::Component::CurDir => {}
206            std::path::Component::ParentDir => {
207                parts.pop()?;
208            }
209            _ => return None,
210        }
211    }
212    (!parts.is_empty()).then(|| ("file", parts.join("/")))
213}
214
215/// A connected machine and the Cloud project of a local root.
216pub(super) struct Connected {
217    pub(super) store: CloudStore,
218    pub(super) session: Session,
219    pub(super) vault_id: String,
220}
221
222/// Whether Cloud applies to `project_root`; `Err` says why not (no request made).
223pub(super) fn connected(project_root: &Path) -> Result<Connected, String> {
224    let config = lean_ctx::core::config::Config::load().cloud.clone();
225    connected_with(
226        &config,
227        CloudStore::open().map_err(|e| e.to_string())?,
228        project_root,
229    )
230}
231
232fn connected_with(
233    config: &CloudConfig,
234    store: CloudStore,
235    project_root: &Path,
236) -> Result<Connected, String> {
237    if config.bus == CloudBusMode::Off || config.enabled == Some(false) {
238        return Err("the Cloud bus is off".into());
239    }
240    let instance = store
241        .instance()
242        .ok()
243        .flatten()
244        .ok_or_else(|| "this machine is not connected to the Cloud".to_string())?;
245    let vault_id = crate::resolution::vault_for_root(&store, project_root)
246        .map_err(|e| e.to_string())?
247        .map(|p| p.vault_id)
248        .ok_or_else(|| "this repository is not linked to a vault".to_string())?;
249    let session = config
250        .root_key(&instance.url)
251        .and_then(|root| Session::load(store.clone(), root))
252        .map_err(|e| e.to_string())?;
253    if !matches!(
254        session.lease.state_at(lean_ctx_time::UtcDateTime::now()),
255        LeaseState::Valid | LeaseState::Grace
256    ) {
257        return Err("the Cloud lease has lapsed".into());
258    }
259    if !session.lease.lease.grants(CloudRight::BusRelay) {
260        return Err("the Cloud lease does not include the bus".into());
261    }
262    Ok(Connected {
263        store,
264        session,
265        vault_id,
266    })
267}
268
269fn decode_lease(value: serde_json::Value) -> Result<BusLeaseV1, CloudError> {
270    let lease: BusLeaseV1 = serde_json::from_value(value)
271        .map_err(|e| CloudError::Protocol(format!("bus lease: {e}")))?;
272    lease
273        .validate()
274        .map_err(|e| CloudError::Protocol(format!("bus lease: {e}")))?;
275    Ok(lease)
276}
277
278fn outcome(answer: Result<BusLeaseV1, CloudError>) -> Outcome {
279    match answer {
280        Ok(BusLeaseV1 {
281            granted: true,
282            lease_id: Some(lease_id),
283            fencing_token: Some(fencing_token),
284            expires_at: Some(expires_at),
285            ..
286        }) => Outcome::Granted {
287            lease_id,
288            fencing_token,
289            expires_at: expires_at.as_str().to_string(),
290        },
291        Ok(BusLeaseV1 {
292            holder: Some(holder),
293            ..
294        }) => Outcome::Held {
295            agent_id: holder.agent_id,
296            instance_id: holder.instance_id,
297            expires_at: holder.expires_at.as_str().to_string(),
298        },
299        Ok(_) => Outcome::Local("the Cloud sent an incomplete lease".into()),
300        Err(CloudError::Vetoed) => Outcome::Vetoed,
301        Err(CloudError::NotFound) => Outcome::Superseded,
302        Err(CloudError::Offline(why)) => {
303            Outcome::Local(format!("the Cloud is not reachable ({why})"))
304        }
305        Err(error) => Outcome::Local(error.to_string()),
306    }
307}
308
309/// Ask Cloud, off the tool call, for the lease the agent already holds
310/// locally (`local_ref`). [`Outcome::Local`] at once when Cloud does not
311/// apply (no request); otherwise [`Outcome::Pending`], and `settle` runs in
312/// the queue with Cloud's answer and returns the line the agent gets with
313/// its next `ctx_agent` call. A grant is bound to `local_ref` before
314/// `settle` runs; `settle` releases the local lease on a refusal.
315pub fn acquire(
316    project_root: &Path,
317    agent_id: &str,
318    target: &str,
319    duration_ms: u64,
320    local_ref: &str,
321    settle: impl FnOnce(Outcome) -> Option<String> + Send + 'static,
322) -> Outcome {
323    let connected = match connected(project_root) {
324        Ok(connected) => connected,
325        Err(why) => return Outcome::Local(why),
326    };
327    if normalize_target(project_root, target).is_none() {
328        return Outcome::Local("the target is outside the project".into());
329    }
330    let (root, agent, target, local) = (
331        project_root.to_path_buf(),
332        agent_id.to_string(),
333        target.to_string(),
334        local_ref.to_string(),
335    );
336    pending().insert(local.clone());
337    crate::background::submit(&caller(agent_id), move || {
338        let outcome = acquire_with(&connected, &root, &agent, &target, duration_ms, &local);
339        pending().remove(&local);
340        settle(outcome)
341    });
342    Outcome::Pending
343}
344
345fn acquire_with(
346    c: &Connected,
347    project_root: &Path,
348    agent_id: &str,
349    target: &str,
350    duration_ms: u64,
351    local_ref: &str,
352) -> Outcome {
353    let Some((kind, normalized)) = normalize_target(project_root, target) else {
354        return Outcome::Local("the target is outside the project".into());
355    };
356    let deadline = Instant::now() + BUDGET;
357    let body = json!({
358        "schema": BUS_LEASE_REQUEST_SCHEMA,
359        "resource_kind": kind,
360        "resource_ref": resource_ref(&c.vault_id, kind, &normalized),
361        "vault_id": c.vault_id,
362        "owner_agent_id": agent_id,
363        "duration_ms": duration_ms.clamp(1, MAX_BUS_LEASE_MS),
364    });
365    let answer = c
366        .session
367        .bounded_client(deadline)
368        .and_then(|client| client.post("/bus/leases", &body))
369        .and_then(decode_lease);
370    let result = outcome(answer);
371    if let Outcome::Granted {
372        lease_id,
373        fencing_token,
374        expires_at,
375    } = &result
376    {
377        let binding = Binding {
378            lease_id: lease_id.clone(),
379            fencing_token: *fencing_token,
380            vault_id: c.vault_id.clone(),
381            expires_at: expires_at.clone(),
382        };
383        if let Err(error) = Bindings::mutate(c.store.data_dir(), |b| {
384            b.leases.insert(local_ref.to_string(), binding);
385        }) {
386            // Unrecorded, the lease would never be renewed or released by us;
387            // the service lets it expire.
388            return Outcome::Local(format!("could not record the Cloud lease: {error}"));
389        }
390    }
391    result
392}
393
394/// Renew the Cloud lease bound to `local_ref`, off the tool call and behind
395/// a pending acquire (it needs Cloud's `lease_id`). A local-only lease gets
396/// [`Outcome::Local`] at once; otherwise [`Outcome::Pending`], and `settle`
397/// gets Cloud's answer as [`acquire`]'s does.
398pub fn renew(
399    project_root: &Path,
400    agent_id: &str,
401    local_ref: &str,
402    duration_ms: u64,
403    settle: impl FnOnce(Outcome) -> Option<String> + Send + 'static,
404) -> Outcome {
405    let Ok(store) = CloudStore::open() else {
406        return Outcome::Local("no Cloud state".into());
407    };
408    let bound = Bindings::load(store.data_dir())
409        .leases
410        .contains_key(local_ref);
411    if !bound && !pending().contains(local_ref) {
412        return Outcome::Local("this lease is local only".into());
413    }
414    let connected = match connected(project_root) {
415        Ok(connected) => connected,
416        Err(why) => return Outcome::Local(why),
417    };
418    let local = local_ref.to_string();
419    crate::background::submit(&caller(agent_id), move || {
420        settle(renew_with(&connected, &local, duration_ms))
421    });
422    Outcome::Pending
423}
424
425fn renew_with(c: &Connected, local_ref: &str, duration_ms: u64) -> Outcome {
426    let data = c.store.data_dir();
427    let Some(binding) = Bindings::load(data).leases.get(local_ref).cloned() else {
428        return Outcome::Local("the Cloud did not grant this lease".into());
429    };
430    let deadline = Instant::now() + BUDGET;
431    let body = json!({
432        "schema": BUS_LEASE_RENEW_REQUEST_SCHEMA,
433        "fencing_token": binding.fencing_token,
434        "duration_ms": duration_ms.clamp(1, MAX_BUS_LEASE_MS),
435    });
436    let path = format!("/bus/leases/{}/renew", binding.lease_id);
437    let result = outcome(
438        c.session
439            .bounded_client(deadline)
440            .and_then(|client| client.post(&path, &body))
441            .and_then(decode_lease),
442    );
443    // Applied to the binding as it is now, and only while it is still the
444    // lease that was renewed (a release or a new grant may have come since).
445    let applied = Bindings::mutate(data, |bindings| {
446        let same = |b: &Binding| b.lease_id == binding.lease_id;
447        match &result {
448            Outcome::Granted { expires_at, .. } => {
449                if let Some(b) = bindings.leases.get_mut(local_ref).filter(|b| same(b)) {
450                    b.expires_at.clone_from(expires_at);
451                }
452            }
453            Outcome::Superseded | Outcome::Vetoed
454                if bindings.leases.get(local_ref).is_some_and(same) =>
455            {
456                bindings.leases.remove(local_ref);
457            }
458            _ => {}
459        }
460    });
461    if let Err(error) = applied {
462        tracing::debug!("cloud lease bindings not saved: {error}");
463    }
464    result
465}
466
467/// The Cloud lease bound to `local_ref`, if any.
468pub fn binding(local_ref: &str) -> Option<Binding> {
469    let store = CloudStore::open().ok()?;
470    Bindings::load(store.data_dir())
471        .leases
472        .get(local_ref)
473        .cloned()
474}
475
476/// Queue the release of the Cloud lease bound to `local_ref` (the relay
477/// sends it). No network in the tool call; while the acquire is still
478/// pending, the release is queued behind it and applies to its grant.
479pub fn release(agent_id: &str, local_ref: &str) {
480    let Ok(store) = CloudStore::open() else {
481        return;
482    };
483    // Checked first: a pending acquire that ends meanwhile has bound its
484    // grant before it leaves `PENDING`, so one of the two releases sees it.
485    let was_pending = pending().contains(local_ref);
486    queue_release_in(store.data_dir(), local_ref);
487    if was_pending {
488        let (data, local) = (store.data_dir().to_path_buf(), local_ref.to_string());
489        crate::background::submit(&caller(agent_id), move || {
490            queue_release_in(&data, &local);
491            None
492        });
493    }
494}
495
496fn queue_release_in(data_dir: &Path, local_ref: &str) {
497    let queued = Bindings::mutate(data_dir, |bindings| {
498        if let Some(b) = bindings.leases.remove(local_ref) {
499            bindings.releases.push(Release {
500                lease_id: b.lease_id,
501                fencing_token: b.fencing_token,
502            });
503        }
504    });
505    if let Err(error) = queued {
506        tracing::debug!("cloud lease release not queued: {error}");
507    }
508}
509
510/// The relay's half: send queued releases (blocking; run off the socket loop).
511/// A release Cloud no longer knows counts as done.
512pub fn send_releases(store: &CloudStore, session: &Session) {
513    let data = store.data_dir();
514    // Sent without the lock; only the ones done leave the queue as it is by
515    // then, so a release queued meanwhile stays (RB8 E5).
516    let done: Vec<Release> = Bindings::load(data)
517        .releases
518        .into_iter()
519        .filter(|r| {
520            let path = format!(
521                "/bus/leases/{}?fencing_token={}",
522                r.lease_id, r.fencing_token
523            );
524            match session.with_client(|client| client.delete(&path)) {
525                Ok(()) | Err(CloudError::NotFound) => true,
526                Err(error) => matches!(
527                    error,
528                    CloudError::Forbidden | CloudError::Vetoed | CloudError::Protocol(_)
529                ),
530            }
531        })
532        .collect();
533    if done.is_empty() {
534        return;
535    }
536    if let Err(error) = Bindings::mutate(data, |b| b.releases.retain(|r| !done.contains(r))) {
537        tracing::debug!("cloud lease releases not saved: {error}");
538    }
539}
540
541/// One line for `ctx_agent`: where the lease holds. The Cloud fencing token
542/// stays in `leases.json` (0600) and is never printed, like a task claim's.
543pub fn scope_line(outcome: &Outcome) -> String {
544    match outcome {
545        Outcome::Granted { .. } | Outcome::Held { .. } | Outcome::Vetoed | Outcome::Superseded => {
546            "scope=cloud".into()
547        }
548        Outcome::Local(why) => {
549            format!("scope=local ({why}; other machines are not excluded)")
550        }
551        Outcome::Pending => "scope=pending (the Cloud is asked off this call; until it grants, \
552             other machines are not excluded; its answer comes with your next ctx_agent call)"
553            .into(),
554    }
555}
556
557#[cfg(test)]
558mod vault_rename_tests {
559    use super::*;
560
561    /// `Binding` of the engine before the VA rename.
562    #[derive(Deserialize)]
563    #[allow(dead_code)]
564    struct PreVaBinding {
565        lease_id: String,
566        fencing_token: u64,
567        project_id: String,
568        expires_at: String,
569    }
570
571    #[test]
572    fn lease_bindings_keep_pre_va_names() {
573        let old = r#"{"lease_id":"lse_1","fencing_token":4,"project_id":"v1","expires_at":"2026-10-22T10:00:00Z"}"#;
574        let read = crate::vault::assert_pre_va_round_trip::<Binding, PreVaBinding>(
575            old,
576            "project_id",
577            "vault_id",
578        );
579        assert_eq!((read.vault_id.as_str(), read.fencing_token), ("v1", 4));
580    }
581}
582
583#[cfg(test)]
584mod tests {
585    use super::*;
586
587    #[test]
588    fn every_checkout_names_a_file_the_same_way() {
589        let a = Path::new("/home/ada/src/payments");
590        let b = Path::new("/Users/bob/work/payments-clone");
591        let (kind, ta) = normalize_target(a, "/home/ada/src/payments/src/lib.rs").unwrap();
592        let (_, tb) = normalize_target(b, "./src/../src/lib.rs").unwrap();
593        assert_eq!((kind, ta.as_str()), ("file", "src/lib.rs"));
594        assert_eq!(ta, tb);
595        let pid = "0123456789abcdef0123456789abcdef";
596        let ref_a = resource_ref(pid, kind, &ta);
597        assert_eq!(ref_a, resource_ref(pid, kind, &tb));
598        assert_eq!(ref_a.len(), 64);
599        assert!(!ref_a.contains("lib"));
600        assert_ne!(
601            ref_a,
602            resource_ref("fedcba9876543210fedcba9876543210", kind, &ta)
603        );
604        assert_ne!(ref_a, resource_ref(pid, "symbol", &ta));
605        assert_eq!(
606            normalize_target(a, "symbol: Parser::parse"),
607            Some(("symbol", "Parser::parse".into()))
608        );
609        assert_eq!(
610            normalize_target(a, "/etc/passwd"),
611            None,
612            "outside the project"
613        );
614        assert_eq!(normalize_target(a, "../other/x.rs"), None);
615        assert_eq!(normalize_target(a, "symbol:"), None);
616    }
617
618    #[test]
619    fn answers_map_to_outcomes_and_the_scope_is_always_named() {
620        let granted = serde_json::json!({"schema": "leanctx.cloud.bus-lease/v1", "granted": true,
621            "lease_id": "bl_1", "fencing_token": 4, "expires_at": "2026-10-21T12:10:00Z",
622            "server_time": "2026-10-21T12:00:00Z"});
623        let out = outcome(decode_lease(granted));
624        assert!(matches!(
625            out,
626            Outcome::Granted {
627                fencing_token: 4,
628                ..
629            }
630        ));
631        assert_eq!(
632            scope_line(&out),
633            "scope=cloud",
634            "the token is never printed"
635        );
636        let held = serde_json::json!({"schema": "leanctx.cloud.bus-lease/v1", "granted": false,
637            "holder": {"agent_id": "beta", "instance_id": "inst_b", "expires_at": "2026-10-21T12:10:00Z"},
638            "server_time": "2026-10-21T12:00:00Z"});
639        assert!(
640            matches!(outcome(decode_lease(held)), Outcome::Held { agent_id, .. } if agent_id == "beta")
641        );
642        assert_eq!(outcome(Err(CloudError::Vetoed)), Outcome::Vetoed);
643        assert_eq!(outcome(Err(CloudError::NotFound)), Outcome::Superseded);
644        let offline = outcome(Err(CloudError::Offline("timeout".into())));
645        assert!(
646            scope_line(&offline).starts_with("scope=local (the Cloud is not reachable (timeout)")
647        );
648        assert!(scope_line(&offline).ends_with("other machines are not excluded)"));
649        let pending = scope_line(&Outcome::Pending);
650        assert!(pending.starts_with("scope=pending (") && !pending.contains("fencing"));
651    }
652
653    #[test]
654    fn without_an_enrollment_no_request_is_made() {
655        let dir = tempfile::tempdir().unwrap();
656        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
657        let err = connected_with(&CloudConfig::default(), store.clone(), dir.path())
658            .err()
659            .unwrap();
660        assert_eq!(err, "this machine is not connected to the Cloud");
661        let off = CloudConfig {
662            bus: CloudBusMode::Off,
663            ..CloudConfig::default()
664        };
665        assert_eq!(
666            connected_with(&off, store, dir.path()).err().unwrap(),
667            "the Cloud bus is off"
668        );
669    }
670
671    #[test]
672    fn bindings_round_trip_and_queue_releases() {
673        let dir = tempfile::tempdir().unwrap();
674        let mut b = Bindings::default();
675        b.leases.insert(
676            "lease-ref:1".into(),
677            Binding {
678                lease_id: "bl_1".into(),
679                fencing_token: 2,
680                vault_id: "p".into(),
681                expires_at: "2026-10-21T12:10:00Z".into(),
682            },
683        );
684        b.save(dir.path()).unwrap();
685        assert_eq!(Bindings::load(dir.path()), b);
686    }
687}