Skip to main content

lean_ctx_ext/core/skillify/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Skillify (#290): distill a project's recurring session patterns into versioned,
3//! git-committable `.cursor/rules/skillify-*.mdc` rule files.
4//!
5//! Pipeline: [`candidate::mine_candidates`] (read diary + knowledge) →
6//! `gate::judge` (precision-biased KEEP/SKIP) → `rule_file::plan`
7//! (create / merge / unchanged). Runs on demand only; nothing is written unless
8//! the miner is invoked, and re-runs are idempotent.
9//!
10//! A rule file is a derived copy of the facts it was distilled from: it is
11//! bound to their sources when it is written and asked again before lean-ctx
12//! lists or promotes it (`provenance`).
13
14pub mod candidate;
15pub(crate) mod gate;
16mod provenance;
17pub(crate) mod rule_file;
18
19use std::path::{Path, PathBuf};
20
21use gate::Verdict;
22use rule_file::WriteOutcome;
23
24/// Summary of one mining run, for human + machine reporting.
25#[derive(Debug, Default)]
26pub struct MineReport {
27    pub created: Vec<String>,
28    pub merged: Vec<String>,
29    pub unchanged: Vec<String>,
30    /// `(title, reason)` for every rejected candidate.
31    pub skipped: Vec<(String, String)>,
32    pub candidates_seen: usize,
33    pub output_dir: String,
34    /// Rule files the run found and must not touch, sorted by path.
35    pub notices: Vec<RuleNotice>,
36}
37
38/// One generated rule on disk.
39#[derive(Debug, Clone)]
40pub struct RuleSummary {
41    pub slug: String,
42    pub version: u32,
43    pub title: String,
44}
45
46/// A rule file that needs the user's attention. Never a rule: the path, a
47/// reason code and a fixed sentence — nothing of the file's content.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct RuleNotice {
50    pub path: String,
51    pub code: &'static str,
52    pub reason: &'static str,
53}
54
55/// What `list` returns: the rules lean-ctx may show now, and — apart from
56/// them — the files it reports instead. Both sorted (#498).
57#[derive(Debug, Default)]
58pub struct RuleListing {
59    pub rules: Vec<RuleSummary>,
60    pub notices: Vec<RuleNotice>,
61}
62
63/// The walk every operation runs first (`provenance::review`), as notices.
64fn reviewed(output_root: &Path, project_root: &str) -> Vec<RuleNotice> {
65    provenance::review(output_root, project_root)
66        .into_iter()
67        .map(|(path, notice)| RuleNotice {
68            path: path.display().to_string(),
69            code: notice.code(),
70            reason: notice.sentence(),
71        })
72        .collect()
73}
74
75fn config() -> crate::core::config::SkillifyConfig {
76    crate::core::config::Config::load().skillify
77}
78
79/// Resolve the output root from the configured scope.
80fn output_root(project_root: &str, scope: &str) -> PathBuf {
81    if scope.eq_ignore_ascii_case("global")
82        && let Some(home) = dirs::home_dir()
83    {
84        return home;
85    }
86    PathBuf::from(project_root)
87}
88
89/// Run the miner end-to-end. Returns an error only when skillify is disabled or
90/// a write fails; an empty project simply yields an empty report.
91pub fn mine(project_root: &str) -> Result<MineReport, String> {
92    let cfg = config();
93    if !cfg.enabled {
94        return Err("skillify is disabled — set `[skillify] enabled = true`".to_string());
95    }
96    let root = output_root(project_root, &cfg.scope);
97    let now = lean_ctx_time::UtcDateTime::now().to_rfc3339();
98    let candidates = candidate::mine_candidates(project_root);
99
100    let mut report = MineReport {
101        candidates_seen: candidates.len(),
102        output_dir: rule_file::rules_dir(&root).display().to_string(),
103        // Rules whose sources were withdrawn leave the host's directory
104        // first; a rule that is derived again below is written anew through
105        // admission.
106        notices: reviewed(&root, project_root),
107        ..Default::default()
108    };
109
110    for c in &candidates {
111        match gate::judge(c, cfg.min_confidence, cfg.min_recurrence) {
112            Verdict::Skip(reason) => report.skipped.push((c.title.clone(), reason)),
113            Verdict::Keep => {
114                let full = rule_file::full_slug(&c.slug);
115                match write_rule(&root, project_root, c, &now) {
116                    Ok(WriteOutcome::Created) => report.created.push(full),
117                    Ok(WriteOutcome::Merged) => report.merged.push(full),
118                    Ok(WriteOutcome::Unchanged) => report.unchanged.push(full),
119                    Err(Refused::Withheld(reason)) => report.skipped.push((full, reason)),
120                    Err(Refused::Failed(error)) => return Err(error),
121                }
122            }
123        }
124    }
125    Ok(report)
126}
127
128/// Why a kept candidate did not become a rule file.
129enum Refused {
130    /// Not permitted now; the reason is typed and content-free.
131    Withheld(String),
132    /// The file system refused the write.
133    Failed(String),
134}
135
136/// Write the rule file of one kept candidate under `output_root`, for a
137/// request working in `project_root`.
138///
139/// A rule file is a persisted, git-committable artefact: only admitted text
140/// is written into it (E3), and it is a derived copy of the facts it was
141/// distilled from (G04) — its binding to their sources is decided before the
142/// write and recorded after it. An unchanged rule is bound again, so a rule
143/// written before bindings existed gets one on the next run.
144fn write_rule(
145    output_root: &Path,
146    project_root: &str,
147    candidate: &candidate::SkillCandidate,
148    now: &str,
149) -> Result<WriteOutcome, Refused> {
150    let admitted = admitted_candidate(candidate).map_err(Refused::Withheld)?;
151    let planned = rule_file::plan(output_root, &admitted, now);
152    let binding = provenance::prepare(&planned.text, &candidate.derivation, project_root)
153        .map_err(|withheld| Refused::Withheld(withheld.message("rule")))?;
154    planned.write().map_err(Refused::Failed)?;
155    if let Some(binding) = &binding {
156        provenance::record(&planned.path, binding).map_err(Refused::Failed)?;
157    }
158    provenance::release(&planned.path);
159    Ok(planned.outcome)
160}
161
162/// List the generated rules currently on disk for the configured scope.
163pub fn list_rules(project_root: &str) -> RuleListing {
164    let cfg = config();
165    let root = output_root(project_root, &cfg.scope);
166    let dir = rule_file::rules_dir(&root);
167    // Under protection: a rule lean-ctx wrote whose sources were withdrawn
168    // has left this directory now; one it must not touch is a notice, apart
169    // from the rules.
170    let mut listing = RuleListing {
171        rules: Vec::new(),
172        notices: reviewed(&root, project_root),
173    };
174    let out = &mut listing.rules;
175    let Ok(entries) = std::fs::read_dir(&dir) else {
176        return listing;
177    };
178    for entry in entries.flatten() {
179        let path = entry.path();
180        if path.extension().and_then(|e| e.to_str()) != Some("mdc") {
181            continue;
182        }
183        let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
184            continue;
185        };
186        if !stem.starts_with(rule_file::SLUG_PREFIX) {
187            continue;
188        }
189        // A rule is a derived copy: it is listed only while the sources it is
190        // bound to still admit it (`provenance::served`); a rule without a
191        // binding follows the originless rule.
192        let held = std::fs::read_to_string(&path)
193            .is_ok_and(|raw| provenance::served(&path, &raw, project_root).is_ok());
194        if !held {
195            continue;
196        }
197        // The listed title is content of a file in the output root: it is
198        // read through the common rooted admitted reader; a rule that is
199        // withheld is not listed.
200        if let Ok(content) = crate::core::rooted_read::read_file_for_tool_rooted(
201            &path.to_string_lossy(),
202            &root.to_string_lossy(),
203            "ctx_skillify",
204        ) {
205            let version = rule_file::parse_existing(&content).map_or(1, |r| r.version);
206            let title =
207                rule_file::extract_description(&content).unwrap_or_else(|| stem.to_string());
208            out.push(RuleSummary {
209                slug: stem.to_string(),
210                version,
211                title,
212            });
213        }
214    }
215    out.sort_by(|a, b| a.slug.cmp(&b.slug));
216    listing
217}
218
219/// Copy a project-scoped generated rule into the global `~/.cursor/rules` so it
220/// applies to every project. Returns the destination path on success.
221pub fn promote(project_root: &str, slug: &str) -> Result<String, String> {
222    let home = dirs::home_dir().ok_or("cannot resolve home directory")?;
223    promote_into(project_root, slug, &home)
224}
225
226/// [`promote`] into the rules directory under `home`. Nothing under `home`
227/// is created or written before every check has passed.
228fn promote_into(project_root: &str, slug: &str, home: &Path) -> Result<String, String> {
229    let full = if slug.starts_with(rule_file::SLUG_PREFIX) {
230        slug.to_string()
231    } else {
232        rule_file::full_slug(slug)
233    };
234    // The walk every operation runs first: a rule whose sources were
235    // withdrawn is no longer in the project to be promoted.
236    provenance::review(Path::new(project_root), project_root);
237    let src = rule_file::rule_path(&PathBuf::from(project_root), &full);
238    if !src.exists() {
239        return Err(format!("no generated rule `{full}` in this project"));
240    }
241    // Decided before anything outside the project is touched: the copy may
242    // exist (`promotable`), and the rule is still admitted by the sources it
243    // is bound to (`provenance::served`).
244    let content = promotable(&src, project_root)?;
245    provenance::served(&src, &content, project_root)
246        .map_err(|withheld| withheld.message("rule"))?;
247    let dst = rule_file::rule_path(home, &full);
248    if let Some(parent) = dst.parent() {
249        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
250    }
251    crate::config_io::write_atomic_with_backup(&dst, &content)?;
252    // The copy keeps the binding of its original: it stays as revocable.
253    provenance::carry_over(&src, &dst, &content)?;
254    Ok(dst.display().to_string())
255}
256
257/// The bytes a promotion copies out of the project: the ORIGINAL rule file,
258/// and only when the copy may exist. A promoted rule is a persisted copy
259/// outside the project, so the source must be admitted, complete and storable
260/// NOW (E3), and admission must leave it unchanged — a rule the current
261/// policy would mask is not copied as it is, and never copied masked.
262fn promotable(src: &std::path::Path, project_root: &str) -> Result<String, String> {
263    let mut remaining = crate::core::limits::max_read_bytes();
264    let read = crate::core::rooted_read::read_file_for_tool_rooted_admitted(
265        &src.to_string_lossy(),
266        project_root,
267        "ctx_skillify",
268        &mut remaining,
269    )
270    .map_err(|error| error.to_string())?;
271    let original = std::fs::read_to_string(src).map_err(|e| e.to_string())?;
272    if !read.storable || !read.complete || read.content != original {
273        return Err(
274            "rule withheld by the context gateway: its content may not be copied out of the \
275             project unchanged"
276                .to_string(),
277        );
278    }
279    Ok(original)
280}
281
282/// The candidate as it may be written to a rule file: title and body
283/// admitted for a derived store under the current policy. A candidate is
284/// distilled from knowledge facts and the session diary; a part that is
285/// withheld or restricted refuses the whole rule, with a content-free reason.
286fn admitted_candidate(
287    candidate: &candidate::SkillCandidate,
288) -> Result<candidate::SkillCandidate, String> {
289    use crate::core::context_admission::carrier::admit_for_store;
290    let admit = |text: &str| admit_for_store(text).map_err(|withheld| withheld.message("rule"));
291    Ok(candidate::SkillCandidate {
292        title: admit(&candidate.title)?,
293        body: admit(&candidate.body)?,
294        ..candidate.clone()
295    })
296}
297
298/// Current skillify configuration, for `status`.
299pub fn current_config() -> crate::core::config::SkillifyConfig {
300    config()
301}
302
303#[cfg(test)]
304mod admission_tests {
305    use super::*;
306
307    const AWS_KEY: &str = concat!("AK", "IAIOSFODNN7EXAMPLE");
308
309    fn candidate(body: &str) -> candidate::SkillCandidate {
310        candidate::SkillCandidate {
311            slug: "rotate-keys".into(),
312            title: "Rotate keys".into(),
313            body: body.into(),
314            category: "decision".into(),
315            recurrence: 3,
316            confidence: 0.8,
317            sources: vec!["sess1".into()],
318            derivation: candidate::Derivation::default(),
319        }
320    }
321
322    /// G04: a rule distilled from a fact that is bound to a file is bound to
323    /// that file. lean-ctx lists and promotes it while the file is admitted
324    /// and no longer once it is withdrawn; a rule distilled from a fact
325    /// without a source on record is originless and withheld under
326    /// protection. Refusals are typed and carry nothing of the rule.
327    #[test]
328    fn a_rule_is_used_only_while_the_sources_of_its_facts_admit_it() {
329        use crate::core::context_admission::stored::lineage_support::{
330            governed, project, scoped, two_facts, withdraw_source,
331        };
332        let _data = governed();
333        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
334        let (_directory, root) = project();
335        let output = Path::new(&root);
336        two_facts(&root, "decision");
337        // Under protection a rule is written only with a source on record:
338        // the one distilled from the bound fact is, the one from the typed
339        // fact is refused with a typed reason and leaves no file.
340        scoped(&root, || {
341            for mined in candidate::mine_candidates(&root) {
342                match write_rule(output, &root, &mined, "2026-01-01T00:00:00Z") {
343                    Ok(outcome) => {
344                        assert_eq!(mined.slug, "token-check");
345                        assert_eq!(outcome, WriteOutcome::Created);
346                    }
347                    Err(Refused::Withheld(reason)) => {
348                        assert_eq!(mined.slug, "release-duty");
349                        assert!(reason.contains("store.no_source_authority"), "{reason}");
350                    }
351                    Err(Refused::Failed(error)) => panic!("{error}"),
352                }
353            }
354        });
355        assert!(!rule_file::rule_path(output, "skillify-release-duty").exists());
356        let created = rule_file::rule_path(output, "skillify-token-check");
357        let text = std::fs::read_to_string(&created).expect("written rule");
358        // A sibling lean-ctx wrote from the same sources, edited by hand
359        // since, and a file that was there before bindings existed.
360        let sibling = rule_file::rule_path(output, "skillify-edited");
361        std::fs::write(&sibling, &text).expect("sibling");
362        provenance::carry_over(&created, &sibling, &text).expect("binding of the sibling");
363        let edited = format!("{text}\nA line added by hand.\n");
364        std::fs::write(&sibling, &edited).expect("hand edit");
365        let legacy = rule_file::rule_path(output, "skillify-legacy");
366        std::fs::write(&legacy, "Run the linter before a push.\n").expect("legacy rule");
367
368        let listed = || scoped(&root, || list_rules(&root));
369        let slugs = |listing: &RuleListing| -> Vec<String> {
370            listing.rules.iter().map(|rule| rule.slug.clone()).collect()
371        };
372        let notice = |path: &Path, code: &'static str| -> (String, &'static str) {
373            (path.display().to_string(), code)
374        };
375        let codes = |listing: &RuleListing| -> Vec<(String, &'static str)> {
376            listing
377                .notices
378                .iter()
379                .map(|notice| (notice.path.clone(), notice.code))
380                .collect()
381        };
382        // Served while its source is admitted. A notice is not a rule.
383        let before = listed();
384        assert_eq!(slugs(&before), ["skillify-token-check"]);
385        assert_eq!(
386            codes(&before),
387            [notice(&legacy, "rule.no_source_on_record")]
388        );
389
390        // Withdrawn: the rule lean-ctx wrote leaves the host's directory — a
391        // move, the bytes are kept — and the hand-edited one is left alone
392        // and reported, with nothing of either rule in the report. The
393        // quarantine is keyed by the canonical path of the rule while it
394        // exists, as the move computes it: once moved, the path no longer
395        // canonicalizes (on Windows the raw spelling then differs).
396        let (copy, origin) = provenance::quarantine_paths(&created).expect("quarantine");
397        withdraw_source(&root);
398        let after = listed();
399        assert!(slugs(&after).is_empty());
400        assert!(!created.exists());
401        assert_eq!(
402            std::fs::read_to_string(copy).ok().as_deref(),
403            Some(text.as_str())
404        );
405        assert!(origin.is_file());
406        assert_eq!(
407            std::fs::read_to_string(&sibling).ok().as_deref(),
408            Some(edited.as_str())
409        );
410        assert_eq!(
411            codes(&after),
412            [
413                notice(&sibling, "rule.edited_source_withdrawn"),
414                notice(&legacy, "rule.no_source_on_record"),
415            ]
416        );
417        assert!(
418            after
419                .notices
420                .iter()
421                .all(|notice| !notice.reason.contains("RS256"))
422        );
423
424        // After the move there is no rule to promote, and nothing is copied.
425        let home = tempfile::tempdir().expect("home");
426        let refused = scoped(&root, || promote_into(&root, "token-check", home.path()))
427            .expect_err("a moved rule is not promoted");
428        assert!(refused.contains("no generated rule"), "{refused}");
429        assert!(!home.path().join(".cursor").exists());
430    }
431
432    /// E3: a generated rule file was written with whatever the miner
433    /// distilled, and `promote` copied any rule file out of the project raw.
434    #[test]
435    fn rule_files_receive_admitted_text_and_only_unmasked_rules_are_promoted() {
436        use crate::core::context_admission::stored::lineage_support::{
437            bound_fact, project as canonical_project, scoped, withdraw_source,
438        };
439        let _data = crate::core::data_dir::isolated_data_dir();
440        let project = tempfile::tempdir().unwrap();
441        let root = project.path().to_string_lossy().into_owned();
442        let rule = |name: &str, content: &str| {
443            let path = rule_file::rule_path(project.path(), name);
444            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
445            std::fs::write(&path, content).unwrap();
446            path
447        };
448        {
449            let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
450            // Control: a clean candidate and a clean rule keep their bytes.
451            let clean = admitted_candidate(&candidate("Run the linter before a push.")).unwrap();
452            assert_eq!(clean.body, "Run the linter before a push.");
453            let path = rule("skillify-clean", "Run the linter before a push.\n");
454            assert_eq!(
455                promotable(&path, &root).as_deref(),
456                Ok("Run the linter before a push.\n")
457            );
458
459            let keyed = admitted_candidate(&candidate(&format!("Deploy with {AWS_KEY}.")));
460            assert!(keyed.is_ok_and(|rule| !rule.body.contains(AWS_KEY)));
461            let path = rule("skillify-keyed", &format!("Deploy with {AWS_KEY}.\n"));
462            let refused = promotable(&path, &root).expect_err("a masked rule is not copied");
463            assert!(!refused.contains(AWS_KEY), "{refused}");
464
465            // G04, Community developer mode: a rule bound to a source that is
466            // withdrawn is not moved (no protection claim) and is not copied
467            // out of the project — refused with the typed reason, nothing of
468            // the rule in it, nothing written under the home directory.
469            let (_bound, bound_root) = canonical_project();
470            let output = Path::new(&bound_root);
471            bound_fact(&bound_root, "decision");
472            scoped(&bound_root, || {
473                for mined in candidate::mine_candidates(&bound_root) {
474                    let written = write_rule(output, &bound_root, &mined, "2026-01-01T00:00:00Z");
475                    assert!(
476                        matches!(written, Ok(WriteOutcome::Created)),
477                        "{}",
478                        mined.slug
479                    );
480                }
481            });
482            let kept = rule_file::rule_path(output, "skillify-token-check");
483            assert!(kept.is_file());
484            withdraw_source(&bound_root);
485            let home = tempfile::tempdir().unwrap();
486            let refused = scoped(&bound_root, || {
487                promote_into(&bound_root, "token-check", home.path())
488            })
489            .expect_err("a rule whose source is withdrawn is not copied");
490            assert!(refused.contains("store.source_unavailable"), "{refused}");
491            assert!(!refused.contains("RS256"), "{refused}");
492            assert!(kept.is_file());
493            assert!(!home.path().join(".cursor").exists());
494        }
495        let policy = crate::core::policy::load(
496            "name = \"skillify-test\"\nversion = \"1.0.0\"\ndescription = \"test\"\n\
497             [filters]\nclassification = \"block\"\nblocked_labels = [\"CONFIDENTIAL\"]\n",
498        )
499        .unwrap();
500        let _policy = crate::core::policy::runtime::TestPolicyOverride::set(Some(policy));
501        let refused = admitted_candidate(&candidate("CONFIDENTIAL\nroadmap-marker"))
502            .expect_err("a blocked candidate is not written");
503        assert!(!refused.contains("roadmap-marker"), "{refused}");
504        let path = rule("skillify-plan", "CONFIDENTIAL\nroadmap-marker\n");
505        let refused = promotable(&path, &root).expect_err("a blocked rule is not copied");
506        assert!(!refused.contains("roadmap-marker"), "{refused}");
507    }
508}