1use chrono::{DateTime, Utc};
14use sha2::{Digest, Sha256};
15
16use crate::core::hive::capture::{self, CaptureRun, ReasonCode, dedupe};
17use crate::core::knowledge::{KnowledgeFact, NodeType, ProjectKnowledge};
18use crate::core::sensitivity::SensitivityLevel;
19use lean_ctx_protocol::hive::knowledge::{FactV1, ResearchContextDocumentV1};
20
21#[derive(Debug, Clone, Default)]
23pub struct LearnPlan {
24 pub added: Vec<FactV1>,
25 pub dropped: Vec<(String, ReasonCode)>,
28 pub merges: Vec<(String, Vec<String>)>,
31 pub watermark: Option<DateTime<Utc>>,
33 pub import_sources: Vec<String>,
36 pub captured: Vec<capture::CapturedFact>,
39}
40
41fn slug(s: &str, max: usize) -> String {
43 let mut out = String::new();
44 for c in s.chars() {
45 if c.is_ascii_alphanumeric() {
46 out.push(c.to_ascii_lowercase());
47 } else if !out.ends_with('-') && !out.is_empty() {
48 out.push('-');
49 }
50 }
51 let mut out: String = out.trim_matches('-').chars().take(max).collect();
52 while out.ends_with('-') {
53 out.pop();
54 }
55 out
56}
57
58fn short_hash(parts: &[&str]) -> String {
59 let mut h = Sha256::new();
60 for p in parts {
61 h.update(p.as_bytes());
62 h.update([0u8]);
63 }
64 hex::encode(&h.finalize()[..4])
65}
66
67pub fn fact_id(category: &str, key: &str, value: &str) -> String {
69 let hash = short_hash(&[category, key, value]);
70 let s = slug(key, 60);
71 if s.is_empty() {
72 format!("lc-{hash}")
73 } else {
74 format!("lc-{s}-{hash}")
75 }
76}
77
78pub fn kind_of(node_type: NodeType) -> &'static str {
80 match node_type {
81 NodeType::Fact | NodeType::Finding => "observation",
82 NodeType::Decision => "decision",
83 NodeType::Gotcha => "gotcha",
84 NodeType::Procedure => "procedure",
85 }
86}
87
88fn node_type_of_kind(kind: &str) -> NodeType {
90 match kind {
91 "decision" => NodeType::Decision,
92 "gotcha" => NodeType::Gotcha,
93 "procedure" => NodeType::Procedure,
94 _ => NodeType::Fact,
95 }
96}
97
98fn statement_of(c: &capture::CaptureCandidate) -> String {
101 let mut text = c.statement.clone();
102 if c.node_type != NodeType::Procedure {
103 return text;
104 }
105 for (i, step) in c.steps.iter().enumerate() {
106 text.push_str(&format!("\n{}. {step}", i + 1));
107 }
108 text
109}
110
111fn humanize(key: &str) -> String {
112 key.split(['-', '_', '.', ':', '/'])
113 .filter(|s| !s.is_empty())
114 .collect::<Vec<_>>()
115 .join(" ")
116}
117
118fn eligible(f: &KnowledgeFact) -> bool {
122 f.imported_from.is_none()
123 && f.is_current()
124 && !crate::core::knowledge::is_machine_derived(&f.category, &f.key)
125}
126
127fn eligible_import(f: &KnowledgeFact) -> bool {
131 matches!(f.imported_from.as_deref(), Some("docs" | "git"))
132 && f.review.is_none()
133 && f.is_current()
134 && !crate::core::knowledge::is_machine_derived(&f.category, &f.key)
135 && f.sensitivity == SensitivityLevel::Public
136}
137
138pub fn import_source(f: &KnowledgeFact) -> Option<String> {
143 let source = match f.imported_from.as_deref()? {
144 "git" => format!("import:git:{}", f.key.strip_prefix("git:")?),
145 "docs" => {
146 let (path, section) = f.key.split_once('#')?;
147 let section = section.rsplit_once('/').map_or(section, |(head, _)| head);
148 format!(
149 "import:docs:{path}#{}",
150 lean_ctx_protocol::hive::ctxpkg::import_slug(§ion.replace('/', " "))
151 )
152 }
153 _ => return None,
154 };
155 lean_ctx_protocol::hive::knowledge::import_source_ok(&source).then_some(source)
156}
157
158pub fn plan_learn(
162 knowledge: &ProjectKnowledge,
163 repo: &ResearchContextDocumentV1,
164 since: Option<DateTime<Utc>>,
165 limit: usize,
166 run: &mut CaptureRun<'_>,
167) -> LearnPlan {
168 plan_facts(knowledge, repo, since, limit, run, false)
169}
170
171pub fn plan_import(
176 knowledge: &ProjectKnowledge,
177 repo: &ResearchContextDocumentV1,
178 since: Option<DateTime<Utc>>,
179 limit: usize,
180 run: &mut CaptureRun<'_>,
181) -> LearnPlan {
182 plan_facts(knowledge, repo, since, limit, run, true)
183}
184
185fn changed_at(f: &KnowledgeFact) -> DateTime<Utc> {
187 f.created_at.max(f.last_confirmed)
188}
189
190fn import_reference(source: &str) -> Option<String> {
193 if let Some(sha) = source.strip_prefix("import:git:") {
194 return Some(format!("commit:{}", sha.to_ascii_lowercase()));
195 }
196 let path = source.strip_prefix("import:docs:")?.split('#').next()?;
197 Some(format!("file:{path}"))
198}
199
200fn held_index(pk_id: &[u8; 32], repo: &ResearchContextDocumentV1) -> (dedupe::Index, Vec<String>) {
202 let mut index = dedupe::Index::default();
203 let mut ids = Vec::new();
204 for f in &repo.facts {
205 let node_type = node_type_of_kind(&f.kind);
206 let refs = f
207 .anchors
208 .iter()
209 .map(|a| format!("file:{}", a.path))
210 .chain(f.sources.iter().cloned())
211 .collect();
212 index.insert(
213 dedupe::exact_key(pk_id, node_type, &f.statement),
214 dedupe::Known {
215 node_type,
216 signature: dedupe::signature(pk_id, &f.statement),
217 refs,
218 },
219 );
220 ids.push(f.id.clone());
221 }
222 (index, ids)
223}
224
225fn plan_facts(
226 knowledge: &ProjectKnowledge,
227 repo: &ResearchContextDocumentV1,
228 since: Option<DateTime<Utc>>,
229 limit: usize,
230 run: &mut CaptureRun<'_>,
231 imports: bool,
232) -> LearnPlan {
233 let mut plan = LearnPlan::default();
234 let stamp = |f: &KnowledgeFact| {
238 if imports {
239 changed_at(f)
240 } else {
241 f.capture
242 .changed_at
243 .map_or(f.created_at, |at| at.max(f.created_at))
244 }
245 };
246 let mut facts: Vec<&KnowledgeFact> = knowledge
247 .facts
248 .iter()
249 .filter(|f| {
250 (if imports {
251 eligible_import(f)
252 } else {
253 eligible(f)
254 }) && (since.is_none_or(|since| stamp(f) > since) || run.is_pending(f))
255 })
256 .collect();
257 facts.sort_by(|a, b| {
258 (stamp(a), &a.category, &a.key, &a.value).cmp(&(stamp(b), &b.category, &b.key, &b.value))
259 });
260
261 let (mut index, mut held_ids) = held_index(&run.pk_id, repo);
262 let mut seen_ids: std::collections::HashSet<String> = held_ids.iter().cloned().collect();
263
264 for f in facts {
265 if plan.added.len() == limit {
266 run.counts.reject(ReasonCode::BudgetBatchFull);
267 break;
268 }
269 plan.watermark = plan.watermark.max(Some(stamp(f)));
270 let import = if imports {
271 let Some(source) = import_source(f) else {
272 continue;
273 };
274 Some(source)
275 } else {
276 None
277 };
278 run.counts.considered += 1;
279 let label = format!("{}/{}", f.category, f.key);
280 let verdict = capture_one(f, import.as_deref(), run, &mut index);
281 let Captured {
282 candidate,
283 refs,
284 anchors,
285 } = match verdict {
286 Ok(ok) => ok,
287 Err(Rejected::Reason(reason)) => {
288 run.counts.reject(reason);
289 plan.dropped.push((label, reason));
290 continue;
291 }
292 Err(Rejected::Merge { index: i, refs }) => {
293 run.counts.reject(ReasonCode::NearDuplicateMerged);
294 plan.dropped.push((label, ReasonCode::NearDuplicateMerged));
295 if let Some(id) = held_ids.get(i) {
296 plan.merges.push((id.clone(), refs));
297 }
298 continue;
299 }
300 };
301 let statement = statement_of(&candidate);
302 let id = fact_id(&f.category, &f.key, &statement);
303 if !seen_ids.insert(id.clone()) {
304 run.counts.reject(ReasonCode::Duplicate);
305 plan.dropped.push((label, ReasonCode::Duplicate));
306 continue;
307 }
308 held_ids.push(id.clone());
309 let applies = humanize(&f.key);
310 let applies_to = if applies.is_empty() || applies.chars().count() > 500 {
311 Vec::new()
312 } else {
313 vec![applies]
314 };
315 let mut sources = vec![format!(
316 "lean-ctx:knowledge/{}/{}#{}",
317 slug(&f.category, 60),
318 slug(&f.key, 80),
319 short_hash(&[&f.category, &f.key, &statement])
320 )];
321 sources.extend(refs.iter().cloned());
322 run.counts.captured += 1;
323 plan.import_sources.extend(import);
324 plan.captured.push(capture::CapturedFact {
325 candidate: candidate.clone(),
326 refs,
327 category: f.category.clone(),
328 key: f.key.clone(),
329 value: f.value.clone(),
330 derived_from: Vec::new(),
331 });
332 plan.added.push(FactV1 {
333 id,
334 statement,
335 kind: kind_of(candidate.node_type).to_string(),
336 applies_to,
337 sources,
338 from_contributions: Vec::new(),
339 anchors,
340 });
341 }
342 plan
343}
344
345enum Rejected {
346 Reason(ReasonCode),
347 Merge { index: usize, refs: Vec<String> },
348}
349
350impl From<ReasonCode> for Rejected {
351 fn from(reason: ReasonCode) -> Self {
352 Self::Reason(reason)
353 }
354}
355
356fn capture_one(
360 f: &KnowledgeFact,
361 import: Option<&str>,
362 run: &mut CaptureRun<'_>,
363 index: &mut dedupe::Index,
364) -> Result<Captured, Rejected> {
365 let anchors_ok = f.anchors.iter().all(|a| {
369 run.screen
370 .check(&format!(
371 "{}\n{}",
372 a.path,
373 a.symbol.as_deref().unwrap_or_default()
374 ))
375 .is_ok()
376 });
377 let mut shaped = f.clone();
378 if !anchors_ok {
379 shaped.anchors.clear();
380 }
381 let candidate = capture::shape(&shaped, import.and_then(import_reference))?;
382 let refs = match capture::gate(&candidate, &mut run.checkout, run.sealed) {
383 Ok(refs) => refs,
384 Err(reason) => {
385 if reason == ReasonCode::UnpublishedRef {
386 run.unpublished(f);
387 } else {
388 run.settled(f);
389 }
390 return Err(reason.into());
391 }
392 };
393 run.settled(f);
394 let mut texts = vec![
395 f.category.clone(),
396 f.key.clone(),
397 candidate.statement.clone(),
398 ];
399 texts.extend(candidate.steps.iter().cloned());
400 texts.extend(candidate.commands.iter().map(|c| c.cmd.clone()));
401 texts.extend(refs.iter().cloned());
402 for text in &texts {
403 if crate::core::context_admission::carrier::admit_for_store_under(text, None)
404 .ok()
405 .is_none_or(|admitted| admitted != *text)
406 {
407 return Err(ReasonCode::Admission.into());
408 }
409 }
410 run.screen
411 .check(&texts.join("\n"))
412 .map_err(|b| ReasonCode::of_screen(&b))?;
413 let key = dedupe::exact_key(&run.pk_id, candidate.node_type, &candidate.statement);
414 let known = dedupe::Known {
415 node_type: candidate.node_type,
416 signature: dedupe::signature(&run.pk_id, &candidate.statement),
417 refs: refs.clone(),
418 };
419 match index.verdict(&key, &known) {
420 dedupe::Verdict::Duplicate => Err(ReasonCode::Duplicate.into()),
421 dedupe::Verdict::Merge { index: i, refs } => Err(Rejected::Merge { index: i, refs }),
422 dedupe::Verdict::New => {
423 index.insert(key, known);
424 Ok(Captured {
425 candidate,
426 refs,
427 anchors: shaped.anchors,
428 })
429 }
430 }
431}
432
433struct Captured {
435 candidate: capture::CaptureCandidate,
436 refs: Vec<String>,
438 anchors: Vec<crate::core::knowledge::anchors::CodeAnchor>,
440}
441
442pub fn knowledge_category(ns: &str, name: &str) -> String {
444 format!("hive/{ns}/{name}")
445}
446
447pub(crate) const IMPORT_TAG_SCHEME: &str = "hive-repo:";
451const VAULT_IMPORT_TAG_SCHEME: &str = "hive-vault:";
453
454pub(crate) fn import_tag_source(origin: &str) -> Option<&str> {
457 origin
458 .strip_prefix(IMPORT_TAG_SCHEME)
459 .or_else(|| origin.strip_prefix(VAULT_IMPORT_TAG_SCHEME))
460}
461
462pub(crate) fn import_tag_prefix(ns: &str, name: &str) -> String {
463 format!("@{ns}/{name}@r")
464}
465
466fn pulled_fact_key(id: &str) -> String {
473 let bytes = id.as_bytes();
474 let strict = !bytes.is_empty()
475 && bytes.len() <= 80
476 && bytes[0].is_ascii_alphanumeric()
477 && bytes
478 .iter()
479 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'));
480 if strict {
481 id.to_string()
482 } else {
483 format!("fact-{}", short_hash(&[id]))
484 }
485}
486
487pub fn served_by_replica(ns: &str, name: &str) -> bool {
491 let Ok(store) = crate::core::hive::HiveStore::open() else {
492 return false;
493 };
494 crate::core::hive::vault::VaultMap::load(store.data_dir())
495 .vaults
496 .values()
497 .find(|r| r.ns == ns && r.name == name)
498 .is_some_and(|r| {
499 crate::core::hive::replica::store::place_dir(store.data_dir(), &r.vault_id)
500 .join("replica.db")
501 .exists()
502 })
503}
504
505pub fn remove_pulled(project_root: &str, ns: &str, name: &str) -> Result<usize, String> {
507 let prefix = import_tag_prefix(ns, name);
508 let (_, removed) = ProjectKnowledge::mutate_locked(project_root, |k| {
509 let before = k.facts.len();
510 k.facts.retain(|f| {
511 !f.imported_from
512 .as_deref()
513 .and_then(import_tag_source)
514 .is_some_and(|source| source.starts_with(&prefix))
515 });
516 let removed = before - k.facts.len();
517 if removed > 0 {
518 k.rebuild_index();
519 }
520 removed
521 })?;
522 Ok(removed)
523}
524
525pub fn sync_into_knowledge(
529 project_root: &str,
530 ns: &str,
531 name: &str,
532 revision: u64,
533 doc: &ResearchContextDocumentV1,
534) -> Result<(usize, usize), String> {
535 if served_by_replica(ns, name) {
536 return Ok((0, remove_pulled(project_root, ns, name)?));
537 }
538 let policy = crate::core::memory_policy::MemoryPolicy::default();
539 let prefix = import_tag_prefix(ns, name);
540 let tag = format!("{IMPORT_TAG_SCHEME}{prefix}{revision}");
541 let category = knowledge_category(ns, name);
542 let (_, counts) = ProjectKnowledge::mutate_locked(project_root, |k| {
543 let before = k.facts.len();
544 k.facts.retain(|f| {
545 !f.imported_from
546 .as_deref()
547 .and_then(import_tag_source)
548 .is_some_and(|source| source.starts_with(&prefix))
549 });
550 let removed = before - k.facts.len();
551 if removed > 0 {
552 k.rebuild_index();
553 }
554 let mut loaded = 0usize;
555 for fact in &doc.facts {
556 let key = pulled_fact_key(&fact.id);
560 let value = crate::core::hive::untrusted::wrap(
561 crate::core::hive::untrusted::UntrustedKind::Knowledge,
562 &tag,
563 &fact.statement,
564 );
565 k.remember(&category, &key, &value, &tag, 0.8, &policy);
566 if let Some(last) = k
567 .facts
568 .iter_mut()
569 .rev()
570 .find(|f| f.category == category && f.key == key && f.is_current())
571 {
572 last.imported_from = Some(tag.clone());
573 last.anchors.clone_from(&fact.anchors);
576 loaded += 1;
577 }
578 }
579 (loaded, removed)
580 })?;
581 Ok(counts)
582}
583
584#[cfg(test)]
585mod tests {
586 use super::*;
587
588 #[test]
589 fn ids_and_kinds_are_stable() {
590 assert_eq!(
591 fact_id("decision", "db-choice", "Postgres"),
592 fact_id("decision", "db-choice", "Postgres")
593 );
594 assert_ne!(
595 fact_id("decision", "db-choice", "Postgres"),
596 fact_id("decision", "db-choice", "MySQL")
597 );
598 assert!(fact_id("decision", "DB Choice!", "x").starts_with("lc-db-choice-"));
599 assert_eq!(kind_of(NodeType::Decision), "decision");
600 assert_eq!(kind_of(NodeType::Finding), "observation");
601 }
602
603 #[test]
606 fn pulled_copies_of_a_vault_are_removed_and_nothing_else() {
607 let _data = crate::core::data_dir::isolated_data_dir();
608 let dir = tempfile::tempdir().unwrap();
609 let root = dir.path().to_string_lossy().into_owned();
610 let doc = |statement: &str| ResearchContextDocumentV1 {
611 facts: vec![FactV1 {
612 id: "f1".into(),
613 statement: statement.into(),
614 kind: "observation".into(),
615 applies_to: vec![],
616 sources: vec![],
617 from_contributions: vec![],
618 anchors: vec![],
619 }],
620 ..ResearchContextDocumentV1::default()
621 };
622 sync_into_knowledge(&root, "acme", "pay", 3, &doc("Pay copies this claim.")).unwrap();
623 sync_into_knowledge(&root, "acme", "other", 1, &doc("Other vault claim here.")).unwrap();
624 let policy = crate::core::memory_policy::MemoryPolicy::default();
625 ProjectKnowledge::mutate_locked(&root, |k| {
626 k.remember("arch", "own", "My own claim stays here.", "s", 0.9, &policy);
627 })
628 .unwrap();
629
630 assert_eq!(remove_pulled(&root, "acme", "pay").unwrap(), 1);
631 let k = ProjectKnowledge::load(&root).unwrap();
632 let values: Vec<&str> = k.facts.iter().map(|f| f.value.as_str()).collect();
633 assert!(values.iter().any(|v| v.contains("Other vault claim")));
634 assert!(values.contains(&"My own claim stays here."));
635 assert!(!values.iter().any(|v| v.contains("Pay copies")));
636 assert_eq!(remove_pulled(&root, "acme", "pay").unwrap(), 0);
637 }
638}