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/// Every channel a "no" switches off is off: what [`without_sharing`]
140/// leaves. A yes given while it holds shares nothing until they are on again.
141pub fn switched_off_by_no(config: &CloudConfig) -> bool {
142    !config.auto_capture
143        && !config.metrics_upload
144        && !config.receipts_upload
145        && config.bus == CloudBusMode::Off
146}
147
148/// `config` with the channels a "no" switched off back at their defaults:
149/// what a later yes means.
150pub fn with_sharing(config: &mut CloudConfig) {
151    let defaults = CloudConfig::default();
152    config.auto_capture = defaults.auto_capture;
153    config.metrics_upload = defaults.metrics_upload;
154    config.receipts_upload = defaults.receipts_upload;
155    config.bus = defaults.bus;
156}
157
158/// What connect does for the project at `root`.
159#[derive(Debug, Clone, PartialEq, Eq)]
160pub enum ProjectStep {
161    /// No stable identity (no git origin, id file or manifest): nothing to map.
162    None,
163    /// This machine already knows the vault (`ns/name`).
164    Known(String),
165    /// The person unlinked this folder (`cloud unlink`), or the list of
166    /// unlinked folders is damaged: connect shares nothing and never says
167    /// it syncs, also not through the main checkout's record (bd 40060).
168    Unlinked,
169    /// Ask Cloud for the vault: it maps a known project, or (1.x and v4)
170    /// creates one on first sight.
171    Resolve,
172}
173
174/// The project step for `root`, from local state only.
175pub fn project_step(data_dir: &Path, map: &VaultMap, root: &Path) -> ProjectStep {
176    if project_identity(root).is_none() {
177        return ProjectStep::None;
178    }
179    if crate::unlinked::contains(data_dir, root) {
180        return ProjectStep::Unlinked;
181    }
182    match map.for_root(&root.to_string_lossy()) {
183        Some(record) => ProjectStep::Known(format!("{}/{}", record.ns, record.name)),
184        None => ProjectStep::Resolve,
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191    use crate::vault::VaultRecord;
192
193    fn store() -> (tempfile::TempDir, CloudStore) {
194        let dir = tempfile::tempdir().unwrap();
195        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
196        (dir, store)
197    }
198
199    #[test]
200    fn a_decision_holds_for_its_workspace_only() {
201        let (_dir, store) = store();
202        assert!(decision(&store, "org_a").is_none(), "nothing asked yet");
203        let now = UtcDateTime::now();
204        record(&store, "org_a", false, now).unwrap();
205        assert!(decision(&store, "org_a").is_some_and(|d| !d.shared));
206        assert!(decision(&store, "org_b").is_none());
207        record(&store, "org_a", true, now).unwrap();
208        let kept = decision(&store, "org_a").unwrap();
209        assert!(kept.shared);
210        assert!(
211            decision(&store, "org_b").is_none(),
212            "another workspace asks again"
213        );
214        assert_eq!(kept.source, None, "answered in the terminal");
215        record(&store, "org_a", false, now).unwrap();
216        assert!(!decision(&store, "org_a").unwrap().shared);
217        // C0 2.1: the device page's answer keeps where it came from.
218        record_from(&store, "org_a", true, now, Some(SOURCE_BROWSER)).unwrap();
219        let browser = decision(&store, "org_a").unwrap();
220        assert!(browser.shared);
221        assert_eq!(browser.source.as_deref(), Some("browser"));
222        #[cfg(unix)]
223        {
224            use std::os::unix::fs::PermissionsExt as _;
225            let mode = std::fs::metadata(store.config_dir().join(SHARING_FILE))
226                .unwrap()
227                .permissions()
228                .mode();
229            assert_eq!(mode & 0o777, 0o600);
230        }
231    }
232
233    #[test]
234    fn a_damaged_or_foreign_record_counts_as_no_answer() {
235        let (_dir, store) = store();
236        store
237            .write_config_bytes(SHARING_FILE, b"{not json")
238            .unwrap();
239        assert!(decision(&store, "org_a").is_none());
240        let other = serde_json::json!({
241            "schema": "leanctx.cloud.sharing/v0",
242            "org_id": "org_a",
243            "shared": true,
244            "decided_at": "2026-10-25T00:00:00Z",
245        });
246        store.write_config(SHARING_FILE, &other).unwrap();
247        assert!(decision(&store, "org_a").is_none());
248    }
249
250    #[test]
251    fn disconnect_forgets_the_decision() {
252        let (_dir, store) = store();
253        record(&store, "org_a", true, UtcDateTime::now()).unwrap();
254        store.forget(true).unwrap();
255        assert!(decision(&store, "org_a").is_none());
256    }
257
258    #[test]
259    fn the_summary_names_each_channel_that_is_on_and_a_no_turns_all_off() {
260        let mut config = CloudConfig::default();
261        // Exactly what is sent: knowledge, bus with friction
262        // counts, task traffic; never usage totals or receipts, which this
263        // version does not send.
264        let items = shared_items(&config).join("\n");
265        for sent in [
266            "knowledge",
267            "bus messages",
268            "friction counts",
269            "task traffic",
270        ] {
271            assert!(items.contains(sent), "{sent}: {items}");
272        }
273        for not_sent in ["usage totals", "receipts"] {
274            assert!(!items.contains(not_sent), "{not_sent}: {items}");
275        }
276        assert!(
277            items.contains("machine's short name, never its domain"),
278            "{items}"
279        );
280        assert!(items.contains("paths and secrets removed"), "{items}");
281        let unnamed = CloudConfig {
282            presence_names: false,
283            ..CloudConfig::default()
284        };
285        let unnamed = shared_items(&unnamed).join("\n");
286        assert!(!unnamed.contains("working on"), "the opt-out is said");
287        // The Instance's short name rides with presence either way.
288        assert!(unnamed.contains("machine's short name"), "{unnamed}");
289        assert_eq!(share_codes(&config), ["bus", "knowledge"]);
290        without_sharing(&mut config);
291        assert!(share_codes(&config).is_empty());
292        let left = shared_items(&config).join("\n");
293        assert!(!left.contains("knowledge from") && !left.contains("bus messages"));
294        assert!(!config.auto_capture && !config.metrics_upload && !config.receipts_upload);
295        assert_eq!(config.bus, CloudBusMode::Off);
296        assert!(switched_off_by_no(&config));
297        // A later yes (E2E 27.10. E2) turns the same channels back on.
298        with_sharing(&mut config);
299        assert_eq!(share_codes(&config), share_codes(&CloudConfig::default()));
300        assert!(!switched_off_by_no(&config));
301        // One channel switched off by hand is not a "no".
302        let one_off = CloudConfig {
303            bus: CloudBusMode::Off,
304            ..CloudConfig::default()
305        };
306        assert!(!switched_off_by_no(&one_off));
307        let paused = CloudConfig {
308            enabled: Some(false),
309            ..CloudConfig::default()
310        };
311        assert!(
312            shared_items(&paused).is_empty(),
313            "a paused LeanCTX Cloud connection sends nothing"
314        );
315    }
316
317    #[test]
318    fn the_project_step_maps_known_checkouts_and_resolves_new_ones() {
319        let base = tempfile::tempdir().unwrap();
320        let bare = base.path().join("bare");
321        std::fs::create_dir_all(&bare).unwrap();
322        let data = base.path().join("data");
323        let map = VaultMap::default();
324        assert_eq!(project_step(&data, &map, &bare), ProjectStep::None);
325
326        let repo = base.path().join("repo");
327        std::fs::create_dir_all(repo.join(".git")).unwrap();
328        std::fs::write(
329            repo.join(".git/config"),
330            "[remote \"origin\"]\n\turl = git@github.com:acme/payments.git\n",
331        )
332        .unwrap();
333        assert_eq!(project_step(&data, &map, &repo), ProjectStep::Resolve);
334
335        let mut map = VaultMap::default();
336        map.vaults.insert(
337            "s1".into(),
338            VaultRecord {
339                vault_id: "v1".into(),
340                ns: "acme".into(),
341                name: "payments".into(),
342                sealed: false,
343                roots: vec![repo.to_string_lossy().into_owned()],
344            },
345        );
346        assert_eq!(
347            project_step(&data, &map, &repo),
348            ProjectStep::Known("acme/payments".into())
349        );
350    }
351
352    /// bd 40060: connect never says an unlinked worktree syncs through its
353    /// main checkout's record.
354    #[test]
355    fn unlink_of_a_worktree_is_its_own_project_step() {
356        let base = tempfile::tempdir().unwrap();
357        let base = base.path().canonicalize().unwrap();
358        let (main, wt) = crate::unlinked::fake_worktree(&base);
359        std::fs::write(wt.join(".lean-ctx-id"), "payments-repo").unwrap();
360        let data = base.join("data");
361        let mut map = VaultMap::default();
362        map.vaults.insert(
363            "s1".into(),
364            VaultRecord {
365                vault_id: "v1".into(),
366                ns: "acme".into(),
367                name: "payments".into(),
368                sealed: false,
369                roots: vec![main.to_string_lossy().into_owned()],
370            },
371        );
372        assert_eq!(
373            project_step(&data, &map, &wt),
374            ProjectStep::Known("acme/payments".into())
375        );
376        crate::unlinked::add(&data, &wt).unwrap();
377        assert_eq!(project_step(&data, &map, &wt), ProjectStep::Unlinked);
378    }
379}