1use 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(deny_unknown_fields)]
26pub struct SharingDecision {
27 pub schema: String,
28 pub org_id: String,
30 pub shared: bool,
31 pub decided_at: String,
32 #[serde(default, skip_serializing_if = "Option::is_none")]
35 pub source: Option<String>,
36}
37
38pub const SOURCE_BROWSER: &str = "browser";
40
41pub 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
51pub 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
61pub 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
81pub 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
105pub 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
127pub 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
135pub 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#[derive(Debug, Clone, PartialEq, Eq)]
147pub enum ProjectStep {
148 None,
150 Known(String),
152 Resolve,
155}
156
157pub 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 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 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}