1use lean_ctx_time::UtcDateTime;
14use sha2::{Digest, Sha256};
15
16use crate::capture::{self, CaptureRun, ReasonCode, dedupe};
17use lean_ctx::core::knowledge::{KnowledgeFact, NodeType, ProjectKnowledge};
18use lean_ctx::core::sensitivity::SensitivityLevel;
19use lean_ctx_protocol::cloud::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<UtcDateTime>,
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 && !lean_ctx::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 && !lean_ctx::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::cloud::ctxpkg::import_slug(§ion.replace('/', " "))
151 )
152 }
153 _ => return None,
154 };
155 lean_ctx_protocol::cloud::knowledge::import_source_ok(&source).then_some(source)
156}
157
158pub fn plan_learn(
162 knowledge: &ProjectKnowledge,
163 repo: &ResearchContextDocumentV1,
164 since: Option<UtcDateTime>,
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<UtcDateTime>,
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) -> UtcDateTime {
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<UtcDateTime>,
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 session: (!imports && !f.source_session.trim().is_empty())
334 .then(|| f.source_session.trim().to_string()),
335 });
336 plan.added.push(FactV1 {
337 id,
338 statement,
339 kind: kind_of(candidate.node_type).to_string(),
340 applies_to,
341 sources,
342 from_contributions: Vec::new(),
343 anchors,
344 });
345 }
346 plan
347}
348
349enum Rejected {
350 Reason(ReasonCode),
351 Merge { index: usize, refs: Vec<String> },
352}
353
354impl From<ReasonCode> for Rejected {
355 fn from(reason: ReasonCode) -> Self {
356 Self::Reason(reason)
357 }
358}
359
360fn capture_one(
364 f: &KnowledgeFact,
365 import: Option<&str>,
366 run: &mut CaptureRun<'_>,
367 index: &mut dedupe::Index,
368) -> Result<Captured, Rejected> {
369 let anchors_ok = f.anchors.iter().all(|a| {
373 run.screen
374 .check(&format!(
375 "{}\n{}",
376 a.path,
377 a.symbol.as_deref().unwrap_or_default()
378 ))
379 .is_ok()
380 });
381 let mut shaped = f.clone();
382 if !anchors_ok {
383 shaped.anchors.clear();
384 }
385 let candidate = capture::shape(&shaped, import.and_then(import_reference))?;
386 let refs = match capture::gate(&candidate, &mut run.checkout) {
387 Ok(refs) => refs,
388 Err(reason) => {
389 if reason == ReasonCode::UnpublishedRef {
390 run.unpublished(f);
391 } else {
392 run.settled(f);
393 }
394 return Err(reason.into());
395 }
396 };
397 run.settled(f);
398 let mut texts = vec![
399 f.category.clone(),
400 f.key.clone(),
401 candidate.statement.clone(),
402 ];
403 texts.extend(candidate.steps.iter().cloned());
404 texts.extend(candidate.commands.iter().map(|c| c.cmd.clone()));
405 texts.extend(refs.iter().cloned());
406 for text in &texts {
407 if lean_ctx::core::context_admission::carrier::admit_for_store_under(text, None)
408 .ok()
409 .is_none_or(|admitted| admitted != *text)
410 {
411 return Err(ReasonCode::Admission.into());
412 }
413 }
414 run.screen
415 .check(&texts.join("\n"))
416 .map_err(|b| ReasonCode::of_screen(&b))?;
417 let key = dedupe::exact_key(&run.pk_id, candidate.node_type, &candidate.statement);
418 let known = dedupe::Known {
419 node_type: candidate.node_type,
420 signature: dedupe::signature(&run.pk_id, &candidate.statement),
421 refs: refs.clone(),
422 };
423 match index.verdict(&key, &known) {
424 dedupe::Verdict::Duplicate => Err(ReasonCode::Duplicate.into()),
425 dedupe::Verdict::Merge { index: i, refs } => Err(Rejected::Merge { index: i, refs }),
426 dedupe::Verdict::New => {
427 index.insert(key, known);
428 Ok(Captured {
429 candidate,
430 refs,
431 anchors: shaped.anchors,
432 })
433 }
434 }
435}
436
437struct Captured {
439 candidate: capture::CaptureCandidate,
440 refs: Vec<String>,
442 anchors: Vec<lean_ctx::core::knowledge::anchors::CodeAnchor>,
444}
445
446pub fn knowledge_category(ns: &str, name: &str) -> String {
448 format!("cloud/{ns}/{name}")
449}
450
451pub use lean_ctx::core::knowledge::import_tag::{IMPORT_TAG_SCHEME, import_tag_source};
452
453pub(crate) fn import_tag_prefix(ns: &str, name: &str) -> String {
454 format!("@{ns}/{name}@r")
455}
456
457fn pulled_fact_key(id: &str) -> String {
464 let bytes = id.as_bytes();
465 let strict = !bytes.is_empty()
466 && bytes.len() <= 80
467 && bytes[0].is_ascii_alphanumeric()
468 && bytes
469 .iter()
470 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'));
471 if strict {
472 id.to_string()
473 } else {
474 format!("fact-{}", short_hash(&[id]))
475 }
476}
477
478pub fn served_by_replica(ns: &str, name: &str) -> bool {
482 let Ok(store) = crate::CloudStore::open() else {
483 return false;
484 };
485 crate::vault::VaultMap::load(store.data_dir())
486 .vaults
487 .values()
488 .find(|r| r.ns == ns && r.name == name)
489 .is_some_and(|r| {
490 crate::replica::store::place_dir(store.data_dir(), &r.vault_id)
491 .join("replica.db")
492 .exists()
493 })
494}
495
496pub fn remove_pulled(project_root: &str, ns: &str, name: &str) -> Result<usize, String> {
498 let prefix = import_tag_prefix(ns, name);
499 let (_, removed) = ProjectKnowledge::mutate_locked(project_root, |k| {
500 let before = k.facts.len();
501 k.facts.retain(|f| {
502 !f.imported_from
503 .as_deref()
504 .and_then(import_tag_source)
505 .is_some_and(|source| source.starts_with(&prefix))
506 });
507 let removed = before - k.facts.len();
508 if removed > 0 {
509 k.rebuild_index();
510 }
511 removed
512 })?;
513 Ok(removed)
514}
515
516pub fn remove_all_pulled(project_root: &str) -> Result<usize, String> {
525 ProjectKnowledge::remove_facts_locked(project_root, |f| {
526 f.imported_from
527 .as_deref()
528 .and_then(import_tag_source)
529 .is_some()
530 })
531}
532
533pub fn sync_into_knowledge(
537 project_root: &str,
538 ns: &str,
539 name: &str,
540 revision: u64,
541 doc: &ResearchContextDocumentV1,
542) -> Result<(usize, usize), String> {
543 if served_by_replica(ns, name) {
544 return Ok((0, remove_pulled(project_root, ns, name)?));
545 }
546 let policy = lean_ctx::core::memory_policy::MemoryPolicy::default();
547 let prefix = import_tag_prefix(ns, name);
548 let tag = format!("{IMPORT_TAG_SCHEME}{prefix}{revision}");
549 let category = knowledge_category(ns, name);
550 let (_, counts) = ProjectKnowledge::mutate_locked(project_root, |k| {
551 let before = k.facts.len();
552 k.facts.retain(|f| {
553 !f.imported_from
554 .as_deref()
555 .and_then(import_tag_source)
556 .is_some_and(|source| source.starts_with(&prefix))
557 });
558 let removed = before - k.facts.len();
559 if removed > 0 {
560 k.rebuild_index();
561 }
562 let mut loaded = 0usize;
563 for fact in &doc.facts {
564 let key = pulled_fact_key(&fact.id);
568 let value = crate::untrusted::wrap(
569 crate::untrusted::UntrustedKind::Knowledge,
570 &tag,
571 &fact.statement,
572 );
573 k.remember(&category, &key, &value, &tag, 0.8, &policy);
574 if let Some(last) = k
575 .facts
576 .iter_mut()
577 .rev()
578 .find(|f| f.category == category && f.key == key && f.is_current())
579 {
580 last.imported_from = Some(tag.clone());
581 last.anchors.clone_from(&fact.anchors);
584 loaded += 1;
585 }
586 }
587 (loaded, removed)
588 })?;
589 Ok(counts)
590}
591
592#[cfg(test)]
593mod tests {
594 use super::*;
595
596 #[test]
597 fn ids_and_kinds_are_stable() {
598 assert_eq!(
599 fact_id("decision", "db-choice", "Postgres"),
600 fact_id("decision", "db-choice", "Postgres")
601 );
602 assert_ne!(
603 fact_id("decision", "db-choice", "Postgres"),
604 fact_id("decision", "db-choice", "MySQL")
605 );
606 assert!(fact_id("decision", "DB Choice!", "x").starts_with("lc-db-choice-"));
607 assert_eq!(kind_of(NodeType::Decision), "decision");
608 assert_eq!(kind_of(NodeType::Finding), "observation");
609 }
610
611 #[test]
614 fn pulled_copies_of_a_vault_are_removed_and_nothing_else() {
615 let _data = lean_ctx::core::data_dir::isolated_data_dir();
616 let dir = tempfile::tempdir().unwrap();
617 let root = dir.path().to_string_lossy().into_owned();
618 let doc = |statement: &str| ResearchContextDocumentV1 {
619 facts: vec![FactV1 {
620 id: "f1".into(),
621 statement: statement.into(),
622 kind: "observation".into(),
623 applies_to: vec![],
624 sources: vec![],
625 from_contributions: vec![],
626 anchors: vec![],
627 }],
628 ..ResearchContextDocumentV1::default()
629 };
630 sync_into_knowledge(&root, "acme", "pay", 3, &doc("Pay copies this claim.")).unwrap();
631 sync_into_knowledge(&root, "acme", "other", 1, &doc("Other vault claim here.")).unwrap();
632 let policy = lean_ctx::core::memory_policy::MemoryPolicy::default();
633 ProjectKnowledge::mutate_locked(&root, |k| {
634 k.remember("arch", "own", "My own claim stays here.", "s", 0.9, &policy);
635 })
636 .unwrap();
637
638 assert_eq!(remove_pulled(&root, "acme", "pay").unwrap(), 1);
639 let k = ProjectKnowledge::load(&root).unwrap();
640 let values: Vec<&str> = k.facts.iter().map(|f| f.value.as_str()).collect();
641 assert!(values.iter().any(|v| v.contains("Other vault claim")));
642 assert!(values.contains(&"My own claim stays here."));
643 assert!(!values.iter().any(|v| v.contains("Pay copies")));
644 assert_eq!(remove_pulled(&root, "acme", "pay").unwrap(), 0);
645 }
646}