1pub 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#[derive(Debug, Default)]
26pub struct MineReport {
27 pub created: Vec<String>,
28 pub merged: Vec<String>,
29 pub unchanged: Vec<String>,
30 pub skipped: Vec<(String, String)>,
32 pub candidates_seen: usize,
33 pub output_dir: String,
34 pub notices: Vec<RuleNotice>,
36}
37
38#[derive(Debug, Clone)]
40pub struct RuleSummary {
41 pub slug: String,
42 pub version: u32,
43 pub title: String,
44}
45
46#[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#[derive(Debug, Default)]
58pub struct RuleListing {
59 pub rules: Vec<RuleSummary>,
60 pub notices: Vec<RuleNotice>,
61}
62
63fn 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
79fn 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
89pub 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 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
128enum Refused {
130 Withheld(String),
132 Failed(String),
134}
135
136fn 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
162pub 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 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 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 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
219pub 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
226fn 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 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 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 provenance::carry_over(&src, &dst, &content)?;
254 Ok(dst.display().to_string())
255}
256
257fn 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
282fn 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
298pub 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 #[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 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 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 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 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 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 #[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 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 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}