Skip to main content

lean_ctx/core/hive/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::core::hive::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 chrono::{DateTime, Duration, Utc};
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::core::hive::HiveError;
21use crate::core::hive::capture;
22use crate::core::hive::config::HiveConfig;
23use crate::core::hive::outbox::{CHANNEL_KNOWLEDGE, Outbox};
24use crate::core::hive::state::{HiveStore, write_private};
25use crate::core::hive::vault::{VaultMap, project_identity};
26use lean_ctx_protocol::hive::knowledge::{
27    ContextPatchV1, DRAFT_PROPOSAL_SCHEMA, DraftProposalV1, MAX_PATCH_OPS, PatchOpV1, ProposalState,
28};
29use lean_ctx_protocol::hive::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<DateTime<Utc>>,
46    pub last_draft_at: Option<DateTime<Utc>>,
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}
58
59/// 3.11.5 kept a project's watermark in `<data>/hive/drafts/<stable>.watermark`.
60pub(crate) const LEGACY_WATERMARK_DIR: &str = "drafts";
61/// 3.12: `<data>/hive/capture/<place>.watermark` (SPEC-ENGINE §3.16).
62pub(crate) const WATERMARK_DIR: &str = "capture";
63pub(crate) const WATERMARK_EXT: &str = "watermark";
64
65/// The place a project's capture state is kept under: its vault once it is
66/// bound, the project itself before (as [`capture::open_run`]).
67pub(crate) fn watermark_place(data_dir: &Path, stable: &str) -> String {
68    VaultMap::load(data_dir)
69        .vaults
70        .get(stable)
71        .map_or_else(|| stable.to_string(), |r| r.vault_id.clone())
72}
73
74fn read_watermark(path: &Path) -> Option<Watermark> {
75    std::fs::read(path)
76        .ok()
77        .and_then(|b| serde_json::from_slice(&b).ok())
78}
79
80/// The vault's watermark; before the upgrade moved it (or before the
81/// project was bound), the one kept under the project.
82fn load_watermark(data_dir: &Path, stable: &str) -> Watermark {
83    let name = |place: &str| format!("{place}.{WATERMARK_EXT}");
84    let place = watermark_place(data_dir, stable);
85    [
86        data_dir.join(WATERMARK_DIR).join(name(&place)),
87        data_dir.join(WATERMARK_DIR).join(name(stable)),
88        data_dir.join(LEGACY_WATERMARK_DIR).join(name(stable)),
89    ]
90    .iter()
91    .find_map(|path| read_watermark(path))
92    .unwrap_or_default()
93}
94
95fn save_watermark(data_dir: &Path, stable: &str, mark: &Watermark) -> Result<(), HiveError> {
96    let bytes = serde_json::to_vec(mark).map_err(|e| HiveError::Local(e.to_string()))?;
97    let place = watermark_place(data_dir, stable);
98    write_private(
99        &data_dir.join(WATERMARK_DIR),
100        &format!("{place}.{WATERMARK_EXT}"),
101        &bytes,
102    )
103}
104
105/// An opaque per-session reference: no host, user or path data.
106pub fn session_ref(session_id: &str) -> String {
107    let digest = Sha256::digest(format!("leanctx.hive.session.v1\n{session_id}").as_bytes());
108    format!("ses_{}", hex::encode(&digest[..12]))
109}
110
111/// Summary and body of a draft: every fact passed the capture gate, so each
112/// is one complete claim and is listed whole (a procedure by its title).
113fn summary_and_body(ops: &[PatchOpV1]) -> (String, String) {
114    let summary = match ops.len() {
115        1 => "Captured 1 fact".to_string(),
116        n => format!("Captured {n} facts"),
117    };
118    let mut body = format!(
119        "Captured in a lean-ctx session (capture gate v{}):\n",
120        capture::GATE_VERSION
121    );
122    for op in ops {
123        if let PatchOpV1::AddFact { fact } = op {
124            let claim = fact.statement.lines().next().unwrap_or_default();
125            body.push_str(&format!("- {claim}\n"));
126        }
127    }
128    (summary, body)
129}
130
131/// Whether the project `stable` at `root` syncs through its vault's C0 2.0
132/// replica, as `hive sync` decides: the enrolled Hive speaks 2.0 and the
133/// project is bound (or linked, and bound on its next sync). A 1.x Hive
134/// keeps the draft path.
135pub(crate) fn syncs_through_replica(store: &HiveStore, stable: &str, root: &Path) -> bool {
136    crate::core::hive::bus::relay_v2::speaks_v2(store)
137        && (VaultMap::load(store.data_dir()).vaults.contains_key(stable)
138            || crate::core::hive::link::has_link_file(root))
139}
140
141/// Plan, screen and queue the learnings of the project at `root` made since
142/// its last draft. Returns the outbox id, or `None` when there is nothing
143/// to propose (or Hive is not set up for this machine).
144pub fn enqueue_session_draft(
145    store: &HiveStore,
146    config: &HiveConfig,
147    root: &Path,
148    session_id: &str,
149    trigger: Trigger,
150    screen: &mut Screen,
151    now: DateTime<Utc>,
152) -> Result<Option<String>, HiveError> {
153    capture_session(store, config, root, session_id, trigger, screen, now).map(|(id, _)| id)
154}
155
156/// [`enqueue_session_draft`], also returning what the capture run counted.
157fn capture_session(
158    store: &HiveStore,
159    config: &HiveConfig,
160    root: &Path,
161    session_id: &str,
162    trigger: Trigger,
163    screen: &mut Screen,
164    now: DateTime<Utc>,
165) -> Result<(Option<String>, capture::CaptureCounts), HiveError> {
166    let nothing = || Ok((None, capture::CaptureCounts::default()));
167    if config.enabled == Some(false) || !config.auto_capture || store.instance()?.is_none() {
168        return nothing();
169    }
170    let Some(identity) = project_identity(root) else {
171        return nothing();
172    };
173    let stable = stable_identity(&identity);
174    // A vault that syncs through its v2 replica gets knowledge only as
175    // signed events (`hive sync`); a 1.x draft would duplicate it and
176    // feed the frozen review flow.
177    if syncs_through_replica(store, &stable, root) {
178        return nothing();
179    }
180    let data = store.data_dir();
181    let mut mark = load_watermark(data, &stable);
182    if trigger == Trigger::Save
183        && mark
184            .last_draft_at
185            .is_some_and(|at| now - at < Duration::minutes(SAVE_DEBOUNCE_MINUTES))
186    {
187        return nothing();
188    }
189    let Some(knowledge) = crate::core::knowledge::ProjectKnowledge::load(&root.to_string_lossy())
190    else {
191        return nothing();
192    };
193    let base: BaseRevision = VaultMap::load(data)
194        .vaults
195        .get(&stable)
196        .map(|record| load_base(data, &record.vault_id))
197        .unwrap_or_default();
198    let (mut run, place) = capture::open_run(data, &stable, root, screen, now.timestamp_millis());
199    let plan = plan_learn(
200        &knowledge,
201        &base.document,
202        mark.since,
203        MAX_PATCH_OPS,
204        &mut run,
205    );
206    capture::finish_run(data, &place, &run)?;
207    let screening = run.screen.counts();
208    let counts = run.counts.clone();
209    if plan.watermark.is_some() {
210        mark.since = plan.watermark;
211    }
212    if plan.added.is_empty() {
213        save_watermark(data, &stable, &mark)?;
214        return Ok((None, counts));
215    }
216    let ops: Vec<PatchOpV1> = plan
217        .added
218        .into_iter()
219        .map(|fact| PatchOpV1::AddFact { fact })
220        .collect();
221    let (summary, body) = summary_and_body(&ops);
222    let draft = DraftProposalV1 {
223        schema: DRAFT_PROPOSAL_SCHEMA.into(),
224        state: ProposalState::Draft,
225        summary: Some(summary),
226        body: Some(body),
227        sources: Vec::new(),
228        context_patch: ContextPatchV1 {
229            base_revision: base.revision,
230            ops,
231            sealed: None,
232        },
233        session_ref: session_ref(session_id),
234        engine_screening: screening,
235        origin: None,
236    };
237    draft
238        .validate()
239        .map_err(|e| HiveError::Protocol(format!("draft: {e}")))?;
240    let payload = serde_json::to_value(QueuedDraft {
241        stable_identity: stable.clone(),
242        root: root.to_string_lossy().into_owned(),
243        draft,
244    })
245    .map_err(|e| HiveError::Local(e.to_string()))?;
246    let id = Outbox::at(data).enqueue(CHANNEL_KNOWLEDGE, payload, now)?;
247    mark.last_draft_at = Some(now);
248    save_watermark(data, &stable, &mark)?;
249    Ok((Some(id), counts))
250}
251
252/// What [`recapture`] did.
253#[derive(Debug, Clone, Default)]
254pub struct Recapture {
255    /// Unsent session drafts of the project it removed.
256    pub removed: usize,
257    /// Drafts it queued instead.
258    pub queued: Vec<String>,
259    pub counts: capture::CaptureCounts,
260}
261
262/// `lean-ctx hive capture --recapture` (SPEC-ENGINE §3.1.6): remove the
263/// project's unsent session drafts (they never reached members), reset its
264/// capture watermark and run the gate over the whole local knowledge.
265pub fn recapture(
266    store: &HiveStore,
267    config: &HiveConfig,
268    root: &Path,
269    screen: &mut Screen,
270    now: DateTime<Utc>,
271) -> Result<Recapture, HiveError> {
272    let identity = project_identity(root)
273        .ok_or_else(|| HiveError::Config("not inside a git repository".into()))?;
274    let stable = stable_identity(&identity);
275    let data = store.data_dir();
276    let outbox = Outbox::at(data);
277    let mut done = Recapture::default();
278    for item in outbox.list(CHANNEL_KNOWLEDGE) {
279        if queued(&item.payload)
280            .is_some_and(|q| q.stable_identity == stable && q.draft.origin.is_none())
281        {
282            outbox.remove(&item)?;
283            done.removed += 1;
284        }
285    }
286    save_watermark(data, &stable, &Watermark::default())?;
287    // A run queues at most one draft of `MAX_PATCH_OPS` facts; the next
288    // continues after it.
289    loop {
290        let (id, counts) = capture_session(
291            store,
292            config,
293            root,
294            "cli-recapture",
295            Trigger::SessionEnd,
296            screen,
297            now,
298        )?;
299        done.counts.absorb(&counts);
300        let full = counts
301            .rejected
302            .contains_key(&capture::ReasonCode::BudgetBatchFull);
303        done.queued.extend(id);
304        if !full {
305            break;
306        }
307    }
308    // A batch that was full is continued, not rejected.
309    done.counts
310        .rejected
311        .remove(&capture::ReasonCode::BudgetBatchFull);
312    Ok(done)
313}
314
315/// Hook for session end, save and shutdown: enqueue only, never network,
316/// never an error for the caller (a failure is recorded for `hive status`).
317pub fn on_session_event(project_root: &str, session_id: &str, trigger: Trigger) {
318    let Ok(store) = HiveStore::open() else {
319        return;
320    };
321    if !matches!(store.instance(), Ok(Some(_))) {
322        return;
323    }
324    let config = crate::core::config::Config::load().hive.clone();
325    let mut screen = Screen::for_installation();
326    if let Err(error) = enqueue_session_draft(
327        &store,
328        &config,
329        Path::new(project_root),
330        session_id,
331        trigger,
332        &mut screen,
333        Utc::now(),
334    ) {
335        store.record_error(&format!("draft: {error}"));
336    }
337}
338
339/// The draft inside a queued item, for status listings.
340pub fn queued(payload: &Value) -> Option<QueuedDraft> {
341    serde_json::from_value(payload.clone()).ok()
342}
343
344#[cfg(test)]
345#[path = "draft_tests.rs"]
346mod tests;