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/// An opaque per-session reference: no host, user or path data. It is an
128/// unsalted digest, so a guessable session id can be tested against it:
129/// it names sessions locally (file names, done markers) and, uploaded, only
130/// constant labels that name no session (`cloud-link`,
131/// `cloud-task-proposals`). What is uploaded for a session, or for a label
132/// passed in its place (`cli-import`, `emspace-import`), is
133/// [`crate::session_ref::uploaded_ses_ref`].
134pub fn session_ref(session_id: &str) -> String {
135    let digest = Sha256::digest(format!("leanctx.cloud.session.v1\n{session_id}").as_bytes());
136    format!("ses_{}", hex::encode(&digest[..12]))
137}
138
139/// Summary and body of a draft: every fact passed the capture gate, so each
140/// is one complete claim and is listed whole (a procedure by its title).
141fn summary_and_body(ops: &[PatchOpV1]) -> (String, String) {
142    let summary = match ops.len() {
143        1 => "Captured 1 fact".to_string(),
144        n => format!("Captured {n} facts"),
145    };
146    let mut body = format!(
147        "Captured in a lean-ctx session (capture gate v{}):\n",
148        capture::GATE_VERSION
149    );
150    for op in ops {
151        if let PatchOpV1::AddFact { fact } = op {
152            let claim = fact.statement.lines().next().unwrap_or_default();
153            body.push_str(&format!("- {claim}\n"));
154        }
155    }
156    (summary, body)
157}
158
159/// Whether the project `stable` at `root` syncs through its vault's C0 2.0
160/// replica, as `cloud sync` decides: the enrolled Cloud speaks 2.0 and the
161/// project is bound (or linked, and bound on its next sync). A 1.x Cloud
162/// keeps the draft path.
163pub fn syncs_through_replica(store: &CloudStore, stable: &str, root: &Path) -> bool {
164    crate::bus::relay_v2::speaks_v2(store)
165        && (VaultMap::load(store.data_dir()).vaults.contains_key(stable)
166            || crate::link::has_link_file(root))
167}
168
169/// Plan, screen and queue the learnings of the project at `root` made since
170/// its last draft. Returns the outbox id, or `None` when there is nothing
171/// to propose (or Cloud is not set up for this machine).
172pub fn enqueue_session_draft(
173    store: &CloudStore,
174    config: &CloudConfig,
175    root: &Path,
176    session_id: &str,
177    trigger: Trigger,
178    screen: &mut Screen,
179    now: UtcDateTime,
180) -> Result<Option<String>, CloudError> {
181    capture_session(store, config, root, session_id, trigger, screen, now).map(|(id, _)| id)
182}
183
184/// [`enqueue_session_draft`], also returning what the capture run counted.
185fn capture_session(
186    store: &CloudStore,
187    config: &CloudConfig,
188    root: &Path,
189    session_id: &str,
190    trigger: Trigger,
191    screen: &mut Screen,
192    now: UtcDateTime,
193) -> Result<(Option<String>, capture::CaptureCounts), CloudError> {
194    let nothing = || Ok((None, capture::CaptureCounts::default()));
195    if config.enabled == Some(false) || !config.auto_capture || store.instance()?.is_none() {
196        return nothing();
197    }
198    let Some(identity) = project_identity(root) else {
199        return nothing();
200    };
201    let stable = stable_identity(&identity);
202    // A C0 2.0 Cloud gets knowledge only as signed events (`cloud sync`),
203    // and only into a linked or bound vault: it takes no 1.x draft.
204    if crate::bus::relay_v2::speaks_v2(store) {
205        return nothing();
206    }
207    let data = store.data_dir();
208    // Without the local key nothing naming the session is uploaded: the
209    // draft is not queued and the watermark stays, so a later run retries.
210    let session_ref = crate::session_ref::uploaded_ses_ref(data, session_id)?;
211    let mut mark = load_watermark(data, &stable);
212    if trigger == Trigger::Save
213        && mark
214            .last_draft_at
215            .is_some_and(|at| now - at < Duration::minutes(SAVE_DEBOUNCE_MINUTES))
216    {
217        return nothing();
218    }
219    let Some(knowledge) =
220        lean_ctx::core::knowledge::ProjectKnowledge::load(&root.to_string_lossy())
221    else {
222        return nothing();
223    };
224    let base: BaseRevision = VaultMap::load(data)
225        .vaults
226        .get(&stable)
227        .map(|record| load_base(data, &record.vault_id))
228        .unwrap_or_default();
229    let (mut run, place) = capture::open_run(data, &stable, root, screen, now.timestamp_millis());
230    let plan = plan_learn(
231        &knowledge,
232        &base.document,
233        mark.since,
234        MAX_PATCH_OPS,
235        &mut run,
236    );
237    capture::finish_run(data, &place, &run)?;
238    let screening = run.screen.counts();
239    let counts = run.counts.clone();
240    if plan.watermark.is_some() {
241        mark.since = plan.watermark;
242    }
243    if plan.added.is_empty() {
244        save_watermark(data, &stable, &mark)?;
245        return Ok((None, counts));
246    }
247    let ops: Vec<PatchOpV1> = plan
248        .added
249        .into_iter()
250        .map(|fact| PatchOpV1::AddFact { fact })
251        .collect();
252    let (summary, body) = summary_and_body(&ops);
253    let draft = DraftProposalV1 {
254        schema: DRAFT_PROPOSAL_SCHEMA.into(),
255        state: ProposalState::Draft,
256        summary: Some(summary),
257        body: Some(body),
258        sources: Vec::new(),
259        context_patch: ContextPatchV1 {
260            base_revision: base.revision,
261            ops,
262        },
263        session_ref,
264        engine_screening: screening,
265        origin: None,
266    };
267    draft
268        .validate()
269        .map_err(|e| CloudError::Protocol(format!("draft: {e}")))?;
270    let payload = serde_json::to_value(QueuedDraft {
271        stable_identity: stable.clone(),
272        root: root.to_string_lossy().into_owned(),
273        draft,
274        ref_keyed: true,
275    })
276    .map_err(|e| CloudError::Local(e.to_string()))?;
277    let id = Outbox::at(data).enqueue(CHANNEL_KNOWLEDGE, payload, now)?;
278    mark.last_draft_at = Some(now);
279    save_watermark(data, &stable, &mark)?;
280    Ok((Some(id), counts))
281}
282
283/// What [`recapture`] did.
284#[derive(Debug, Clone, Default)]
285pub struct Recapture {
286    /// Unsent session drafts of the project it removed.
287    pub removed: usize,
288    /// Drafts it queued instead.
289    pub queued: Vec<String>,
290    pub counts: capture::CaptureCounts,
291}
292
293/// `lean-ctx cloud capture --recapture` (SPEC-ENGINE §3.1.6): remove the
294/// project's unsent session drafts (they never reached members), reset its
295/// capture watermark and run the gate over the whole local knowledge.
296pub fn recapture(
297    store: &CloudStore,
298    config: &CloudConfig,
299    root: &Path,
300    screen: &mut Screen,
301    now: UtcDateTime,
302) -> Result<Recapture, CloudError> {
303    let identity = project_identity(root)
304        .ok_or_else(|| CloudError::Config("not inside a git repository".into()))?;
305    let stable = stable_identity(&identity);
306    let data = store.data_dir();
307    let outbox = Outbox::at(data);
308    let mut done = Recapture::default();
309    for item in outbox.list(CHANNEL_KNOWLEDGE) {
310        if queued(&item.payload)
311            .is_some_and(|q| q.stable_identity == stable && q.draft.origin.is_none())
312        {
313            outbox.remove(&item)?;
314            done.removed += 1;
315        }
316    }
317    save_watermark(data, &stable, &Watermark::default())?;
318    // A run queues at most one draft of `MAX_PATCH_OPS` facts; the next
319    // continues after it.
320    loop {
321        let (id, counts) = capture_session(
322            store,
323            config,
324            root,
325            "cli-recapture",
326            Trigger::SessionEnd,
327            screen,
328            now,
329        )?;
330        done.counts.absorb(&counts);
331        let full = counts
332            .rejected
333            .contains_key(&capture::ReasonCode::BudgetBatchFull);
334        done.queued.extend(id);
335        if !full {
336            break;
337        }
338    }
339    // A batch that was full is continued, not rejected.
340    done.counts
341        .rejected
342        .remove(&capture::ReasonCode::BudgetBatchFull);
343    Ok(done)
344}
345
346/// Hook for session end, save and shutdown: enqueue only, never network,
347/// never an error for the caller (a failure is recorded for `cloud status`).
348pub fn on_session_event(project_root: &str, session_id: &str, trigger: Trigger) {
349    let Ok(store) = CloudStore::open() else {
350        return;
351    };
352    if !matches!(store.instance(), Ok(Some(_))) {
353        return;
354    }
355    let config = lean_ctx::core::config::Config::load().cloud.clone();
356    let mut screen = Screen::for_installation();
357    if let Err(error) = enqueue_session_draft(
358        &store,
359        &config,
360        Path::new(project_root),
361        session_id,
362        trigger,
363        &mut screen,
364        UtcDateTime::now(),
365    ) {
366        store.record_error(&format!("draft: {error}"));
367    }
368}
369
370/// The draft inside a queued item, for status listings.
371pub fn queued(payload: &Value) -> Option<QueuedDraft> {
372    serde_json::from_value(payload.clone()).ok()
373}
374
375#[cfg(test)]
376#[path = "draft_tests.rs"]
377mod tests;