1use 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
31const SAVE_DEBOUNCE_MINUTES: i64 = 10;
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum Trigger {
37 SessionEnd,
38 Save,
39 Shutdown,
40}
41
42#[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
51pub struct QueuedDraft {
52 pub stable_identity: String,
54 pub root: String,
56 pub draft: DraftProposalV1,
57 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
62 pub ref_keyed: bool,
63}
64
65impl QueuedDraft {
66 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
81pub(crate) const LEGACY_WATERMARK_DIR: &str = "drafts";
83pub(crate) const WATERMARK_DIR: &str = "capture";
85pub(crate) const WATERMARK_EXT: &str = "watermark";
86
87pub(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
102fn 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
127pub(crate) fn reset_watermark(data_dir: &Path, stable: &str) -> Result<(), CloudError> {
131 save_watermark(data_dir, stable, &Watermark::default())
132}
133
134pub 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
146fn 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
166pub 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
178pub 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
193fn 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 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 if crate::bus::relay_v2::speaks_v2(store) {
218 return nothing();
219 }
220 let data = store.data_dir();
221 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#[derive(Debug, Clone, Default)]
298pub struct Recapture {
299 pub removed: usize,
301 pub queued: Vec<String>,
303 pub counts: capture::CaptureCounts,
304}
305
306pub 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 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 done.counts
354 .rejected
355 .remove(&capture::ReasonCode::BudgetBatchFull);
356 Ok(done)
357}
358
359pub 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
383pub 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;