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;
15use crate::vault::VaultMap;
16
17/// Where a remembered fact goes.
18#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
19#[serde(tag = "state", rename_all = "snake_case")]
20pub enum Sharing {
21    /// Goes to the vault with the next sync (once its sources check out).
22    NextSync { vault: String },
23    /// Stays on this machine: the gate would reject it for `reason`.
24    LocalOnly {
25        reason: ReasonCode,
26        hint: &'static str,
27    },
28    /// Sharing knowledge is switched off on this machine.
29    Off,
30    /// The project is not shared with the workspace yet.
31    NotShared,
32}
33
34impl Sharing {
35    /// The line under a `remember` answer; `org` names the workspace.
36    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
55/// The statement rules and the reference rule for `value`; `has_ref`: the
56/// call named a source (refs or anchors), or the fact already has anchors.
57pub 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
63/// Where `value`, just remembered in `project_root`, goes. `None` on a
64/// machine not connected to Cloud (nothing to say).
65pub 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    Some(
83        match VaultMap::load(store.data_dir()).for_root(project_root) {
84            Some(vault) => Sharing::NextSync {
85                vault: format!("{}/{}", vault.ns, vault.name),
86            },
87            None => Sharing::NotShared,
88        },
89    )
90}
91
92/// [`decide`] for this machine, as the line under a `remember` answer
93/// (`None`: not connected to Cloud). `has_ref` as in [`problem`]; a fact
94/// LeanCTX anchored to code carries that reference itself.
95pub fn note(project_root: &str, value: &str, has_ref: bool) -> Option<String> {
96    let store = CloudStore::open().ok()?;
97    let instance = store.instance().ok().flatten()?;
98    let anchored =
99        lean_ctx::core::knowledge::ProjectKnowledge::load(project_root).is_some_and(|k| {
100            k.facts
101                .iter()
102                .any(|f| f.is_current() && f.value == value && !f.anchors.is_empty())
103        });
104    let config = lean_ctx::core::config::Config::load().cloud.clone();
105    decide(&store, &config, project_root, value, has_ref || anchored)
106        .map(|sharing| sharing.line(&instance.org_name))
107}
108
109// ---------------------------------------------------------------------------
110// Facts the gate kept local at sync, for the sync status (local only).
111
112/// At most this many rejected facts are kept per vault (the newest).
113pub const MAX_REJECTED: usize = 200;
114
115/// One fact the capture gate kept on this machine.
116#[derive(Debug, Clone, PartialEq, Eq, Serialize, serde::Deserialize)]
117pub struct RejectedFact {
118    pub category: String,
119    pub key: String,
120    pub reason: ReasonCode,
121    /// How to fix it ([`ReasonCode::plain`]).
122    #[serde(default)]
123    pub hint: String,
124    /// When the gate rejected it (RFC 3339).
125    pub at: String,
126}
127
128fn rejected_file(vault_id: &str) -> String {
129    let name: String = vault_id
130        .chars()
131        .filter(|c| c.is_ascii_alphanumeric() || *c == '-')
132        .collect();
133    format!("{name}.rejected.json")
134}
135
136fn load_rejected(data_dir: &std::path::Path, vault_id: &str) -> Vec<RejectedFact> {
137    std::fs::read(data_dir.join("capture").join(rejected_file(vault_id)))
138        .ok()
139        .and_then(|b| serde_json::from_slice(&b).ok())
140        .unwrap_or_default()
141}
142
143/// Note what the gate refused in one sync of `vault_id` (`dropped` as
144/// [`crate::knowledge::learn::LearnPlan::dropped`]: `category/key`,
145/// reason). A fact refused again replaces its earlier row.
146pub fn record_rejected(
147    data_dir: &std::path::Path,
148    vault_id: &str,
149    dropped: &[(String, ReasonCode)],
150    now: lean_ctx_time::UtcDateTime,
151) {
152    // Only what a person or agent can fix; a duplicate or a full batch is
153    // no rejection of the fact.
154    let fixable = |reason: &ReasonCode| {
155        !matches!(
156            reason,
157            ReasonCode::Duplicate | ReasonCode::NearDuplicateMerged | ReasonCode::BudgetBatchFull
158        )
159    };
160    if dropped.iter().all(|(_, r)| !fixable(r)) {
161        return;
162    }
163    let at = now.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true);
164    let mut rows = load_rejected(data_dir, vault_id);
165    for (label, reason) in dropped.iter().filter(|(_, r)| fixable(r)) {
166        let (category, key) = label.split_once('/').unwrap_or((label.as_str(), ""));
167        rows.retain(|row| !(row.category == category && row.key == key));
168        rows.push(RejectedFact {
169            category: category.to_owned(),
170            key: key.to_owned(),
171            reason: *reason,
172            hint: reason.plain().to_owned(),
173            at: at.clone(),
174        });
175    }
176    if rows.len() > MAX_REJECTED {
177        let extra = rows.len() - MAX_REJECTED;
178        rows.drain(..extra);
179    }
180    if let Ok(bytes) = serde_json::to_vec(&rows) {
181        let _ = crate::state::write_private(
182            &data_dir.join("capture"),
183            &rejected_file(vault_id),
184            &bytes,
185        );
186    }
187}
188
189/// The rejected facts of `vault_id` still waiting for a fix: the fact is
190/// current in `knowledge` and was not changed since (a changed fact is
191/// considered again by the next sync).
192pub fn rejected_now(
193    data_dir: &std::path::Path,
194    vault_id: &str,
195    knowledge: Option<&lean_ctx::core::knowledge::ProjectKnowledge>,
196) -> Vec<RejectedFact> {
197    let rows = load_rejected(data_dir, vault_id);
198    let Some(knowledge) = knowledge else {
199        return rows;
200    };
201    rows.into_iter()
202        .filter(|row| {
203            let Ok(at) = lean_ctx_time::OffsetDateTime::parse_from_rfc3339(&row.at) else {
204                return true;
205            };
206            knowledge.facts.iter().any(|f| {
207                f.is_current() && f.category == row.category && f.key == row.key && {
208                    let changed = f
209                        .capture
210                        .changed_at
211                        .map_or(f.created_at, |c| c.max(f.created_at));
212                    changed <= at
213                }
214            })
215        })
216        .collect()
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222
223    #[test]
224    fn rejections_are_kept_per_fact_and_only_the_fixable_ones() {
225        let dir = tempfile::tempdir().unwrap();
226        let now = lean_ctx_time::UtcDateTime::now();
227        record_rejected(
228            dir.path(),
229            "v-1",
230            &[
231                ("gotcha/a".into(), ReasonCode::NotSentence),
232                ("gotcha/b".into(), ReasonCode::Duplicate),
233            ],
234            now,
235        );
236        record_rejected(
237            dir.path(),
238            "v-1",
239            &[("gotcha/a".into(), ReasonCode::NoReference)],
240            now,
241        );
242        let rows = rejected_now(dir.path(), "v-1", None);
243        assert_eq!(rows.len(), 1);
244        assert_eq!(
245            (rows[0].category.as_str(), rows[0].key.as_str()),
246            ("gotcha", "a")
247        );
248        assert_eq!(rows[0].reason, ReasonCode::NoReference);
249        assert!(rows[0].hint.contains("--ref"));
250        assert!(rejected_now(dir.path(), "v-2", None).is_empty());
251    }
252
253    #[test]
254    fn a_fragment_or_a_fact_without_a_source_stays_local_with_the_fix() {
255        assert_eq!(
256            problem("not a sentence, just a lowercase fragment here", true),
257            Some(ReasonCode::NotSentence)
258        );
259        assert_eq!(problem("Too short.", true), Some(ReasonCode::TooShort));
260        assert_eq!(
261            problem(
262                "The daemon syncs every shared vault in the background.",
263                false
264            ),
265            Some(ReasonCode::NoReference)
266        );
267        assert_eq!(
268            problem(
269                "The daemon syncs every shared vault in the background.",
270                true
271            ),
272            None
273        );
274        let local = Sharing::LocalOnly {
275            reason: ReasonCode::NoReference,
276            hint: ReasonCode::NoReference.plain(),
277        };
278        let line = local.line("Acme");
279        assert!(line.contains("local only: no_reference"), "{line}");
280        assert!(line.contains("--ref file:"), "the fix is named: {line}");
281    }
282
283    #[test]
284    fn not_connected_says_nothing() {
285        let dir = tempfile::tempdir().unwrap();
286        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
287        assert_eq!(
288            decide(
289                &store,
290                &crate::CloudConfig::default(),
291                "/x",
292                "not a sentence",
293                false
294            ),
295            None
296        );
297    }
298
299    #[test]
300    fn the_json_shape_names_state_reason_and_hint() {
301        let local = Sharing::LocalOnly {
302            reason: ReasonCode::NotSentence,
303            hint: ReasonCode::NotSentence.plain(),
304        };
305        let value = serde_json::to_value(&local).unwrap();
306        assert_eq!(value["state"], "local_only");
307        assert_eq!(value["reason"], "not_sentence");
308        assert!(value["hint"].as_str().unwrap().contains("capital letter"));
309        assert_eq!(
310            serde_json::to_value(Sharing::NextSync {
311                vault: "a/b".into()
312            })
313            .unwrap(),
314            serde_json::json!({"state": "next_sync", "vault": "a/b"})
315        );
316    }
317}