Skip to main content

lean_ctx_cloud/
connect.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The steps of `lean-ctx cloud connect` after the device flow (CHECKLIST
3//! 2.1.1): the person confirms once per workspace what this machine shares
4//! with it, then the current project is mapped to its vault.
5//!
6//! The answer is kept in `<config_dir>/cloud/sharing.json` (0600), so later
7//! sessions and later connects to the same workspace ask nothing. A "no"
8//! switches every outbound channel off in `[cloud]`. Pulling the workspace's
9//! knowledge and policy goes on.
10//! Nothing here talks to Cloud.
11
12use std::path::Path;
13
14use lean_ctx_time::UtcDateTime;
15use serde::{Deserialize, Serialize};
16
17use super::config::{CloudBusMode, CloudConfig};
18use super::state::SHARING_FILE;
19use super::vault::{VaultMap, project_identity};
20use super::{CloudError, CloudStore};
21
22pub const SHARING_SCHEMA: &str = "leanctx.cloud.sharing/v1";
23
24/// What the person answered for one workspace.
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26#[serde(deny_unknown_fields)]
27pub struct SharingDecision {
28    pub schema: String,
29    /// The workspace (organization) the answer is for.
30    pub org_id: String,
31    pub shared: bool,
32    pub decided_at: String,
33    /// Where it was answered: `browser` for the device approval page
34    /// (C0 2.1); absent for the terminal.
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub source: Option<String>,
37}
38
39/// [`SharingDecision::source`] of an answer given on the approval page.
40pub const SOURCE_BROWSER: &str = "browser";
41
42/// The decision recorded for `org_id`. An answer for another workspace,
43/// another schema or a damaged file counts as none, so it is asked again.
44pub fn decision(store: &CloudStore, org_id: &str) -> Option<SharingDecision> {
45    store
46        .read_config::<SharingDecision>(SHARING_FILE)
47        .ok()
48        .flatten()
49        .filter(|d| d.schema == SHARING_SCHEMA && d.org_id == org_id)
50}
51
52/// Record the person's answer for `org_id`, given in the terminal.
53pub fn record(
54    store: &CloudStore,
55    org_id: &str,
56    shared: bool,
57    now: UtcDateTime,
58) -> Result<SharingDecision, CloudError> {
59    record_from(store, org_id, shared, now, None)
60}
61
62/// Record the person's answer for `org_id`; `source` names where it was
63/// given ([`SOURCE_BROWSER`]), `None` for the terminal.
64pub fn record_from(
65    store: &CloudStore,
66    org_id: &str,
67    shared: bool,
68    now: UtcDateTime,
69    source: Option<&str>,
70) -> Result<SharingDecision, CloudError> {
71    let decision = SharingDecision {
72        schema: SHARING_SCHEMA.into(),
73        org_id: org_id.into(),
74        shared,
75        decided_at: now.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true),
76        source: source.map(str::to_string),
77    };
78    store.write_config(SHARING_FILE, &decision)?;
79    Ok(decision)
80}
81
82/// What leaves this machine for the workspace under `config`, one line
83/// each: exactly what the engine sends, nothing it does not. Empty when
84/// nothing does. Engine metrics are asked separately once released
85/// (`engine_metrics_notice`); usage totals and context receipts are not
86/// sent by this version.
87pub fn shared_items(config: &CloudConfig) -> Vec<&'static str> {
88    if config.enabled == Some(false) {
89        return Vec::new();
90    }
91    let mut items = Vec::new();
92    if config.auto_capture {
93        items.push(
94            "knowledge from your sessions that passes the capture gate: single claims with a file, symbol, test, commit or link reference (never chats, tool output or whole files)",
95        );
96    }
97    if config.bus == CloudBusMode::Auto {
98        items.push(
99            "your agents' presence (role, state and this machine's short name, never its domain) and the bus messages they send to the workspace",
100        );
101        if config.presence_names {
102            items.push(
103                "for your team only: what each agent is working on, from the status it sets itself, with paths and secrets removed (turn off with cloud.presence_names = false)",
104            );
105        }
106        items.push("hourly collaboration friction counts, such as merge conflicts (numbers only)");
107    }
108    items.push(
109        "task traffic your agents start: tasks they propose, and claims, one-line updates and results of tasks they work on under your worker opt-in",
110    );
111    items
112}
113
114/// [`shared_items`] as the C0 2.1 share codes the approval page words
115/// (`knowledge`, `bus`), sorted. `usage` and `receipts` are not sent by
116/// this version and are not announced.
117pub fn share_codes(config: &CloudConfig) -> Vec<String> {
118    if config.enabled == Some(false) {
119        return Vec::new();
120    }
121    let mut codes = Vec::new();
122    if config.bus == CloudBusMode::Auto {
123        codes.push("bus".to_string());
124    }
125    if config.auto_capture {
126        codes.push("knowledge".to_string());
127    }
128    codes
129}
130
131/// `config` with every outbound channel off: what a "no" means.
132pub fn without_sharing(config: &mut CloudConfig) {
133    config.auto_capture = false;
134    config.metrics_upload = false;
135    config.receipts_upload = false;
136    config.bus = CloudBusMode::Off;
137}
138
139/// `config` with the channels a "no" switched off back at their defaults:
140/// what a later yes means.
141pub fn with_sharing(config: &mut CloudConfig) {
142    let defaults = CloudConfig::default();
143    config.auto_capture = defaults.auto_capture;
144    config.metrics_upload = defaults.metrics_upload;
145    config.receipts_upload = defaults.receipts_upload;
146    config.bus = defaults.bus;
147}
148
149/// What connect does for the project at `root`.
150#[derive(Debug, Clone, PartialEq, Eq)]
151pub enum ProjectStep {
152    /// No stable identity (no git origin, id file or manifest): nothing to map.
153    None,
154    /// This machine already knows the vault (`ns/name`).
155    Known(String),
156    /// Ask Cloud for the vault: it maps a known project, or (1.x and v4)
157    /// creates one on first sight.
158    Resolve,
159}
160
161/// The project step for `root`, from local state only.
162pub fn project_step(map: &VaultMap, root: &Path) -> ProjectStep {
163    if project_identity(root).is_none() {
164        return ProjectStep::None;
165    }
166    match map.for_root(&root.to_string_lossy()) {
167        Some(record) => ProjectStep::Known(format!("{}/{}", record.ns, record.name)),
168        None => ProjectStep::Resolve,
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175    use crate::vault::VaultRecord;
176
177    fn store() -> (tempfile::TempDir, CloudStore) {
178        let dir = tempfile::tempdir().unwrap();
179        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
180        (dir, store)
181    }
182
183    #[test]
184    fn a_decision_holds_for_its_workspace_only() {
185        let (_dir, store) = store();
186        assert!(decision(&store, "org_a").is_none(), "nothing asked yet");
187        let now = UtcDateTime::now();
188        record(&store, "org_a", false, now).unwrap();
189        assert!(decision(&store, "org_a").is_some_and(|d| !d.shared));
190        assert!(decision(&store, "org_b").is_none());
191        record(&store, "org_a", true, now).unwrap();
192        let kept = decision(&store, "org_a").unwrap();
193        assert!(kept.shared);
194        assert!(
195            decision(&store, "org_b").is_none(),
196            "another workspace asks again"
197        );
198        assert_eq!(kept.source, None, "answered in the terminal");
199        record(&store, "org_a", false, now).unwrap();
200        assert!(!decision(&store, "org_a").unwrap().shared);
201        // C0 2.1: the device page's answer keeps where it came from.
202        record_from(&store, "org_a", true, now, Some(SOURCE_BROWSER)).unwrap();
203        let browser = decision(&store, "org_a").unwrap();
204        assert!(browser.shared);
205        assert_eq!(browser.source.as_deref(), Some("browser"));
206        #[cfg(unix)]
207        {
208            use std::os::unix::fs::PermissionsExt as _;
209            let mode = std::fs::metadata(store.config_dir().join(SHARING_FILE))
210                .unwrap()
211                .permissions()
212                .mode();
213            assert_eq!(mode & 0o777, 0o600);
214        }
215    }
216
217    #[test]
218    fn a_damaged_or_foreign_record_counts_as_no_answer() {
219        let (_dir, store) = store();
220        store
221            .write_config_bytes(SHARING_FILE, b"{not json")
222            .unwrap();
223        assert!(decision(&store, "org_a").is_none());
224        let other = serde_json::json!({
225            "schema": "leanctx.cloud.sharing/v0",
226            "org_id": "org_a",
227            "shared": true,
228            "decided_at": "2026-10-25T00:00:00Z",
229        });
230        store.write_config(SHARING_FILE, &other).unwrap();
231        assert!(decision(&store, "org_a").is_none());
232    }
233
234    #[test]
235    fn disconnect_forgets_the_decision() {
236        let (_dir, store) = store();
237        record(&store, "org_a", true, UtcDateTime::now()).unwrap();
238        store.forget(true).unwrap();
239        assert!(decision(&store, "org_a").is_none());
240    }
241
242    #[test]
243    fn the_summary_names_each_channel_that_is_on_and_a_no_turns_all_off() {
244        let mut config = CloudConfig::default();
245        // Exactly what is sent: knowledge, bus with friction
246        // counts, task traffic; never usage totals or receipts, which this
247        // version does not send.
248        let items = shared_items(&config).join("\n");
249        for sent in [
250            "knowledge",
251            "bus messages",
252            "friction counts",
253            "task traffic",
254        ] {
255            assert!(items.contains(sent), "{sent}: {items}");
256        }
257        for not_sent in ["usage totals", "receipts"] {
258            assert!(!items.contains(not_sent), "{not_sent}: {items}");
259        }
260        assert!(
261            items.contains("machine's short name, never its domain"),
262            "{items}"
263        );
264        assert!(items.contains("paths and secrets removed"), "{items}");
265        let unnamed = CloudConfig {
266            presence_names: false,
267            ..CloudConfig::default()
268        };
269        let unnamed = shared_items(&unnamed).join("\n");
270        assert!(!unnamed.contains("working on"), "the opt-out is said");
271        // The Instance's short name rides with presence either way.
272        assert!(unnamed.contains("machine's short name"), "{unnamed}");
273        assert_eq!(share_codes(&config), ["bus", "knowledge"]);
274        without_sharing(&mut config);
275        assert!(share_codes(&config).is_empty());
276        let left = shared_items(&config).join("\n");
277        assert!(!left.contains("knowledge from") && !left.contains("bus messages"));
278        assert!(!config.auto_capture && !config.metrics_upload && !config.receipts_upload);
279        assert_eq!(config.bus, CloudBusMode::Off);
280        // A later yes (E2E 27.10. E2) turns the same channels back on.
281        with_sharing(&mut config);
282        assert_eq!(share_codes(&config), share_codes(&CloudConfig::default()));
283        let paused = CloudConfig {
284            enabled: Some(false),
285            ..CloudConfig::default()
286        };
287        assert!(
288            shared_items(&paused).is_empty(),
289            "a paused LeanCTX Cloud connection sends nothing"
290        );
291    }
292
293    #[test]
294    fn the_project_step_maps_known_checkouts_and_resolves_new_ones() {
295        let base = tempfile::tempdir().unwrap();
296        let bare = base.path().join("bare");
297        std::fs::create_dir_all(&bare).unwrap();
298        let map = VaultMap::default();
299        assert_eq!(project_step(&map, &bare), ProjectStep::None);
300
301        let repo = base.path().join("repo");
302        std::fs::create_dir_all(repo.join(".git")).unwrap();
303        std::fs::write(
304            repo.join(".git/config"),
305            "[remote \"origin\"]\n\turl = git@github.com:acme/payments.git\n",
306        )
307        .unwrap();
308        assert_eq!(project_step(&map, &repo), ProjectStep::Resolve);
309
310        let mut map = VaultMap::default();
311        map.vaults.insert(
312            "s1".into(),
313            VaultRecord {
314                vault_id: "v1".into(),
315                ns: "acme".into(),
316                name: "payments".into(),
317                sealed: false,
318                roots: vec![repo.to_string_lossy().into_owned()],
319            },
320        );
321        assert_eq!(
322            project_step(&map, &repo),
323            ProjectStep::Known("acme/payments".into())
324        );
325    }
326}