1use serde::Serialize;
12
13use super::{ReasonCode, rules};
14use crate::state::CloudStore;
15
16#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
18#[serde(tag = "state", rename_all = "snake_case")]
19pub enum Sharing {
20 NextSync { vault: String },
22 LocalOnly {
24 reason: ReasonCode,
25 hint: &'static str,
26 },
27 Off,
29 NotShared,
31}
32
33impl Sharing {
34 pub fn line(&self, org: &str) -> String {
36 match self {
37 Self::NextSync { vault } => {
38 format!("Goes to {vault} with the next sync (once its source checks out).")
39 }
40 Self::LocalOnly { reason, hint } => format!(
41 "Saved on this machine only. Not shared with {org}: {hint}. (local only: {})",
42 reason.as_str()
43 ),
44 Self::Off => format!(
45 "Saved on this machine only: sharing knowledge with {org} is switched off on this machine (`cloud.auto_capture`)."
46 ),
47 Self::NotShared => format!(
48 "Ready to share, but this project is not shared with {org} yet: run `lean-ctx cloud connect` here."
49 ),
50 }
51 }
52}
53
54pub fn problem(value: &str, has_ref: bool) -> Option<ReasonCode> {
57 rules::check_statement(value.trim())
58 .err()
59 .or((!has_ref).then_some(ReasonCode::NoReference))
60}
61
62pub fn decide(
65 store: &CloudStore,
66 config: &crate::CloudConfig,
67 project_root: &str,
68 value: &str,
69 has_ref: bool,
70) -> Option<Sharing> {
71 store.instance().ok().flatten()?;
72 if let Some(reason) = problem(value, has_ref) {
73 return Some(Sharing::LocalOnly {
74 reason,
75 hint: reason.plain(),
76 });
77 }
78 if !crate::sync::place::capture_allowed(config) {
79 return Some(Sharing::Off);
80 }
81 let map = crate::vault::connected_map(store);
85 Some(
86 match crate::unlinked::shared_record(store.data_dir(), &map, project_root) {
87 Some(vault) => Sharing::NextSync {
88 vault: format!("{}/{}", vault.ns, vault.name),
89 },
90 None => Sharing::NotShared,
91 },
92 )
93}
94
95pub fn note(project_root: &str, value: &str, has_ref: bool) -> Option<String> {
99 let store = CloudStore::open().ok()?;
100 let instance = store.instance().ok().flatten()?;
101 let anchored =
102 lean_ctx::core::knowledge::ProjectKnowledge::load(project_root).is_some_and(|k| {
103 k.facts
104 .iter()
105 .any(|f| f.is_current() && f.value == value && !f.anchors.is_empty())
106 });
107 let config = lean_ctx::core::config::Config::load().cloud.clone();
108 decide(&store, &config, project_root, value, has_ref || anchored)
109 .map(|sharing| sharing.line(&instance.org_name))
110}
111
112pub const MAX_REJECTED: usize = 200;
117
118#[derive(Debug, Clone, PartialEq, Eq, Serialize, serde::Deserialize)]
120pub struct RejectedFact {
121 pub category: String,
122 pub key: String,
123 pub reason: ReasonCode,
124 #[serde(default)]
126 pub hint: String,
127 pub at: String,
129}
130
131fn rejected_file(vault_id: &str) -> String {
132 let name: String = vault_id
133 .chars()
134 .filter(|c| c.is_ascii_alphanumeric() || *c == '-')
135 .collect();
136 format!("{name}.rejected.json")
137}
138
139fn load_rejected(data_dir: &std::path::Path, vault_id: &str) -> Vec<RejectedFact> {
140 std::fs::read(data_dir.join("capture").join(rejected_file(vault_id)))
141 .ok()
142 .and_then(|b| serde_json::from_slice(&b).ok())
143 .unwrap_or_default()
144}
145
146pub fn record_rejected(
150 data_dir: &std::path::Path,
151 vault_id: &str,
152 dropped: &[(String, ReasonCode)],
153 now: lean_ctx_time::UtcDateTime,
154) {
155 let fixable = |reason: &ReasonCode| {
158 !matches!(
159 reason,
160 ReasonCode::Duplicate | ReasonCode::NearDuplicateMerged | ReasonCode::BudgetBatchFull
161 )
162 };
163 if dropped.iter().all(|(_, r)| !fixable(r)) {
164 return;
165 }
166 let at = now.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true);
167 let mut rows = load_rejected(data_dir, vault_id);
168 for (label, reason) in dropped.iter().filter(|(_, r)| fixable(r)) {
169 let (category, key) = label.split_once('/').unwrap_or((label.as_str(), ""));
170 rows.retain(|row| !(row.category == category && row.key == key));
171 rows.push(RejectedFact {
172 category: category.to_owned(),
173 key: key.to_owned(),
174 reason: *reason,
175 hint: reason.plain().to_owned(),
176 at: at.clone(),
177 });
178 }
179 if rows.len() > MAX_REJECTED {
180 let extra = rows.len() - MAX_REJECTED;
181 rows.drain(..extra);
182 }
183 if let Ok(bytes) = serde_json::to_vec(&rows) {
184 let _ = crate::state::write_private(
185 &data_dir.join("capture"),
186 &rejected_file(vault_id),
187 &bytes,
188 );
189 }
190}
191
192pub fn rejected_now(
196 data_dir: &std::path::Path,
197 vault_id: &str,
198 knowledge: Option<&lean_ctx::core::knowledge::ProjectKnowledge>,
199) -> Vec<RejectedFact> {
200 let rows = load_rejected(data_dir, vault_id);
201 let Some(knowledge) = knowledge else {
202 return rows;
203 };
204 rows.into_iter()
205 .filter(|row| {
206 let Ok(at) = lean_ctx_time::OffsetDateTime::parse_from_rfc3339(&row.at) else {
207 return true;
208 };
209 knowledge.facts.iter().any(|f| {
210 f.is_current() && f.category == row.category && f.key == row.key && {
211 let changed = f
212 .capture
213 .changed_at
214 .map_or(f.created_at, |c| c.max(f.created_at));
215 changed <= at
216 }
217 })
218 })
219 .collect()
220}
221
222#[cfg(test)]
223mod tests {
224 use super::*;
225 use crate::vault::VaultMap;
226
227 #[test]
228 fn rejections_are_kept_per_fact_and_only_the_fixable_ones() {
229 let dir = tempfile::tempdir().unwrap();
230 let now = lean_ctx_time::UtcDateTime::now();
231 record_rejected(
232 dir.path(),
233 "v-1",
234 &[
235 ("gotcha/a".into(), ReasonCode::NotSentence),
236 ("gotcha/b".into(), ReasonCode::Duplicate),
237 ],
238 now,
239 );
240 record_rejected(
241 dir.path(),
242 "v-1",
243 &[("gotcha/a".into(), ReasonCode::NoReference)],
244 now,
245 );
246 let rows = rejected_now(dir.path(), "v-1", None);
247 assert_eq!(rows.len(), 1);
248 assert_eq!(
249 (rows[0].category.as_str(), rows[0].key.as_str()),
250 ("gotcha", "a")
251 );
252 assert_eq!(rows[0].reason, ReasonCode::NoReference);
253 assert!(rows[0].hint.contains("--ref"));
254 assert!(rejected_now(dir.path(), "v-2", None).is_empty());
255 }
256
257 #[test]
258 fn a_fragment_or_a_fact_without_a_source_stays_local_with_the_fix() {
259 assert_eq!(
260 problem("not a sentence, just a lowercase fragment here", true),
261 Some(ReasonCode::NotSentence)
262 );
263 assert_eq!(problem("Too short.", true), Some(ReasonCode::TooShort));
264 assert_eq!(
265 problem(
266 "The daemon syncs every shared vault in the background.",
267 false
268 ),
269 Some(ReasonCode::NoReference)
270 );
271 assert_eq!(
272 problem(
273 "The daemon syncs every shared vault in the background.",
274 true
275 ),
276 None
277 );
278 let local = Sharing::LocalOnly {
279 reason: ReasonCode::NoReference,
280 hint: ReasonCode::NoReference.plain(),
281 };
282 let line = local.line("Acme");
283 assert!(line.contains("local only: no_reference"), "{line}");
284 assert!(line.contains("--ref file:"), "the fix is named: {line}");
285 }
286
287 #[test]
290 fn unlink_of_a_worktree_says_not_shared() {
291 let base = tempfile::tempdir().unwrap();
292 let base = base.path().canonicalize().unwrap();
293 let (main, wt) = crate::unlinked::fake_worktree(&base);
294 let store = CloudStore::at(base.join("config"), base.join("data"));
295 store
296 .write_config(
297 crate::state::INSTANCE_FILE,
298 &crate::state::InstanceRecord {
299 instance_id: "inst_a".into(),
300 org_id: "org_a".into(),
301 org_name: "Acme".into(),
302 label: "mac".into(),
303 url: "https://cloud.example".into(),
304 org_salt_id: "salt".into(),
305 enrolled_at: "2026-10-24T00:00:00Z".into(),
306 web_url: None,
307 org_kind: None,
308 company_name: None,
309 },
310 )
311 .unwrap();
312 let mut map = VaultMap::default();
313 map.vaults.insert(
314 "s1".into(),
315 crate::vault::VaultRecord {
316 vault_id: "v1".into(),
317 ns: "acme".into(),
318 name: "payments".into(),
319 sealed: false,
320 roots: vec![main.to_string_lossy().into_owned()],
321 },
322 );
323 map.save(store.data_dir()).unwrap();
324 let config = crate::CloudConfig {
325 auto_capture: true,
326 enabled: None,
327 ..crate::CloudConfig::default()
328 };
329 let fact = "The daemon syncs every shared vault in the background.";
330 let wt_text = wt.to_string_lossy();
331 assert_eq!(
332 decide(&store, &config, &wt_text, fact, true),
333 Some(Sharing::NextSync {
334 vault: "acme/payments".into()
335 })
336 );
337 crate::unlinked::add(store.data_dir(), &wt).unwrap();
338 assert_eq!(
339 decide(&store, &config, &wt_text, fact, true),
340 Some(Sharing::NotShared)
341 );
342 }
343
344 #[test]
345 fn not_connected_says_nothing() {
346 let dir = tempfile::tempdir().unwrap();
347 let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
348 assert_eq!(
349 decide(
350 &store,
351 &crate::CloudConfig::default(),
352 "/x",
353 "not a sentence",
354 false
355 ),
356 None
357 );
358 }
359
360 #[test]
361 fn the_json_shape_names_state_reason_and_hint() {
362 let local = Sharing::LocalOnly {
363 reason: ReasonCode::NotSentence,
364 hint: ReasonCode::NotSentence.plain(),
365 };
366 let value = serde_json::to_value(&local).unwrap();
367 assert_eq!(value["state"], "local_only");
368 assert_eq!(value["reason"], "not_sentence");
369 assert!(value["hint"].as_str().unwrap().contains("capital letter"));
370 assert_eq!(
371 serde_json::to_value(Sharing::NextSync {
372 vault: "a/b".into()
373 })
374 .unwrap(),
375 serde_json::json!({"state": "next_sync", "vault": "a/b"})
376 );
377 }
378}