1use 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26#[serde(deny_unknown_fields)]
27pub struct SharingDecision {
28 pub schema: String,
29 pub org_id: String,
31 pub shared: bool,
32 pub decided_at: String,
33 #[serde(default, skip_serializing_if = "Option::is_none")]
36 pub source: Option<String>,
37}
38
39pub const SOURCE_BROWSER: &str = "browser";
41
42pub 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
52pub 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
62pub 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
82pub 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
114pub 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
131pub 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
139pub 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#[derive(Debug, Clone, PartialEq, Eq)]
151pub enum ProjectStep {
152 None,
154 Known(String),
156 Resolve,
159}
160
161pub 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 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 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 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 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}