Skip to main content

lean_ctx_cloud/knowledge/
learn.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Bridges between LeanCTX project knowledge and Cloud repo knowledge.
3//!
4//! * [`plan_learn`] turns what the agent learned in a project since the last
5//!   draft into new repo facts: every fact through the capture gate
6//!   ([`crate::capture`]: one claim, a reference, evidence,
7//!   dedupe, admission, screening), stable content ids, a lean-ctx
8//!   provenance source.
9//! * [`sync_into_knowledge`] makes a pulled revision available to the agent
10//!   like an installed package: merged into the project knowledge store,
11//!   tagged with `imported_from`, replaced on every new revision.
12
13use 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/// What [`plan_learn`] proposes.
22#[derive(Debug, Clone, Default)]
23pub struct LearnPlan {
24    pub added: Vec<FactV1>,
25    /// `(category/key, reason)` of every fact the gate refused; texts are
26    /// never included.
27    pub dropped: Vec<(String, ReasonCode)>,
28    /// Near duplicates that bring references the held fact lacks: `(id of
29    /// the held fact, new references)`, for the event builder (V4).
30    pub merges: Vec<(String, Vec<String>)>,
31    /// `created_at` of the newest fact considered; the next draft starts after it.
32    pub watermark: Option<UtcDateTime>,
33    /// [`plan_import`]: the import source of each fact in `added` (same
34    /// order), `import:docs:<path>#<slug>` or `import:git:<sha>`.
35    pub import_sources: Vec<String>,
36    /// Every fact in `added`, as the gate passed it (same order): what the
37    /// event path (C0 2.0) builds its `node.add` from.
38    pub captured: Vec<capture::CapturedFact>,
39}
40
41/// Lowercase ASCII slug: alphanumerics kept, runs of anything else → `-`.
42fn 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
67/// Stable id from content: `lc-<key-slug>-<sha256(category, key, value)[..8]>`.
68pub 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
78/// The C0 1.x fact kind of a captured node type.
79pub 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
88/// The node type a held C0 1.x fact counts as for dedupe.
89fn 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
98/// The text a C0 1.x fact carries for a captured candidate: the claim, or a
99/// procedure's title with its numbered steps.
100fn 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
118/// A fact the agent itself learned in this project: not imported (packages,
119/// Cloud revisions), current, not a machine-derived capture. Its sensitivity
120/// is the gate's rule G11.
121fn 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
127/// A fact `lean-ctx import docs|git` made from the repository itself (K1):
128/// current, not machine-derived, public. Cloud revisions and packages are
129/// imported too, but never proposed back.
130fn 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
138/// The contract's import source of an imported fact, from its anchor key:
139/// `git:<sha>` → `import:git:<sha>`, `<path>#<section path>/<n>` →
140/// `import:docs:<path>#<section slug>` (the section path through the
141/// contract's `ctxpkg::import_slug`). `None` when the key names neither.
142pub 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(&section.replace('/', " "))
151            )
152        }
153        _ => return None,
154    };
155    lean_ctx_protocol::cloud::knowledge::import_source_ok(&source).then_some(source)
156}
157
158/// Plan the facts learned after `since` (and those waiting for their commit)
159/// that pass the capture gate and the repo does not hold yet, at most
160/// `limit` of them (oldest first).
161pub 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
171/// Plan the imported facts (K1) new or changed after `since` that pass the
172/// capture gate (evidence `imported`, the import source as reference) and
173/// the repo does not hold yet, at most `limit` (oldest first), each with
174/// its import source.
175pub 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
185/// When an imported fact last changed (a re-import updates in place).
186fn changed_at(f: &KnowledgeFact) -> UtcDateTime {
187    f.created_at.max(f.last_confirmed)
188}
189
190/// The reference an import source names: `file:<path>` for docs,
191/// `commit:<sha>` for git history.
192fn 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
200/// The dedupe index of what the repo holds.
201fn 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    // A learned fact counts from its creation, or from the `remember` that
235    // last changed its capture fields (refs added to a fact the gate had
236    // already rejected for having none).
237    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            // V9: a fact learned in a session names it (keyed when it is
332            // signed), an import or a fact without a session names none.
333            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
360/// The capture pipeline for one fact (SPEC-ENGINE §3.1.2 steps 2–5): shape,
361/// gate rules, admission, screening, dedupe. On success the candidate joins
362/// `index` and its valid references are returned.
363fn capture_one(
364    f: &KnowledgeFact,
365    import: Option<&str>,
366    run: &mut CaptureRun<'_>,
367    index: &mut dedupe::Index,
368) -> Result<Captured, Rejected> {
369    // J2: anchors go along when their paths and symbols pass screening (a
370    // path is information); otherwise the fact goes without them, and they
371    // do not count as its references either.
372    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
437/// A fact that passed the gate.
438struct Captured {
439    candidate: capture::CaptureCandidate,
440    /// Its valid references.
441    refs: Vec<String>,
442    /// The anchors that go with it.
443    anchors: Vec<lean_ctx::core::knowledge::anchors::CodeAnchor>,
444}
445
446/// Project-knowledge category for a Cloud repo's facts.
447pub 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
457/// The project-knowledge key of a pulled fact: its Cloud id when that is a
458/// strict token (`[A-Za-z0-9][A-Za-z0-9._-]{0,79}`: every id engines and
459/// Cloud make, `lc-…`, `cloud.…`, ULIDs), otherwise a digest of it.
460/// Renderers show keys outside the X5 fence, so a key carries no spaces,
461/// punctuation or length to phrase anything in; J2 reports the key back as
462/// the Cloud id, so real ids stay as they are.
463fn 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
478/// Whether the vault `@ns/name` is delivered from a local C0 2.0 replica
479/// (SPEC-ENGINE E2, V4.10): its revisions are then no longer copied into
480/// the project knowledge.
481pub fn served_by_replica(ns: &str, name: &str) -> bool {
482    let Ok(store) = crate::CloudStore::open() else {
483        return false;
484    };
485    crate::vault::connected_map(&store)
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
496/// Remove the facts copied in from `@ns/name` revisions. Returns how many.
497pub 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
516/// Remove every fact copied in from any Cloud vault (3.12.8 account scope):
517/// on disconnect nothing pulled for one account stays in the project
518/// knowledge another account would recall. Returns how many.
519///
520/// A pure removal by the store's own lock, without a policy admission: it
521/// also works for a checkout deleted since and for a root other than the
522/// project an MCP request is bound to, so the fail-closed account scope
523/// never gets stuck on one of them.
524pub 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
533/// Replace this repo's facts in the project knowledge store with `doc`.
534/// Returns `(loaded, removed)`. A vault served by a replica only loses its
535/// old copies (its knowledge is delivered from the replica, §3.5).
536pub 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            // X5: other members' text is stored fenced, so every renderer
565            // and every consumer of the store only ever sees it wrapped; the
566            // key stands outside the fence and is only ever a strict slug.
567            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                // J2: the code anchors travel with the fact, so recall marks
582                // it "to verify" once the anchored code changes here.
583                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    /// V4.10: once a replica serves the vault, the facts its 1.x revisions
612    /// copied in are removed; own facts and other vaults' copies stay.
613    #[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}