Skip to main content

lean_ctx_cloud/capture/
sharing.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Whether a fact just remembered goes to the team, decided when it is
3//! remembered (3.12.3): `ctx_knowledge remember` and `lean-ctx knowledge
4//! remember` say `"local only: <reason>"` with how to fix it, instead of a
5//! plain OK that the capture gate later turns into a silent rejection.
6//!
7//! This checks what a person or agent can fix now (the statement rules and
8//! a missing reference); the gate makes the final decision at sync (it
9//! also checks that each reference exists, screening, budget).
10
11use serde::Serialize;
12
13use super::{ReasonCode, rules};
14use crate::state::CloudStore;
15
16/// Where a remembered fact goes.
17#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
18#[serde(tag = "state", rename_all = "snake_case")]
19pub enum Sharing {
20    /// Goes to the vault with the next sync (once its sources check out).
21    NextSync { vault: String },
22    /// Stays on this machine: the gate would reject it for `reason`.
23    LocalOnly {
24        reason: ReasonCode,
25        hint: &'static str,
26    },
27    /// Sharing knowledge is switched off on this machine.
28    Off,
29    /// The project is not shared with the workspace yet.
30    NotShared,
31}
32
33impl Sharing {
34    /// The line under a `remember` answer; `org` names the workspace.
35    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
54/// The statement rules and the reference rule for `value`; `has_ref`: the
55/// call named a source (refs or anchors), or the fact already has anchors.
56pub 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
62/// Where `value`, just remembered in `project_root`, goes. `None` on a
63/// machine not connected to Cloud (nothing to say).
64pub 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    // An unlinked folder is not shared, also not through its main
82    // checkout's record (bd 40060).
83    // The map as the connected Cloud and account see it (rc3-81).
84    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
95/// [`decide`] for this machine, as the line under a `remember` answer
96/// (`None`: not connected to Cloud). `has_ref` as in [`problem`]; a fact
97/// LeanCTX anchored to code carries that reference itself.
98pub 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
112// ---------------------------------------------------------------------------
113// Facts the gate kept local at sync, for the sync status (local only).
114
115/// At most this many rejected facts are kept per vault (the newest).
116pub const MAX_REJECTED: usize = 200;
117
118/// One fact the capture gate kept on this machine.
119#[derive(Debug, Clone, PartialEq, Eq, Serialize, serde::Deserialize)]
120pub struct RejectedFact {
121    pub category: String,
122    pub key: String,
123    pub reason: ReasonCode,
124    /// How to fix it ([`ReasonCode::plain`]).
125    #[serde(default)]
126    pub hint: String,
127    /// When the gate rejected it (RFC 3339).
128    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
146/// Note what the gate refused in one sync of `vault_id` (`dropped` as
147/// [`crate::knowledge::learn::LearnPlan::dropped`]: `category/key`,
148/// reason). A fact refused again replaces its earlier row.
149pub 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    // Only what a person or agent can fix; a duplicate or a full batch is
156    // no rejection of the fact.
157    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
192/// The rejected facts of `vault_id` still waiting for a fix: the fact is
193/// current in `knowledge` and was not changed since (a changed fact is
194/// considered again by the next sync).
195pub 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    /// bd 40060: a remember in an unlinked worktree never says it goes to
288    /// the vault of the main checkout.
289    #[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}