Skip to main content

lean_ctx_cloud/delivery/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Delivery of a place's knowledge into an agent's context (SPEC-ENGINE
3//! §3.5): which folded nodes a host session may see, in which bucket, and a
4//! deterministic rendering (#498) — the same replica and query give the
5//! same bytes, whatever the clock, the scores or the trust revision say.
6
7use serde_json::Value;
8
9use crate::replica::fold::{Graph, Node};
10use crate::untrusted::{UntrustedKind, wrap};
11
12pub mod knowledge_state;
13
14/// Bucket a delivered node is shown in (§3.5.2), in delivery order. The
15/// last two hold knowledge that is not current truth (v5 2.2.1): it is
16/// delivered after everything else and labelled, never as a plain item.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
18pub enum Bucket {
19    High,
20    Normal,
21    /// An anchor changed or is gone: re-verify before relying on it.
22    Outdated,
23    /// An open contradiction with another live claim.
24    Conflicting,
25}
26
27impl Bucket {
28    pub fn as_str(self) -> &'static str {
29        match self {
30            Self::High => "high",
31            Self::Normal => "normal",
32            Self::Outdated => "outdated",
33            Self::Conflicting => "conflicting",
34        }
35    }
36}
37
38/// Node type order inside a bucket (§3.5.3).
39fn type_rank(node_type: &str) -> u8 {
40    match node_type {
41        "gotcha" => 0,
42        "decision" => 1,
43        "procedure" => 2,
44        "fact" => 3,
45        "finding" => 4,
46        "episode" => 5,
47        _ => 6,
48    }
49}
50
51/// One deliverable node.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct Item {
54    pub node_id: String,
55    pub node_type: String,
56    pub bucket: Bucket,
57    /// `low` trust sorts last within `normal`.
58    pub low: bool,
59    /// Knowledge state `provisional` (no observed evidence): served, but
60    /// labelled so an agent does not take a claim for an observation.
61    pub provisional: bool,
62    pub own: bool,
63    pub text: String,
64    /// Relevance tier 0 (best) – 3 for the query.
65    pub tier: u8,
66}
67
68/// The text a node is delivered as: the statement, a procedure's title
69/// with numbered steps, an episode's summary. Never truncated (R70).
70fn text_of(node: &Node) -> Option<String> {
71    let f = |k: &str| node.fields.get(k).and_then(Value::as_str);
72    match node.node_type.as_str() {
73        "procedure" => {
74            let mut t = f("title")?.to_string();
75            if let Some(steps) = node.fields.get("steps").and_then(Value::as_array) {
76                for (i, s) in steps.iter().filter_map(Value::as_str).enumerate() {
77                    t.push_str(&format!("\n  {}. {s}", i + 1));
78                }
79            }
80            Some(t)
81        }
82        "episode" => f("summary").map(str::to_string),
83        "gotcha" => f("statement").map(|s| format!("Gotcha: {s}")),
84        "decision" => f("statement").map(|s| match f("chosen") {
85            Some(chosen) => format!("{s} (chosen: {chosen})"),
86            None => s.to_string(),
87        }),
88        _ => f("statement").map(str::to_string),
89    }
90}
91
92/// Bucket of a node for a session of the owning workspace, from its
93/// provenance and the trust bucket (absent until the trust job publishes
94/// one).
95pub fn bucket_of(node: &Node, trust_bucket: Option<&str>) -> (Bucket, bool) {
96    let own = node.provenance.as_deref() == Some("own");
97    match trust_bucket {
98        Some("high") if !own => (Bucket::High, false),
99        Some("low") => (Bucket::Normal, true),
100        _ => (Bucket::Normal, false),
101    }
102}
103
104/// Relevance tier of `text` for `query` terms: share of query terms the
105/// text contains, cut at fixed quantiles (no raw scores in the output).
106fn tier(text: &str, terms: &[String]) -> Option<u8> {
107    if terms.is_empty() {
108        return Some(0);
109    }
110    let lower = text.to_lowercase();
111    let hits = terms.iter().filter(|t| lower.contains(t.as_str())).count();
112    if hits == 0 {
113        return None;
114    }
115    let share = hits * 100 / terms.len();
116    Some(match share {
117        100 => 0,
118        67..=99 => 1,
119        34..=66 => 2,
120        _ => 3,
121    })
122}
123
124/// The deliverable items of `graph` for `query` (all when empty), in the
125/// order of §3.5.3: bucket → node type → relevance tier → node id.
126pub fn items(graph: &Graph, trust: &dyn Fn(&str) -> Option<String>, query: &str) -> Vec<Item> {
127    items_in(graph, &knowledge_state::Index::new(graph), trust, query)
128}
129
130/// [`items`] with the knowledge states of `states` (e.g. an index that
131/// also resolves fact links from the save history).
132pub fn items_in(
133    graph: &Graph,
134    states: &knowledge_state::Index,
135    trust: &dyn Fn(&str) -> Option<String>,
136    query: &str,
137) -> Vec<Item> {
138    let terms: Vec<String> = query
139        .split_whitespace()
140        .map(str::to_lowercase)
141        .filter(|t| t.chars().count() >= 2)
142        .collect();
143    let mut out: Vec<Item> = graph
144        .live_nodes()
145        .filter_map(|(id, node)| {
146            // Rejected and superseded knowledge leaves delivery (SPEC-ENGINE
147            // §3.4 edge table); outdated and conflicting go last, labelled.
148            let state = states.state(id, node);
149            let (bucket, low) = match state {
150                (knowledge_state::State::Rejected, _)
151                | (knowledge_state::State::Outdated, Some("superseded")) => return None,
152                (knowledge_state::State::Outdated, _) => (Bucket::Outdated, false),
153                (knowledge_state::State::Conflicting, _) => (Bucket::Conflicting, false),
154                _ => bucket_of(node, trust(id).as_deref()),
155            };
156            let text = text_of(node)?;
157            Some(Item {
158                node_id: id.clone(),
159                node_type: node.node_type.clone(),
160                bucket,
161                low,
162                provisional: state.0 == knowledge_state::State::Provisional,
163                own: node.provenance.as_deref() == Some("own"),
164                tier: tier(&text, &terms)?,
165                text,
166            })
167        })
168        .collect();
169    out.sort_by(|a, b| {
170        (a.bucket, a.low, type_rank(&a.node_type), a.tier, &a.node_id).cmp(&(
171            b.bucket,
172            b.low,
173            type_rank(&b.node_type),
174            b.tier,
175            &b.node_id,
176        ))
177    });
178    out
179}
180
181/// Render items for the agent within `budget_tokens` (an item that does
182/// not fit is skipped whole). Header `vault @<ns>/<name> · <d>`, `d` a
183/// digest of the delivered (node id, bucket) pairs; other members' text is
184/// fenced as data.
185///
186/// Every item whose id follows the reference grammar carries its
187/// `node:<id>` (v5 2.6.1), and the section says once how to cite it: a
188/// claim that names the id in its refs gets a `derived_from` edge
189/// (`capture::derived`), the only evidence of verified reuse (BAUPLAN
190/// §5.3). The hint line is counted against the budget with the first
191/// citable item; a section without one carries no hint.
192pub fn render(vault: &str, items: &[Item], budget_tokens: usize) -> String {
193    let source = format!("vault:{vault}");
194    let mut lines = Vec::new();
195    let mut delivered: Vec<(String, &str)> = Vec::new();
196    let mut used = 0;
197    let mut cited = false;
198    for item in items {
199        // Only an id the capture path accepts back is shown: a malformed
200        // target from a foreign event is neither citable nor rendered
201        // outside the data fence.
202        let citable = matches!(
203            crate::capture::refs::parse(&format!("node:{}", item.node_id)),
204            Some(crate::capture::refs::Reference::Node(_))
205        );
206        let id = if citable {
207            format!(" node:{}", item.node_id)
208        } else {
209            String::new()
210        };
211        let label = match item.bucket {
212            Bucket::Outdated => "[outdated: re-verify] ",
213            Bucket::Conflicting => "[conflicting] ",
214            _ if item.low && item.provisional => "[low trust, provisional] ",
215            _ if item.low => "[low trust] ",
216            _ if item.provisional => "[provisional] ",
217            _ => "",
218        };
219        let body = if item.own {
220            item.text.clone()
221        } else {
222            wrap(UntrustedKind::Knowledge, &source, &item.text)
223        };
224        let badge = if item.own { "" } else { " (from workspace)" };
225        let line = format!("- {label}{}{id}{badge}: {body}", item.node_type);
226        let mut cost = lean_ctx::core::tokens::count_tokens(&line);
227        if citable && !cited {
228            cost += lean_ctx::core::tokens::count_tokens(CITE_HINT);
229        }
230        if used + cost > budget_tokens {
231            continue;
232        }
233        used += cost;
234        cited |= citable;
235        lines.push(line);
236        delivered.push((item.node_id.clone(), item.bucket.as_str()));
237    }
238    if lines.is_empty() {
239        return String::new();
240    }
241    delivered.sort();
242    let mut h = blake3::Hasher::new();
243    for (id, bucket) in &delivered {
244        h.update(id.as_bytes());
245        h.update(&[0]);
246        h.update(bucket.as_bytes());
247        h.update(&[0]);
248    }
249    let digest = &h.finalize().to_hex()[..8];
250    let hint = if cited {
251        format!("{CITE_HINT}\n")
252    } else {
253        String::new()
254    };
255    format!("vault @{vault} · {digest}\n{hint}{}\n", lines.join("\n"))
256}
257
258/// How an agent cites a delivered item (once per section, ~15 tokens).
259pub const CITE_HINT: &str = "Building on an item? Put its node:<id> in remember refs.";
260
261/// Knowledge section budget per call (SPEC-ENGINE §3.5.1: hard max).
262pub const MAX_SECTION_TOKENS: usize = 1_500;
263
264/// The machine replica key, read once per process (keychain or file).
265fn master_key(config_dir: &std::path::Path) -> Option<&'static [u8; 32]> {
266    static MK: std::sync::OnceLock<Option<[u8; 32]>> = std::sync::OnceLock::new();
267    MK.get_or_init(|| {
268        crate::replica::crypt::master_key(config_dir, false)
269            .ok()
270            .map(|(k, _)| *k)
271    })
272    .as_ref()
273}
274
275/// The folded graph of `vault_id`'s replica and its knowledge states
276/// (edges and the save history's fact links, #286); `None` when there is
277/// none (nothing is created here).
278fn folded(store: &crate::CloudStore, vault_id: &str) -> Option<(Graph, knowledge_state::Index)> {
279    let dir = crate::replica::store::place_dir(store.data_dir(), vault_id);
280    if !dir.join("replica.db").exists() {
281        return None;
282    }
283    let mk = master_key(store.config_dir())?;
284    let (replica, _) = crate::replica::Replica::open(store.data_dir(), vault_id, mk).ok()?;
285    let mut graph = Graph::default();
286    // lean-ctx: folds the stored log per call; switch to the materialised
287    // nodes table once replicas reach ~10k events.
288    graph.fold(&replica.fold_events().ok()?).ok()?;
289    let states = match replica.first_saves() {
290        Ok(saves) => knowledge_state::Index::with_saves(&graph, &saves),
291        Err(_) => knowledge_state::Index::new(&graph),
292    };
293    Some((graph, states))
294}
295
296/// The vault `root` is bound to through its identity; `None` for a folder
297/// the person unlinked (rc4-6, bd 39936) and while the opt-out store is
298/// damaged.
299fn bound_vault(
300    store: &crate::CloudStore,
301    root: &std::path::Path,
302) -> Option<crate::vault::VaultRecord> {
303    if crate::unlinked::contains(store.data_dir(), root) {
304        return None;
305    }
306    let stable =
307        lean_ctx_protocol::cloud::vault::stable_identity(&crate::vault::project_identity(root)?);
308    // Only a record of the connected Cloud and account (rc3-81).
309    crate::vault::connected_map(store)
310        .vaults
311        .get(&stable)
312        .cloned()
313}
314
315/// The vault section a recall in `project_root` delivers (§3.5.1): the
316/// bound vault's replica, deterministic and within budget. `None` when the
317/// checkout is not bound or has no replica yet (nothing is created here),
318/// and for a folder the person unlinked (rc4-6, bd 39936).
319pub fn for_project(project_root: &str, query: &str) -> Option<String> {
320    let store = crate::CloudStore::open().ok()?;
321    // Nothing while not connected, nothing of another account (3.12.8).
322    store.instance().ok()??;
323    let record = bound_vault(&store, std::path::Path::new(project_root))?;
324    let (graph, states) = folded(&store, &record.vault_id)?;
325    let list = items_in(&graph, &states, &|_| None, query);
326    let out = render(
327        &format!("{}/{}", record.ns, record.name),
328        &list,
329        MAX_SECTION_TOKENS,
330    );
331    (!out.is_empty()).then_some(out)
332}
333
334#[cfg(test)]
335mod tests;