Skip to main content

lean_ctx_cloud/knowledge/
import_draft.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Facts imported from the repository itself (K1: `lean-ctx import
3//! docs|git`) → import drafts in the outbox (C0 1.9 import addendum).
4//!
5//! An import draft is a learning draft with `origin: import` and the import
6//! source of each fact (`import:docs:<path>#<slug>`, `import:git:<sha>`):
7//! the same planning against the last pulled base and the same screening,
8//! queued only, sent by [`super::pull`]. A draft carries at most 16 sources
9//! and [`MAX_PATCH_OPS`] facts, so a large import becomes several drafts.
10
11use std::path::Path;
12
13use lean_ctx_time::UtcDateTime;
14
15use super::draft::{QueuedDraft, Watermark};
16use super::learn::plan_import;
17use super::screening::Screen;
18use super::{BaseRevision, load_base};
19use crate::CloudError;
20use crate::capture;
21use crate::config::CloudConfig;
22use crate::outbox::{CHANNEL_KNOWLEDGE, Outbox};
23use crate::state::{CloudStore, write_private};
24use crate::vault::{VaultMap, project_identity};
25use lean_ctx_protocol::cloud::knowledge::{
26    ContextPatchV1, DRAFT_PROPOSAL_SCHEMA, DraftOrigin, DraftProposalV1, FactV1, MAX_PATCH_OPS,
27    PatchOpV1, ProposalState,
28};
29use lean_ctx_protocol::cloud::vault::stable_identity;
30
31/// Sources one draft may name (`DraftProposalV1::validate`).
32const MAX_SOURCES: usize = 16;
33/// Facts planned per run; the rest follows with the next import.
34const MAX_FACTS_PER_RUN: usize = 400;
35
36fn watermark_name(stable: &str) -> String {
37    format!("{stable}.import-watermark")
38}
39
40fn load_watermark(data_dir: &Path, stable: &str) -> Watermark {
41    std::fs::read(data_dir.join("drafts").join(watermark_name(stable)))
42        .ok()
43        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
44        .unwrap_or_default()
45}
46
47fn save_watermark(data_dir: &Path, stable: &str, mark: &Watermark) -> Result<(), CloudError> {
48    let bytes = serde_json::to_vec(mark).map_err(|e| CloudError::Local(e.to_string()))?;
49    write_private(&data_dir.join("drafts"), &watermark_name(stable), &bytes)
50}
51
52/// The planned facts in drafts of at most [`MAX_SOURCES`] distinct sources
53/// and [`MAX_PATCH_OPS`] facts, in plan order.
54fn batches(facts: Vec<FactV1>, sources: Vec<String>) -> Vec<(Vec<FactV1>, Vec<String>)> {
55    let mut out: Vec<(Vec<FactV1>, Vec<String>)> = Vec::new();
56    for (fact, source) in facts.into_iter().zip(sources) {
57        let fits = out.last().is_some_and(|(facts, names)| {
58            facts.len() < MAX_PATCH_OPS && (names.contains(&source) || names.len() < MAX_SOURCES)
59        });
60        if !fits {
61            out.push((Vec::new(), Vec::new()));
62        }
63        let (facts, names) = out.last_mut().expect("pushed above");
64        if !names.contains(&source) {
65            names.push(source);
66        }
67        facts.push(fact);
68    }
69    out
70}
71
72fn summary_and_body(facts: &[FactV1]) -> (String, String) {
73    let summary = match facts.len() {
74        1 => "Imported from the repository: 1 fact".to_owned(),
75        n => format!("Imported from the repository: {n} facts"),
76    };
77    let mut body = String::from("Imported by lean-ctx from the repository's docs and history:\n");
78    // Each fact passed the capture gate: one complete claim, listed whole.
79    for fact in facts {
80        let claim = fact.statement.lines().next().unwrap_or_default();
81        body.push_str(&format!("- {claim}\n"));
82    }
83    (summary, body)
84}
85
86/// Plan, screen and queue the imported facts of the project at `root` that
87/// changed since its last import draft. Returns the outbox ids (none when
88/// there is nothing to propose, Cloud is not set up here, or the Cloud speaks
89/// C0 2.0: it takes the imported facts from the knowledge store as signed
90/// events through capture, never as a 1.x draft).
91pub fn enqueue_import_drafts(
92    store: &CloudStore,
93    config: &CloudConfig,
94    root: &Path,
95    session_id: &str,
96    screen: &mut Screen,
97    now: UtcDateTime,
98) -> Result<Vec<String>, CloudError> {
99    if config.enabled == Some(false)
100        || !config.auto_capture
101        || store.instance()?.is_none()
102        || crate::bus::relay_v2::speaks_v2(store)
103    {
104        return Ok(Vec::new());
105    }
106    let Some(identity) = project_identity(root) else {
107        return Ok(Vec::new());
108    };
109    let stable = stable_identity(&identity);
110    let data = store.data_dir();
111    // Without the local key nothing naming the session (or label) is
112    // uploaded: no draft is queued and the watermark stays.
113    let session_ref = crate::session_ref::uploaded_ses_ref(data, session_id)?;
114    let Some(knowledge) =
115        lean_ctx::core::knowledge::ProjectKnowledge::load(&root.to_string_lossy())
116    else {
117        return Ok(Vec::new());
118    };
119    let base: BaseRevision = VaultMap::load(data)
120        .vaults
121        .get(&stable)
122        .map(|record| load_base(data, &record.vault_id))
123        .unwrap_or_default();
124    let mut mark = load_watermark(data, &stable);
125    let (mut run, place) = capture::open_run(data, &stable, root, screen, now.timestamp_millis());
126    let plan = plan_import(
127        &knowledge,
128        &base.document,
129        mark.since,
130        MAX_FACTS_PER_RUN,
131        &mut run,
132    );
133    capture::finish_run(data, &place, &run)?;
134    let screening = run.screen.counts();
135    if plan.watermark.is_some() {
136        mark.since = plan.watermark;
137    }
138    // Every draft is built and validated before the first is queued, and a
139    // queue that fails part way takes back what it queued: an aborted run
140    // never leaves drafts that the next run (same watermark) queues again.
141    let mut payloads = Vec::new();
142    for (facts, sources) in batches(plan.added, plan.import_sources) {
143        let (summary, body) = summary_and_body(&facts);
144        let draft = DraftProposalV1 {
145            schema: DRAFT_PROPOSAL_SCHEMA.into(),
146            state: ProposalState::Draft,
147            summary: Some(summary),
148            body: Some(body),
149            sources,
150            context_patch: ContextPatchV1 {
151                base_revision: base.revision,
152                ops: facts
153                    .into_iter()
154                    .map(|fact| PatchOpV1::AddFact { fact })
155                    .collect(),
156            },
157            session_ref: session_ref.clone(),
158            engine_screening: screening,
159            origin: Some(DraftOrigin::Import),
160        };
161        draft
162            .validate()
163            .map_err(|e| CloudError::Protocol(format!("import draft: {e}")))?;
164        let payload = serde_json::to_value(QueuedDraft {
165            stable_identity: stable.clone(),
166            root: root.to_string_lossy().into_owned(),
167            draft,
168            ref_keyed: true,
169        })
170        .map_err(|e| CloudError::Local(e.to_string()))?;
171        payloads.push(payload);
172    }
173    let outbox = Outbox::at(data);
174    let mut ids = Vec::new();
175    for payload in payloads {
176        match outbox.enqueue(CHANNEL_KNOWLEDGE, payload, now) {
177            Ok(id) => ids.push(id),
178            Err(error) => {
179                for item in outbox
180                    .list(CHANNEL_KNOWLEDGE)
181                    .into_iter()
182                    .filter(|item| ids.contains(&item.id))
183                {
184                    let _ = outbox.remove(&item);
185                }
186                return Err(error);
187            }
188        }
189    }
190    if !ids.is_empty() {
191        mark.last_draft_at = Some(now);
192    }
193    save_watermark(data, &stable, &mark)?;
194    Ok(ids)
195}
196
197#[cfg(test)]
198#[path = "import_draft_tests.rs"]
199mod tests;