Skip to main content

lean_ctx_cloud/knowledge/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Project knowledge with Cloud: session learnings stream out as draft
3//! proposals ([`draft`]), reviewed revisions stream back in ([`pull`]).
4//!
5//! The last pulled revision of each project is kept in
6//! `<data_dir>/cloud/knowledge/<vault_id>/base.json`; it is the base that
7//! drafts are computed and rebased against. Nothing is written into the
8//! user's project tree except the project knowledge store.
9
10pub mod code_graph;
11pub mod doc;
12pub mod draft;
13pub mod import_draft;
14pub mod learn;
15pub mod pull;
16pub mod screening;
17pub mod screening_exceptions;
18
19use std::path::Path;
20
21use serde::{Deserialize, Serialize};
22
23use super::CloudError;
24use super::state::write_private;
25use lean_ctx_protocol::cloud::knowledge::ResearchContextDocumentV1;
26use lean_ctx_protocol::cloud::validate_vault_id;
27
28/// The last revision pulled for a project: the delivered (released) head,
29/// the only one ever loaded into a checkout.
30#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
31pub struct BaseRevision {
32    pub revision: u64,
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub etag: Option<String>,
35    pub document: ResearchContextDocumentV1,
36    /// C0 1.9 ยง3: quarantined revisions Cloud holds after this head. They
37    /// never reach an agent here; the next merge writes on top of them.
38    #[serde(default, skip_serializing_if = "is_zero")]
39    pub quarantined_after: u64,
40}
41
42impl BaseRevision {
43    /// The newest merged revision: the one a write must expect.
44    pub fn head(&self) -> u64 {
45        self.revision + self.quarantined_after
46    }
47}
48
49fn is_zero(value: &u64) -> bool {
50    *value == 0
51}
52
53fn base_dir(data_dir: &Path, vault_id: &str) -> Result<std::path::PathBuf, CloudError> {
54    validate_vault_id(vault_id).map_err(|e| CloudError::Protocol(e.to_string()))?;
55    Ok(data_dir.join("knowledge").join(vault_id))
56}
57
58/// The stored base of `vault_id`, or revision 0 (the empty document).
59pub fn load_base(data_dir: &Path, vault_id: &str) -> BaseRevision {
60    base_dir(data_dir, vault_id)
61        .ok()
62        .and_then(|dir| std::fs::read(dir.join("base.json")).ok())
63        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
64        .unwrap_or_default()
65}
66
67pub fn save_base(data_dir: &Path, vault_id: &str, base: &BaseRevision) -> Result<(), CloudError> {
68    let bytes = serde_json::to_vec_pretty(base).map_err(|e| CloudError::Local(e.to_string()))?;
69    write_private(&base_dir(data_dir, vault_id)?, "base.json", &bytes)
70}