Skip to main content

lean_ctx_ext/core/skillify/
candidate.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Skill candidates mined from the project's session diary + knowledge facts.
3//!
4//! A candidate is a *distilled, potentially-reusable* pattern. We never invent
5//! content — every candidate is backed by a real diary entry or knowledge fact.
6
7use std::collections::HashMap;
8
9use crate::core::agents::{AgentDiary, DiaryEntryType};
10use crate::core::knowledge::ProjectKnowledge;
11
12/// A distilled pattern mined from a project's memory, before the gate decides
13/// whether it is durable enough to become a rule.
14#[derive(Debug, Clone)]
15pub struct SkillCandidate {
16    /// Normalized, prefix-free slug (e.g. `stop-before-build`).
17    pub slug: String,
18    /// One-line human title (becomes the rule `description`).
19    pub title: String,
20    /// The actionable body of the rule.
21    pub body: String,
22    /// Origin category (decision / insight / convention / …).
23    pub category: String,
24    /// How many sources reinforced this pattern (confirmations + mentions).
25    pub recurrence: u32,
26    /// Highest source confidence (0.0..=1.0).
27    pub confidence: f32,
28    /// Provenance: source session ids / agent ids.
29    pub sources: Vec<String>,
30    /// The stored items the candidate was distilled from, for the source
31    /// binding of its rule file (`provenance`).
32    pub derivation: Derivation,
33}
34
35/// What a candidate was distilled from: identities only, no source is named
36/// here. The sources are those the knowledge store bound each fact to, asked
37/// when the rule is written (`provenance::prepare`).
38#[derive(Debug, Clone, Default, PartialEq, Eq)]
39pub struct Derivation {
40    /// Project root as the knowledge store names it (the key of its facts).
41    pub store: String,
42    /// `(category, key, value)` of every fact merged into the candidate.
43    pub facts: Vec<(String, String, String)>,
44    /// A part without a source on record was merged in (a diary entry): the
45    /// rule is originless, whatever its facts are bound to.
46    pub unbound: bool,
47}
48
49impl Derivation {
50    fn of_fact(store: &str, category: &str, key: &str, value: &str) -> Self {
51        Self {
52            store: store.to_owned(),
53            facts: vec![(category.to_owned(), key.to_owned(), value.to_owned())],
54            unbound: false,
55        }
56    }
57
58    fn unbound() -> Self {
59        Self {
60            unbound: true,
61            ..Self::default()
62        }
63    }
64
65    /// A merged candidate derives from every part: all of them must hold.
66    fn join(&mut self, other: Self) {
67        if self.store.is_empty() {
68            self.store = other.store;
69        }
70        self.unbound |= other.unbound;
71        for fact in other.facts {
72            if !self.facts.contains(&fact) {
73                self.facts.push(fact);
74            }
75        }
76    }
77}
78
79/// Knowledge categories that can become durable guidance. Progress and raw
80/// blockers are status, not reusable rules, so they are excluded.
81fn knowledge_category_is_skillable(cat: &str) -> bool {
82    matches!(
83        cat.to_ascii_lowercase().as_str(),
84        "decision" | "insight" | "gotcha" | "pattern" | "convention" | "preference"
85    )
86}
87
88/// Mine candidates from the project's knowledge facts and agent diaries,
89/// merged by slug (recurrence summed, strongest body + confidence kept).
90pub fn mine_candidates(project_root: &str) -> Vec<SkillCandidate> {
91    let mut by_slug: HashMap<String, SkillCandidate> = HashMap::new();
92
93    // Source 1 — curated knowledge facts (already deduped by the knowledge layer).
94    // A candidate's body is the fact's value: only facts that may be
95    // delivered now are mined (`ProjectKnowledge::delivery_filter`).
96    let knowledge = ProjectKnowledge::load_or_create(project_root);
97    let deliverable = knowledge.delivery_filter();
98    for fact in &knowledge.facts {
99        // A skill is an instruction to agents: other members' knowledge
100        // pulled from Cloud is data (X5) and never becomes one.
101        if !knowledge_category_is_skillable(&fact.category)
102            || !deliverable(fact)
103            || fact.cloud_origin().is_some()
104        {
105            continue;
106        }
107        let title = title_from(&fact.key, &fact.value);
108        let slug = slugify(&title);
109        if slug.is_empty() {
110            continue;
111        }
112        let sources: Vec<String> = if fact.source_session.is_empty() {
113            Vec::new()
114        } else {
115            vec![fact.source_session.clone()]
116        };
117        merge_candidate(
118            &mut by_slug,
119            SkillCandidate {
120                slug,
121                title,
122                body: fact.value.trim().to_string(),
123                category: fact.category.to_ascii_lowercase(),
124                // Confirmations are explicit reinforcement; floor at 1.
125                recurrence: fact.confirmation_count.max(1),
126                confidence: fact.confidence,
127                sources,
128                derivation: Derivation::of_fact(
129                    &knowledge.project_root,
130                    &fact.category,
131                    &fact.key,
132                    &fact.value,
133                ),
134            },
135        );
136    }
137
138    // Source 2 — diary decisions / insights / discoveries across the project's agents.
139    for diary in AgentDiary::load_all_for_project(project_root) {
140        for entry in &diary.entries {
141            let category = match entry.entry_type {
142                DiaryEntryType::Decision => "decision",
143                DiaryEntryType::Insight => "insight",
144                DiaryEntryType::Discovery => "discovery",
145                DiaryEntryType::Progress | DiaryEntryType::Blocker => continue,
146            };
147            let body = entry.content.trim().to_string();
148            if body.is_empty() {
149                continue;
150            }
151            let title = title_from("", &body);
152            let slug = slugify(&title);
153            if slug.is_empty() {
154                continue;
155            }
156            merge_candidate(
157                &mut by_slug,
158                SkillCandidate {
159                    slug,
160                    title,
161                    body,
162                    category: category.to_string(),
163                    recurrence: 1,
164                    confidence: 0.6,
165                    sources: vec![diary.agent_id.clone()],
166                    derivation: Derivation::unbound(),
167                },
168            );
169        }
170    }
171
172    let mut out: Vec<SkillCandidate> = by_slug.into_values().collect();
173    out.sort_by(|a, b| {
174        b.recurrence
175            .cmp(&a.recurrence)
176            .then(b.confidence.total_cmp(&a.confidence))
177            .then(a.slug.cmp(&b.slug))
178    });
179    out
180}
181
182fn merge_candidate(map: &mut HashMap<String, SkillCandidate>, cand: SkillCandidate) {
183    if let Some(existing) = map.get_mut(&cand.slug) {
184        existing.recurrence = existing.recurrence.saturating_add(cand.recurrence);
185        existing.derivation.join(cand.derivation);
186        if cand.confidence > existing.confidence {
187            existing.confidence = cand.confidence;
188        }
189        // Prefer the longer, more informative body.
190        if cand.body.len() > existing.body.len() {
191            existing.body = cand.body;
192        }
193        for s in cand.sources {
194            if !s.is_empty() && !existing.sources.contains(&s) {
195                existing.sources.push(s);
196            }
197        }
198    } else {
199        map.insert(cand.slug.clone(), cand);
200    }
201}
202
203/// A concise title: prefer a short fact key, else the first sentence of the body.
204fn title_from(key: &str, value: &str) -> String {
205    let k = key.trim();
206    if !k.is_empty() && k.chars().count() <= 80 {
207        return k.to_string();
208    }
209    first_sentence(value)
210}
211
212fn first_sentence(text: &str) -> String {
213    let t = text.trim();
214    let end = t.find(['.', '\n', '!', '?']).unwrap_or(t.len());
215    let candidate = t[..end].trim();
216    let s = if candidate.is_empty() { t } else { candidate };
217    truncate_chars(s, 80)
218}
219
220/// URL/file-safe slug: lowercase alphanumerics, single dashes, trimmed, capped.
221pub(crate) fn slugify(text: &str) -> String {
222    let mut slug = String::new();
223    let mut prev_dash = false;
224    for ch in text.trim().to_ascii_lowercase().chars() {
225        if ch.is_ascii_alphanumeric() {
226            slug.push(ch);
227            prev_dash = false;
228        } else if !slug.is_empty() && !prev_dash {
229            slug.push('-');
230            prev_dash = true;
231        }
232    }
233    let trimmed = slug.trim_matches('-');
234    truncate_chars(trimmed, 50).trim_matches('-').to_string()
235}
236
237fn truncate_chars(s: &str, max: usize) -> String {
238    if s.chars().count() <= max {
239        return s.to_string();
240    }
241    s.chars().take(max).collect()
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247
248    #[test]
249    fn slugify_normalizes() {
250        assert_eq!(slugify("Stop before Build!"), "stop-before-build");
251        assert_eq!(slugify("  multiple   spaces  "), "multiple-spaces");
252        assert_eq!(slugify("___weird@@@chars###"), "weird-chars");
253        assert_eq!(slugify(""), "");
254    }
255
256    #[test]
257    fn first_sentence_truncates() {
258        assert_eq!(
259            first_sentence("Use atomic writes. And more."),
260            "Use atomic writes"
261        );
262        assert!(first_sentence(&"x".repeat(200)).chars().count() <= 80);
263    }
264
265    #[test]
266    fn merge_sums_recurrence_and_keeps_strongest() {
267        let mut map = HashMap::new();
268        merge_candidate(
269            &mut map,
270            SkillCandidate {
271                slug: "s".into(),
272                title: "t".into(),
273                body: "short".into(),
274                category: "decision".into(),
275                recurrence: 1,
276                confidence: 0.5,
277                sources: vec!["a".into()],
278                derivation: Derivation::default(),
279            },
280        );
281        merge_candidate(
282            &mut map,
283            SkillCandidate {
284                slug: "s".into(),
285                title: "t".into(),
286                body: "a much longer body".into(),
287                category: "decision".into(),
288                recurrence: 2,
289                confidence: 0.9,
290                sources: vec!["b".into()],
291                derivation: Derivation::default(),
292            },
293        );
294        let c = &map["s"];
295        assert_eq!(c.recurrence, 3);
296        assert_eq!(c.confidence, 0.9);
297        assert_eq!(c.body, "a much longer body");
298        assert_eq!(c.sources, vec!["a".to_string(), "b".to_string()]);
299    }
300
301    /// Only facts that are served now are mined into skill candidates.
302    #[test]
303    fn a_fact_that_is_not_served_is_not_mined() {
304        use crate::core::context_admission::stored::lineage_support::{
305            BOUND_FACT, TYPED_FACT, governed, project, scoped, two_facts, withdraw_source,
306        };
307        let _data = governed();
308        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
309        let (_directory, root) = project();
310        two_facts(&root, "decision");
311        let bodies = || -> Vec<String> {
312            scoped(&root, || mine_candidates(&root))
313                .into_iter()
314                .map(|candidate| candidate.body)
315                .collect()
316        };
317        let before = bodies();
318        assert!(before.contains(&BOUND_FACT.to_owned()), "{before:?}");
319        assert!(before.contains(&TYPED_FACT.to_owned()), "{before:?}");
320        withdraw_source(&root);
321        assert_eq!(bodies(), [TYPED_FACT.to_owned()]);
322    }
323}