1use serde::Serialize;
12
13use super::{ReasonCode, rules};
14use crate::state::CloudStore;
15use crate::vault::VaultMap;
16
17#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
19#[serde(tag = "state", rename_all = "snake_case")]
20pub enum Sharing {
21 NextSync { vault: String },
23 LocalOnly {
25 reason: ReasonCode,
26 hint: &'static str,
27 },
28 Off,
30 NotShared,
32}
33
34impl Sharing {
35 pub fn line(&self, org: &str) -> String {
37 match self {
38 Self::NextSync { vault } => {
39 format!("Goes to {vault} with the next sync (once its source checks out).")
40 }
41 Self::LocalOnly { reason, hint } => format!(
42 "Saved on this machine only. Not shared with {org}: {hint}. (local only: {})",
43 reason.as_str()
44 ),
45 Self::Off => format!(
46 "Saved on this machine only: sharing knowledge with {org} is switched off on this machine (`cloud.auto_capture`)."
47 ),
48 Self::NotShared => format!(
49 "Ready to share, but this project is not shared with {org} yet: run `lean-ctx cloud connect` here."
50 ),
51 }
52 }
53}
54
55pub fn problem(value: &str, has_ref: bool) -> Option<ReasonCode> {
58 rules::check_statement(value.trim())
59 .err()
60 .or((!has_ref).then_some(ReasonCode::NoReference))
61}
62
63pub fn decide(
66 store: &CloudStore,
67 config: &crate::CloudConfig,
68 project_root: &str,
69 value: &str,
70 has_ref: bool,
71) -> Option<Sharing> {
72 store.instance().ok().flatten()?;
73 if let Some(reason) = problem(value, has_ref) {
74 return Some(Sharing::LocalOnly {
75 reason,
76 hint: reason.plain(),
77 });
78 }
79 if !crate::sync::place::capture_allowed(config) {
80 return Some(Sharing::Off);
81 }
82 let map = VaultMap::load(store.data_dir());
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
226 #[test]
227 fn rejections_are_kept_per_fact_and_only_the_fixable_ones() {
228 let dir = tempfile::tempdir().unwrap();
229 let now = lean_ctx_time::UtcDateTime::now();
230 record_rejected(
231 dir.path(),
232 "v-1",
233 &[
234 ("gotcha/a".into(), ReasonCode::NotSentence),
235 ("gotcha/b".into(), ReasonCode::Duplicate),
236 ],
237 now,
238 );
239 record_rejected(
240 dir.path(),
241 "v-1",
242 &[("gotcha/a".into(), ReasonCode::NoReference)],
243 now,
244 );
245 let rows = rejected_now(dir.path(), "v-1", None);
246 assert_eq!(rows.len(), 1);
247 assert_eq!(
248 (rows[0].category.as_str(), rows[0].key.as_str()),
249 ("gotcha", "a")
250 );
251 assert_eq!(rows[0].reason, ReasonCode::NoReference);
252 assert!(rows[0].hint.contains("--ref"));
253 assert!(rejected_now(dir.path(), "v-2", None).is_empty());
254 }
255
256 #[test]
257 fn a_fragment_or_a_fact_without_a_source_stays_local_with_the_fix() {
258 assert_eq!(
259 problem("not a sentence, just a lowercase fragment here", true),
260 Some(ReasonCode::NotSentence)
261 );
262 assert_eq!(problem("Too short.", true), Some(ReasonCode::TooShort));
263 assert_eq!(
264 problem(
265 "The daemon syncs every shared vault in the background.",
266 false
267 ),
268 Some(ReasonCode::NoReference)
269 );
270 assert_eq!(
271 problem(
272 "The daemon syncs every shared vault in the background.",
273 true
274 ),
275 None
276 );
277 let local = Sharing::LocalOnly {
278 reason: ReasonCode::NoReference,
279 hint: ReasonCode::NoReference.plain(),
280 };
281 let line = local.line("Acme");
282 assert!(line.contains("local only: no_reference"), "{line}");
283 assert!(line.contains("--ref file:"), "the fix is named: {line}");
284 }
285
286 #[test]
289 fn unlink_of_a_worktree_says_not_shared() {
290 let base = tempfile::tempdir().unwrap();
291 let base = base.path().canonicalize().unwrap();
292 let (main, wt) = crate::unlinked::fake_worktree(&base);
293 let store = CloudStore::at(base.join("config"), base.join("data"));
294 store
295 .write_config(
296 crate::state::INSTANCE_FILE,
297 &crate::state::InstanceRecord {
298 instance_id: "inst_a".into(),
299 org_id: "org_a".into(),
300 org_name: "Acme".into(),
301 label: "mac".into(),
302 url: "https://cloud.example".into(),
303 org_salt_id: "salt".into(),
304 enrolled_at: "2026-10-24T00:00:00Z".into(),
305 web_url: None,
306 org_kind: None,
307 company_name: None,
308 },
309 )
310 .unwrap();
311 let mut map = VaultMap::default();
312 map.vaults.insert(
313 "s1".into(),
314 crate::vault::VaultRecord {
315 vault_id: "v1".into(),
316 ns: "acme".into(),
317 name: "payments".into(),
318 sealed: false,
319 roots: vec![main.to_string_lossy().into_owned()],
320 },
321 );
322 map.save(store.data_dir()).unwrap();
323 let config = crate::CloudConfig {
324 auto_capture: true,
325 enabled: None,
326 ..crate::CloudConfig::default()
327 };
328 let fact = "The daemon syncs every shared vault in the background.";
329 let wt_text = wt.to_string_lossy();
330 assert_eq!(
331 decide(&store, &config, &wt_text, fact, true),
332 Some(Sharing::NextSync {
333 vault: "acme/payments".into()
334 })
335 );
336 crate::unlinked::add(store.data_dir(), &wt).unwrap();
337 assert_eq!(
338 decide(&store, &config, &wt_text, fact, true),
339 Some(Sharing::NotShared)
340 );
341 }
342
343 #[test]
344 fn not_connected_says_nothing() {
345 let dir = tempfile::tempdir().unwrap();
346 let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
347 assert_eq!(
348 decide(
349 &store,
350 &crate::CloudConfig::default(),
351 "/x",
352 "not a sentence",
353 false
354 ),
355 None
356 );
357 }
358
359 #[test]
360 fn the_json_shape_names_state_reason_and_hint() {
361 let local = Sharing::LocalOnly {
362 reason: ReasonCode::NotSentence,
363 hint: ReasonCode::NotSentence.plain(),
364 };
365 let value = serde_json::to_value(&local).unwrap();
366 assert_eq!(value["state"], "local_only");
367 assert_eq!(value["reason"], "not_sentence");
368 assert!(value["hint"].as_str().unwrap().contains("capital letter"));
369 assert_eq!(
370 serde_json::to_value(Sharing::NextSync {
371 vault: "a/b".into()
372 })
373 .unwrap(),
374 serde_json::json!({"state": "next_sync", "vault": "a/b"})
375 );
376 }
377}