Skip to main content

lean_ctx_cloud/knowledge/
draft.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Captured session knowledge → one draft proposal in the outbox.
3//!
4//! Every fact passes the capture gate first ([`crate::capture`]);
5//! what fails stays local and is only counted. Runs at session end, on `ctx_session save` (debounced 10 min per
6//! project) and at server shutdown. It never touches the network: the
7//! draft is planned against the last pulled base, screened, and queued;
8//! [`super::pull`] / the scheduler send it later.
9
10use std::path::Path;
11
12use lean_ctx_time::{Duration, UtcDateTime};
13use serde::{Deserialize, Serialize};
14use serde_json::Value;
15use sha2::{Digest, Sha256};
16
17use super::learn::plan_learn;
18use super::screening::Screen;
19use super::{BaseRevision, load_base};
20use crate::CloudError;
21use crate::capture;
22use crate::config::CloudConfig;
23use crate::outbox::{CHANNEL_KNOWLEDGE, Outbox};
24use crate::state::{CloudStore, write_private};
25use crate::vault::{VaultMap, project_identity};
26use lean_ctx_protocol::cloud::knowledge::{
27    ContextPatchV1, DRAFT_PROPOSAL_SCHEMA, DraftProposalV1, MAX_PATCH_OPS, PatchOpV1, ProposalState,
28};
29use lean_ctx_protocol::cloud::vault::stable_identity;
30
31/// `ctx_session save` drafts at most this often per project.
32const SAVE_DEBOUNCE_MINUTES: i64 = 10;
33
34/// Why a draft is being made.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum Trigger {
37    SessionEnd,
38    Save,
39    Shutdown,
40}
41
42/// Where the next draft of a project starts.
43#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
44pub struct Watermark {
45    pub since: Option<UtcDateTime>,
46    pub last_draft_at: Option<UtcDateTime>,
47}
48
49/// The payload of a knowledge outbox item.
50#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
51pub struct QueuedDraft {
52    /// `stable_identity` of the project (never leaves the machine as such).
53    pub stable_identity: String,
54    /// Local checkout the draft came from, to resolve the project later.
55    pub root: String,
56    pub draft: DraftProposalV1,
57    /// The draft's `session_ref` is keyed under the local receipts key
58    /// ([`crate::session_ref::uploaded_ses_ref`]). Absent on a draft queued
59    /// before refs were keyed: its unsalted digest is re-keyed before it is
60    /// sent ([`QueuedDraft::rekey_legacy_ref`]).
61    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
62    pub ref_keyed: bool,
63}
64
65impl QueuedDraft {
66    /// Key the `session_ref` of a draft queued before refs were keyed (the
67    /// queue holds only its unsalted digest, never the session id), so no
68    /// guessable digest is sent. Returns whether it changed; an error (no
69    /// local key) keeps the draft queued.
70    pub fn rekey_legacy_ref(&mut self, cloud_data: &Path) -> Result<bool, CloudError> {
71        if self.ref_keyed {
72            return Ok(false);
73        }
74        self.draft.session_ref =
75            crate::session_ref::rekeyed_legacy_ref(cloud_data, &self.draft.session_ref)?;
76        self.ref_keyed = true;
77        Ok(true)
78    }
79}
80
81/// 3.11.5 kept a project's watermark in `<data>/cloud/drafts/<stable>.watermark`.
82pub(crate) const LEGACY_WATERMARK_DIR: &str = "drafts";
83/// 3.12: `<data>/cloud/capture/<place>.watermark` (SPEC-ENGINE §3.16).
84pub(crate) const WATERMARK_DIR: &str = "capture";
85pub(crate) const WATERMARK_EXT: &str = "watermark";
86
87/// The place a project's capture state is kept under: its vault once it is
88/// bound, the project itself before (as [`capture::open_run`]).
89pub(crate) fn watermark_place(data_dir: &Path, stable: &str) -> String {
90    VaultMap::load(data_dir)
91        .vaults
92        .get(stable)
93        .map_or_else(|| stable.to_string(), |r| r.vault_id.clone())
94}
95
96fn read_watermark(path: &Path) -> Option<Watermark> {
97    std::fs::read(path)
98        .ok()
99        .and_then(|b| serde_json::from_slice(&b).ok())
100}
101
102/// The vault's watermark; before the upgrade moved it (or before the
103/// project was bound), the one kept under the project.
104fn load_watermark(data_dir: &Path, stable: &str) -> Watermark {
105    let name = |place: &str| format!("{place}.{WATERMARK_EXT}");
106    let place = watermark_place(data_dir, stable);
107    [
108        data_dir.join(WATERMARK_DIR).join(name(&place)),
109        data_dir.join(WATERMARK_DIR).join(name(stable)),
110        data_dir.join(LEGACY_WATERMARK_DIR).join(name(stable)),
111    ]
112    .iter()
113    .find_map(|path| read_watermark(path))
114    .unwrap_or_default()
115}
116
117fn save_watermark(data_dir: &Path, stable: &str, mark: &Watermark) -> Result<(), CloudError> {
118    let bytes = serde_json::to_vec(mark).map_err(|e| CloudError::Local(e.to_string()))?;
119    let place = watermark_place(data_dir, stable);
120    write_private(
121        &data_dir.join(WATERMARK_DIR),
122        &format!("{place}.{WATERMARK_EXT}"),
123        &bytes,
124    )
125}
126
127/// Start the capture of the project `stable` from the beginning again, as
128/// [`recapture`] does: `cloud unlink` dropped its unsent drafts, so their
129/// facts are captured again once the folder is shared again (rc4-6).
130pub(crate) fn reset_watermark(data_dir: &Path, stable: &str) -> Result<(), CloudError> {
131    save_watermark(data_dir, stable, &Watermark::default())
132}
133
134/// An opaque per-session reference: no host, user or path data. It is an
135/// unsalted digest, so a guessable session id can be tested against it:
136/// it names sessions locally (file names, done markers) and, uploaded, only
137/// constant labels that name no session (`cloud-link`,
138/// `cloud-task-proposals`). What is uploaded for a session, or for a label
139/// passed in its place (`cli-import`, `emspace-import`), is
140/// [`crate::session_ref::uploaded_ses_ref`].
141pub fn session_ref(session_id: &str) -> String {
142    let digest = Sha256::digest(format!("leanctx.cloud.session.v1\n{session_id}").as_bytes());
143    format!("ses_{}", hex::encode(&digest[..12]))
144}
145
146/// Summary and body of a draft: every fact passed the capture gate, so each
147/// is one complete claim and is listed whole (a procedure by its title).
148fn summary_and_body(ops: &[PatchOpV1]) -> (String, String) {
149    let summary = match ops.len() {
150        1 => "Captured 1 fact".to_string(),
151        n => format!("Captured {n} facts"),
152    };
153    let mut body = format!(
154        "Captured in a lean-ctx session (capture gate v{}):\n",
155        capture::GATE_VERSION
156    );
157    for op in ops {
158        if let PatchOpV1::AddFact { fact } = op {
159            let claim = fact.statement.lines().next().unwrap_or_default();
160            body.push_str(&format!("- {claim}\n"));
161        }
162    }
163    (summary, body)
164}
165
166/// Whether the project `stable` at `root` syncs through its vault's C0 2.0
167/// replica, as `cloud sync` decides: the enrolled Cloud speaks 2.0 and the
168/// project is bound (or linked, and bound on its next sync). A 1.x Cloud
169/// keeps the draft path.
170pub fn syncs_through_replica(store: &CloudStore, stable: &str, root: &Path) -> bool {
171    crate::bus::relay_v2::speaks_v2(store)
172        && (VaultMap::load(store.data_dir()).vaults.contains_key(stable)
173            || crate::link::has_link_file(root))
174}
175
176/// Plan, screen and queue the learnings of the project at `root` made since
177/// its last draft. Returns the outbox id, or `None` when there is nothing
178/// to propose (or Cloud is not set up for this machine).
179pub fn enqueue_session_draft(
180    store: &CloudStore,
181    config: &CloudConfig,
182    root: &Path,
183    session_id: &str,
184    trigger: Trigger,
185    screen: &mut Screen,
186    now: UtcDateTime,
187) -> Result<Option<String>, CloudError> {
188    capture_session(store, config, root, session_id, trigger, screen, now).map(|(id, _)| id)
189}
190
191/// [`enqueue_session_draft`], also returning what the capture run counted.
192fn capture_session(
193    store: &CloudStore,
194    config: &CloudConfig,
195    root: &Path,
196    session_id: &str,
197    trigger: Trigger,
198    screen: &mut Screen,
199    now: UtcDateTime,
200) -> Result<(Option<String>, capture::CaptureCounts), CloudError> {
201    let nothing = || Ok((None, capture::CaptureCounts::default()));
202    if config.enabled == Some(false) || !config.auto_capture || store.instance()?.is_none() {
203        return nothing();
204    }
205    // A folder the person stopped sharing (`cloud unlink`) queues no draft.
206    if crate::unlinked::contains(store.data_dir(), root) {
207        return nothing();
208    }
209    let Some(identity) = project_identity(root) else {
210        return nothing();
211    };
212    let stable = stable_identity(&identity);
213    // A C0 2.0 Cloud gets knowledge only as signed events (`cloud sync`),
214    // and only into a linked or bound vault: it takes no 1.x draft.
215    if crate::bus::relay_v2::speaks_v2(store) {
216        return nothing();
217    }
218    let data = store.data_dir();
219    // Without the local key nothing naming the session is uploaded: the
220    // draft is not queued and the watermark stays, so a later run retries.
221    let session_ref = crate::session_ref::uploaded_ses_ref(data, session_id)?;
222    let mut mark = load_watermark(data, &stable);
223    if trigger == Trigger::Save
224        && mark
225            .last_draft_at
226            .is_some_and(|at| now - at < Duration::minutes(SAVE_DEBOUNCE_MINUTES))
227    {
228        return nothing();
229    }
230    let Some(knowledge) =
231        lean_ctx::core::knowledge::ProjectKnowledge::load(&root.to_string_lossy())
232    else {
233        return nothing();
234    };
235    let base: BaseRevision = VaultMap::load(data)
236        .vaults
237        .get(&stable)
238        .map(|record| load_base(data, &record.vault_id))
239        .unwrap_or_default();
240    let (mut run, place) = capture::open_run(data, &stable, root, screen, now.timestamp_millis());
241    let plan = plan_learn(
242        &knowledge,
243        &base.document,
244        mark.since,
245        MAX_PATCH_OPS,
246        &mut run,
247    );
248    capture::finish_run(data, &place, &run)?;
249    let screening = run.screen.counts();
250    let counts = run.counts.clone();
251    if plan.watermark.is_some() {
252        mark.since = plan.watermark;
253    }
254    if plan.added.is_empty() {
255        save_watermark(data, &stable, &mark)?;
256        return Ok((None, counts));
257    }
258    let ops: Vec<PatchOpV1> = plan
259        .added
260        .into_iter()
261        .map(|fact| PatchOpV1::AddFact { fact })
262        .collect();
263    let (summary, body) = summary_and_body(&ops);
264    let draft = DraftProposalV1 {
265        schema: DRAFT_PROPOSAL_SCHEMA.into(),
266        state: ProposalState::Draft,
267        summary: Some(summary),
268        body: Some(body),
269        sources: Vec::new(),
270        context_patch: ContextPatchV1 {
271            base_revision: base.revision,
272            ops,
273        },
274        session_ref,
275        engine_screening: screening,
276        origin: None,
277    };
278    draft
279        .validate()
280        .map_err(|e| CloudError::Protocol(format!("draft: {e}")))?;
281    let payload = serde_json::to_value(QueuedDraft {
282        stable_identity: stable.clone(),
283        root: root.to_string_lossy().into_owned(),
284        draft,
285        ref_keyed: true,
286    })
287    .map_err(|e| CloudError::Local(e.to_string()))?;
288    let id = Outbox::at(data).enqueue(CHANNEL_KNOWLEDGE, payload, now)?;
289    mark.last_draft_at = Some(now);
290    save_watermark(data, &stable, &mark)?;
291    Ok((Some(id), counts))
292}
293
294/// What [`recapture`] did.
295#[derive(Debug, Clone, Default)]
296pub struct Recapture {
297    /// Unsent session drafts of the project it removed.
298    pub removed: usize,
299    /// Drafts it queued instead.
300    pub queued: Vec<String>,
301    pub counts: capture::CaptureCounts,
302}
303
304/// `lean-ctx cloud capture --recapture` (SPEC-ENGINE §3.1.6): remove the
305/// project's unsent session drafts (they never reached members), reset its
306/// capture watermark and run the gate over the whole local knowledge.
307pub fn recapture(
308    store: &CloudStore,
309    config: &CloudConfig,
310    root: &Path,
311    screen: &mut Screen,
312    now: UtcDateTime,
313) -> Result<Recapture, CloudError> {
314    let identity = project_identity(root)
315        .ok_or_else(|| CloudError::Config("not inside a git repository".into()))?;
316    let stable = stable_identity(&identity);
317    let data = store.data_dir();
318    let outbox = Outbox::at(data);
319    let mut done = Recapture::default();
320    for item in outbox.list(CHANNEL_KNOWLEDGE) {
321        if queued(&item.payload)
322            .is_some_and(|q| q.stable_identity == stable && q.draft.origin.is_none())
323        {
324            outbox.remove(&item)?;
325            done.removed += 1;
326        }
327    }
328    save_watermark(data, &stable, &Watermark::default())?;
329    // A run queues at most one draft of `MAX_PATCH_OPS` facts; the next
330    // continues after it.
331    loop {
332        let (id, counts) = capture_session(
333            store,
334            config,
335            root,
336            "cli-recapture",
337            Trigger::SessionEnd,
338            screen,
339            now,
340        )?;
341        done.counts.absorb(&counts);
342        let full = counts
343            .rejected
344            .contains_key(&capture::ReasonCode::BudgetBatchFull);
345        done.queued.extend(id);
346        if !full {
347            break;
348        }
349    }
350    // A batch that was full is continued, not rejected.
351    done.counts
352        .rejected
353        .remove(&capture::ReasonCode::BudgetBatchFull);
354    Ok(done)
355}
356
357/// Hook for session end, save and shutdown: enqueue only, never network,
358/// never an error for the caller (a failure is recorded for `cloud status`).
359pub fn on_session_event(project_root: &str, session_id: &str, trigger: Trigger) {
360    let Ok(store) = CloudStore::open() else {
361        return;
362    };
363    if !matches!(store.instance(), Ok(Some(_))) {
364        return;
365    }
366    let config = lean_ctx::core::config::Config::load().cloud.clone();
367    let mut screen = Screen::for_installation();
368    if let Err(error) = enqueue_session_draft(
369        &store,
370        &config,
371        Path::new(project_root),
372        session_id,
373        trigger,
374        &mut screen,
375        UtcDateTime::now(),
376    ) {
377        store.record_error(&format!("draft: {error}"));
378    }
379}
380
381/// The draft inside a queued item, for status listings.
382pub fn queued(payload: &Value) -> Option<QueuedDraft> {
383    serde_json::from_value(payload.clone()).ok()
384}
385
386#[cfg(test)]
387#[path = "draft_tests.rs"]
388mod tests;