Skip to main content

lean_ctx/core/hive/
connect.rs

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