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        && (crate::vault::connected_map(store)
173            .vaults
174            .contains_key(stable)
175            || crate::link::has_link_file(root))
176}
177
178/// Plan, screen and queue the learnings of the project at `root` made since
179/// its last draft. Returns the outbox id, or `None` when there is nothing
180/// to propose (or Cloud is not set up for this machine).
181pub fn enqueue_session_draft(
182    store: &CloudStore,
183    config: &CloudConfig,
184    root: &Path,
185    session_id: &str,
186    trigger: Trigger,
187    screen: &mut Screen,
188    now: UtcDateTime,
189) -> Result<Option<String>, CloudError> {
190    capture_session(store, config, root, session_id, trigger, screen, now).map(|(id, _)| id)
191}
192
193/// [`enqueue_session_draft`], also returning what the capture run counted.
194fn capture_session(
195    store: &CloudStore,
196    config: &CloudConfig,
197    root: &Path,
198    session_id: &str,
199    trigger: Trigger,
200    screen: &mut Screen,
201    now: UtcDateTime,
202) -> Result<(Option<String>, capture::CaptureCounts), CloudError> {
203    let nothing = || Ok((None, capture::CaptureCounts::default()));
204    if config.enabled == Some(false) || !config.auto_capture || store.instance()?.is_none() {
205        return nothing();
206    }
207    // A folder the person stopped sharing (`cloud unlink`) queues no draft.
208    if crate::unlinked::contains(store.data_dir(), root) {
209        return nothing();
210    }
211    let Some(identity) = project_identity(root) else {
212        return nothing();
213    };
214    let stable = stable_identity(&identity);
215    // A C0 2.0 Cloud gets knowledge only as signed events (`cloud sync`),
216    // and only into a linked or bound vault: it takes no 1.x draft.
217    if crate::bus::relay_v2::speaks_v2(store) {
218        return nothing();
219    }
220    let data = store.data_dir();
221    // Without the local key nothing naming the session is uploaded: the
222    // draft is not queued and the watermark stays, so a later run retries.
223    let session_ref = crate::session_ref::uploaded_ses_ref(data, session_id)?;
224    let mut mark = load_watermark(data, &stable);
225    if trigger == Trigger::Save
226        && mark
227            .last_draft_at
228            .is_some_and(|at| now - at < Duration::minutes(SAVE_DEBOUNCE_MINUTES))
229    {
230        return nothing();
231    }
232    let Some(knowledge) =
233        lean_ctx::core::knowledge::ProjectKnowledge::load(&root.to_string_lossy())
234    else {
235        return nothing();
236    };
237    let base: BaseRevision = VaultMap::load(data)
238        .vaults
239        .get(&stable)
240        .map(|record| load_base(data, &record.vault_id))
241        .unwrap_or_default();
242    let (mut run, place) = capture::open_run(data, &stable, root, screen, now.timestamp_millis());
243    let plan = plan_learn(
244        &knowledge,
245        &base.document,
246        mark.since,
247        MAX_PATCH_OPS,
248        &mut run,
249    );
250    capture::finish_run(data, &place, &run)?;
251    let screening = run.screen.counts();
252    let counts = run.counts.clone();
253    if plan.watermark.is_some() {
254        mark.since = plan.watermark;
255    }
256    if plan.added.is_empty() {
257        save_watermark(data, &stable, &mark)?;
258        return Ok((None, counts));
259    }
260    let ops: Vec<PatchOpV1> = plan
261        .added
262        .into_iter()
263        .map(|fact| PatchOpV1::AddFact { fact })
264        .collect();
265    let (summary, body) = summary_and_body(&ops);
266    let draft = DraftProposalV1 {
267        schema: DRAFT_PROPOSAL_SCHEMA.into(),
268        state: ProposalState::Draft,
269        summary: Some(summary),
270        body: Some(body),
271        sources: Vec::new(),
272        context_patch: ContextPatchV1 {
273            base_revision: base.revision,
274            ops,
275        },
276        session_ref,
277        engine_screening: screening,
278        origin: None,
279    };
280    draft
281        .validate()
282        .map_err(|e| CloudError::Protocol(format!("draft: {e}")))?;
283    let payload = serde_json::to_value(QueuedDraft {
284        stable_identity: stable.clone(),
285        root: root.to_string_lossy().into_owned(),
286        draft,
287        ref_keyed: true,
288    })
289    .map_err(|e| CloudError::Local(e.to_string()))?;
290    let id = Outbox::at(data).enqueue(CHANNEL_KNOWLEDGE, payload, now)?;
291    mark.last_draft_at = Some(now);
292    save_watermark(data, &stable, &mark)?;
293    Ok((Some(id), counts))
294}
295
296/// What [`recapture`] did.
297#[derive(Debug, Clone, Default)]
298pub struct Recapture {
299    /// Unsent session drafts of the project it removed.
300    pub removed: usize,
301    /// Drafts it queued instead.
302    pub queued: Vec<String>,
303    pub counts: capture::CaptureCounts,
304}
305
306/// `lean-ctx cloud capture --recapture` (SPEC-ENGINE §3.1.6): remove the
307/// project's unsent session drafts (they never reached members), reset its
308/// capture watermark and run the gate over the whole local knowledge.
309pub fn recapture(
310    store: &CloudStore,
311    config: &CloudConfig,
312    root: &Path,
313    screen: &mut Screen,
314    now: UtcDateTime,
315) -> Result<Recapture, CloudError> {
316    let identity = project_identity(root)
317        .ok_or_else(|| CloudError::Config("not inside a git repository".into()))?;
318    let stable = stable_identity(&identity);
319    let data = store.data_dir();
320    let outbox = Outbox::at(data);
321    let mut done = Recapture::default();
322    for item in outbox.list(CHANNEL_KNOWLEDGE) {
323        if queued(&item.payload)
324            .is_some_and(|q| q.stable_identity == stable && q.draft.origin.is_none())
325        {
326            outbox.remove(&item)?;
327            done.removed += 1;
328        }
329    }
330    save_watermark(data, &stable, &Watermark::default())?;
331    // A run queues at most one draft of `MAX_PATCH_OPS` facts; the next
332    // continues after it.
333    loop {
334        let (id, counts) = capture_session(
335            store,
336            config,
337            root,
338            "cli-recapture",
339            Trigger::SessionEnd,
340            screen,
341            now,
342        )?;
343        done.counts.absorb(&counts);
344        let full = counts
345            .rejected
346            .contains_key(&capture::ReasonCode::BudgetBatchFull);
347        done.queued.extend(id);
348        if !full {
349            break;
350        }
351    }
352    // A batch that was full is continued, not rejected.
353    done.counts
354        .rejected
355        .remove(&capture::ReasonCode::BudgetBatchFull);
356    Ok(done)
357}
358
359/// Hook for session end, save and shutdown: enqueue only, never network,
360/// never an error for the caller (a failure is recorded for `cloud status`).
361pub fn on_session_event(project_root: &str, session_id: &str, trigger: Trigger) {
362    let Ok(store) = CloudStore::open() else {
363        return;
364    };
365    if !matches!(store.instance(), Ok(Some(_))) {
366        return;
367    }
368    let config = lean_ctx::core::config::Config::load().cloud.clone();
369    let mut screen = Screen::for_installation();
370    if let Err(error) = enqueue_session_draft(
371        &store,
372        &config,
373        Path::new(project_root),
374        session_id,
375        trigger,
376        &mut screen,
377        UtcDateTime::now(),
378    ) {
379        store.record_error(&format!("draft: {error}"));
380    }
381}
382
383/// The draft inside a queued item, for status listings.
384pub fn queued(payload: &Value) -> Option<QueuedDraft> {
385    serde_json::from_value(payload.clone()).ok()
386}
387
388#[cfg(test)]
389#[path = "draft_tests.rs"]
390mod tests;