Skip to main content

lean_ctx/core/hive/knowledge/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Project knowledge with Hive: 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>/hive/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 review;
17pub mod screening;
18pub mod states;
19
20use std::path::Path;
21
22use serde::{Deserialize, Serialize};
23
24use super::HiveError;
25use super::state::write_private;
26use lean_ctx_protocol::hive::knowledge::ResearchContextDocumentV1;
27use lean_ctx_protocol::hive::validate_vault_id;
28
29/// The last revision pulled for a project: the delivered (released) head,
30/// the only one ever loaded into a checkout.
31#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
32pub struct BaseRevision {
33    pub revision: u64,
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub etag: Option<String>,
36    pub document: ResearchContextDocumentV1,
37    /// C0 1.9 ยง3: quarantined revisions Hive holds after this head. They
38    /// never reach an agent here; the next merge writes on top of them.
39    #[serde(default, skip_serializing_if = "is_zero")]
40    pub quarantined_after: u64,
41}
42
43impl BaseRevision {
44    /// The newest merged revision: the one a write must expect.
45    pub fn head(&self) -> u64 {
46        self.revision + self.quarantined_after
47    }
48}
49
50fn is_zero(value: &u64) -> bool {
51    *value == 0
52}
53
54fn base_dir(data_dir: &Path, vault_id: &str) -> Result<std::path::PathBuf, HiveError> {
55    validate_vault_id(vault_id).map_err(|e| HiveError::Protocol(e.to_string()))?;
56    Ok(data_dir.join("knowledge").join(vault_id))
57}
58
59/// The stored base of `vault_id`, or revision 0 (the empty document).
60pub fn load_base(data_dir: &Path, vault_id: &str) -> BaseRevision {
61    base_dir(data_dir, vault_id)
62        .ok()
63        .and_then(|dir| std::fs::read(dir.join("base.json")).ok())
64        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
65        .unwrap_or_default()
66}
67
68pub fn save_base(data_dir: &Path, vault_id: &str, base: &BaseRevision) -> Result<(), HiveError> {
69    let bytes = serde_json::to_vec_pretty(base).map_err(|e| HiveError::Local(e.to_string()))?;
70    write_private(&base_dir(data_dir, vault_id)?, "base.json", &bytes)
71}