1use serde_json::Value;
8
9use crate::replica::fold::{Graph, Node};
10use crate::untrusted::{UntrustedKind, wrap};
11
12pub mod knowledge_state;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
18pub enum Bucket {
19 High,
20 Normal,
21 Outdated,
23 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
38fn 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#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct Item {
54 pub node_id: String,
55 pub node_type: String,
56 pub bucket: Bucket,
57 pub low: bool,
59 pub provisional: bool,
62 pub own: bool,
63 pub text: String,
64 pub tier: u8,
66}
67
68fn 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
92pub 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
104fn 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
124pub 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
130pub 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 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
181pub 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 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
258pub const CITE_HINT: &str = "Building on an item? Put its node:<id> in remember refs.";
260
261pub const MAX_SECTION_TOKENS: usize = 1_500;
263
264fn 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
275fn 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 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
296pub fn for_project(project_root: &str, query: &str) -> Option<String> {
300 let store = crate::CloudStore::open().ok()?;
301 let root = std::path::Path::new(project_root);
302 let stable =
303 lean_ctx_protocol::cloud::vault::stable_identity(&crate::vault::project_identity(root)?);
304 let record = crate::vault::VaultMap::load(store.data_dir())
305 .vaults
306 .get(&stable)?
307 .clone();
308 let (graph, states) = folded(&store, &record.vault_id)?;
309 let list = items_in(&graph, &states, &|_| None, query);
310 let out = render(
311 &format!("{}/{}", record.ns, record.name),
312 &list,
313 MAX_SECTION_TOKENS,
314 );
315 (!out.is_empty()).then_some(out)
316}
317
318#[cfg(test)]
319mod tests;