1use std::path::PathBuf;
11
12use serde::{Deserialize, Serialize};
13
14use crate::core::rules_canonical::RulesFile;
15pub use crate::core::rules_canonical::{END_MARK, RULES_VERSION, START_MARK};
16
17mod content;
18mod detect;
19mod skills;
20mod targets;
21#[cfg(test)]
22mod tests;
23mod write;
24
25pub use content::cursor_mdc_document;
26pub use content::{
27 GEMINI_DEDICATED_CONTEXT_FILENAME, antigravity_dedicated_rules_path,
28 gemini_dedicated_rules_path, opencode_dedicated_rules_path,
29};
30pub use skills::{
31 install_all_skills, install_skill_for_agent, install_skills_where, planned_skill_files,
32};
33
34fn shared_surface_profile(
38 cfg: &crate::core::config::Config,
39) -> crate::core::tool_profiles::ToolProfile {
40 crate::core::tool_visibility::guidance_profile(cfg, "")
41}
42
43pub fn canonical_rules_block() -> String {
45 let cfg = crate::core::config::Config::load();
46 let shadow = cfg.shadow_mode;
47 let level = crate::core::config::CompressionLevel::effective(&cfg);
48 let profile = shared_surface_profile(&cfg);
49 crate::core::rules_canonical::render(
50 shadow,
51 crate::core::rules_canonical::Wrapper::Shared,
52 level,
53 &profile,
54 )
55}
56pub fn rules_shared_content() -> String {
57 canonical_rules_block()
58}
59pub fn rules_dedicated_markdown() -> String {
60 let cfg = crate::core::config::Config::load();
61 let shadow = cfg.shadow_mode;
62 let level = crate::core::config::CompressionLevel::effective(&cfg);
63 let profile = shared_surface_profile(&cfg);
64 crate::core::rules_canonical::render(
65 shadow,
66 crate::core::rules_canonical::Wrapper::Dedicated,
67 level,
68 &profile,
69 )
70}
71
72pub fn rules_longform_markdown() -> String {
76 let cfg = crate::core::config::Config::load();
77 let shadow = cfg.shadow_mode;
78 let level = crate::core::config::CompressionLevel::effective(&cfg);
79 let profile = shared_surface_profile(&cfg);
80 crate::core::rules_canonical::render(
81 shadow,
82 crate::core::rules_canonical::Wrapper::Longform,
83 level,
84 &profile,
85 )
86}
87
88pub fn expected_blocks_by_target(
97 home: &std::path::Path,
98) -> std::collections::HashMap<String, String> {
99 let injection = crate::core::config::Config::load().rules_injection_effective();
100 let cfg = crate::core::config::Config::load();
101 build_rules_targets(home, injection)
102 .into_iter()
103 .map(|target| {
104 let expected = write::fresh_block(&cfg, &target);
108 (target.name.to_string(), expected)
109 })
110 .collect()
111}
112
113use detect::is_tool_detected;
114use targets::build_rules_targets;
115use write::inject_rules;
116
117struct RulesTarget {
118 name: &'static str,
119 path: PathBuf,
120 format: RulesFormat,
121}
122
123enum RulesFormat {
124 SharedMarkdown,
125 DedicatedMarkdown,
126 CursorMdc,
127 AntigravityRule,
130}
131
132#[derive(Debug, Default)]
133pub struct InjectResult {
134 pub injected: Vec<String>,
135 pub updated: Vec<String>,
136 pub already: Vec<String>,
137 pub errors: Vec<String>,
138 pub backed_up: Vec<String>,
139}
140
141#[derive(Debug, Clone, Serialize, Deserialize)]
142pub struct RulesTargetStatus {
143 pub name: String,
144 pub detected: bool,
145 pub path: String,
146 pub state: String,
147 pub note: Option<String>,
148}
149
150enum RulesResult {
151 Updated,
152 AlreadyPresent,
153}
154
155pub fn inject_all_rules(home: &std::path::Path) -> InjectResult {
156 inject_rules_where(home, &|_| true)
157}
158
159fn rules_agent_key(target_name: &str) -> Option<&'static str> {
162 Some(match target_name {
163 "Gemini CLI" => "gemini",
164 "VS Code" => "vscode",
165 "Copilot CLI" => "copilot",
166 "Cursor" => "cursor",
167 "Windsurf" => "windsurf",
168 "Zed" => "zed",
169 "Cline" => "cline",
170 "Roo Code" => "roo",
171 "OpenCode" => "opencode",
172 "Continue" => "continue",
173 "Amp" => "amp",
174 "Qwen Code" => "qwen",
175 "Trae" => "trae",
176 "Amazon Q Developer" => "amazonq",
177 "JetBrains IDEs" => "jetbrains",
178 "Antigravity" => "antigravity",
179 "Pi Coding Agent" => "pi",
180 "AWS Kiro" => "kiro",
181 "Verdent" => "verdent",
182 "Crush" => "crush",
183 "Augment" => "augment",
184 "OpenClaw" => "openclaw",
185 "Grok" => "grok",
186 "Oh My Pi" => "omp",
187 "Hermes Agent" => "hermes",
188 "Qoder" => "qoder",
189 _ => return None,
190 })
191}
192
193#[must_use]
197pub fn planned_rules_files(
198 home: &std::path::Path,
199 allows: &dyn Fn(&str) -> bool,
200) -> Vec<(String, PathBuf)> {
201 let cfg = crate::core::config::Config::load();
202 let injection = cfg.rules_injection_effective();
203 if cfg.rules_scope_effective() == crate::core::config::RulesScope::Project
204 || injection == crate::core::config::RulesInjection::Off
205 {
206 return Vec::new();
207 }
208 let mut files = Vec::new();
209 if injection == crate::core::config::RulesInjection::Shared
210 && allows("claude")
211 && detect::is_named_agent_ready("Claude Code", home)
212 {
213 files.push((
214 "Claude Code".to_string(),
215 crate::core::editor_registry::claude_state_dir(home).join("CLAUDE.md"),
216 ));
217 }
218 for target in build_rules_targets(home, injection) {
219 if rules_agent_key(target.name).is_some_and(allows) && is_tool_detected(&target, home) {
220 files.push((target.name.to_string(), target.path));
221 }
222 }
223 files
224}
225
226pub fn inject_rules_where(home: &std::path::Path, allows: &dyn Fn(&str) -> bool) -> InjectResult {
228 let cfg = crate::core::config::Config::load();
229 if cfg.rules_scope_effective() == crate::core::config::RulesScope::Project {
230 return InjectResult::default();
231 }
232 if cfg.rules_injection_effective() == crate::core::config::RulesInjection::Off {
233 return InjectResult::default();
234 }
235
236 let targets = build_rules_targets(home, cfg.rules_injection_effective());
237
238 let mut result = InjectResult::default();
239
240 if cfg.rules_injection_effective() == crate::core::config::RulesInjection::Shared
241 && allows("claude")
242 && detect::is_named_agent_ready("Claude Code", home)
243 {
244 sync_claude_pointer_block(home, &mut result);
245 }
246
247 for target in &targets {
248 if !rules_agent_key(target.name).is_some_and(allows) {
249 continue;
250 }
251 if !is_tool_detected(target, home) {
252 continue;
253 }
254 if rules_agent_key(target.name)
255 .is_some_and(|key| crate::core::governor_hosts::is_installed(key, home))
256 {
257 continue;
258 }
259 if !detect::is_mcp_configured(target, home) {
263 continue;
264 }
265
266 remove_legacy_rules_file(target.name, home);
267 let bak_path = target.path.with_extension(format!(
268 "{}.bak",
269 target
270 .path
271 .extension()
272 .and_then(|e| e.to_str())
273 .unwrap_or("")
274 ));
275 let bak_existed_before = bak_path.exists();
276 let bak_mtime_before = bak_existed_before
277 .then(|| {
278 std::fs::metadata(&bak_path)
279 .ok()
280 .and_then(|m| m.modified().ok())
281 })
282 .flatten();
283
284 let injected = inject_rules(target);
285 if injected.is_ok()
288 && cfg.rules_injection_effective() == crate::core::config::RulesInjection::Dedicated
289 {
290 retire_shared_block(target, home);
291 }
292 match injected {
293 Ok(RulesResult::Updated) => {
294 result.updated.push(target.name.to_string());
295 let bak_is_new = if bak_existed_before {
296 std::fs::metadata(&bak_path)
297 .ok()
298 .and_then(|m| m.modified().ok())
299 != bak_mtime_before
300 } else {
301 bak_path.exists()
302 };
303 if bak_is_new {
304 result
305 .backed_up
306 .push(bak_path.to_string_lossy().to_string());
307 }
308 }
309 Ok(RulesResult::AlreadyPresent) => result.already.push(target.name.to_string()),
310 Err(e) => result.errors.push(format!("{}: {e}", target.name)),
311 }
312 }
313
314 result
315}
316
317pub fn inject_rules_for_agent(home: &std::path::Path, agent_key: &str) -> InjectResult {
319 let cfg = crate::core::config::Config::load();
320 if cfg.rules_scope_effective() == crate::core::config::RulesScope::Project {
321 return InjectResult::default();
322 }
323 if cfg.rules_injection_effective() == crate::core::config::RulesInjection::Off {
324 return InjectResult::default();
325 }
326
327 if crate::core::governor_hosts::is_installed(agent_key, home) {
329 return InjectResult::default();
330 }
331 let targets = build_rules_targets(home, cfg.rules_injection_effective());
332 let mut result = InjectResult::default();
333
334 if cfg.rules_injection_effective() == crate::core::config::RulesInjection::Shared
335 && is_claude_agent_key(agent_key)
336 {
337 sync_claude_pointer_block(home, &mut result);
338 return result;
339 }
340
341 for target in &targets {
342 if !match_agent_name(agent_key, target.name) {
343 continue;
344 }
345
346 remove_legacy_rules_file(target.name, home);
347 let bak_path = target.path.with_extension(format!(
348 "{}.bak",
349 target
350 .path
351 .extension()
352 .and_then(|e| e.to_str())
353 .unwrap_or("")
354 ));
355 let bak_existed_before = bak_path.exists();
356
357 let injected = inject_rules(target);
358 if injected.is_ok()
361 && cfg.rules_injection_effective() == crate::core::config::RulesInjection::Dedicated
362 {
363 retire_shared_block(target, home);
364 }
365 match injected {
366 Ok(RulesResult::Updated) => {
367 result.updated.push(target.name.to_string());
368 if !bak_existed_before && bak_path.exists() {
369 result
370 .backed_up
371 .push(bak_path.to_string_lossy().to_string());
372 }
373 }
374 Ok(RulesResult::AlreadyPresent) => result.already.push(target.name.to_string()),
375 Err(e) => result.errors.push(format!("{}: {e}", target.name)),
376 }
377 }
378
379 result
380}
381
382fn legacy_rules_path(target_name: &str, home: &std::path::Path) -> Option<PathBuf> {
386 match target_name {
387 "Antigravity" => Some(home.join(".gemini/antigravity/rules/lean-ctx.md")),
388 "Pi Coding Agent" => Some(home.join(".pi/rules/lean-ctx.md")),
389 _ => None,
390 }
391}
392
393fn remove_legacy_rules_file(target_name: &str, home: &std::path::Path) {
394 let Some(path) = legacy_rules_path(target_name, home) else {
395 return;
396 };
397 let ours = std::fs::read_to_string(&path).is_ok_and(|content| {
398 crate::marked_block::contains_marker_line(
399 &content,
400 crate::core::rules_canonical::START_MARK,
401 )
402 });
403 if ours {
404 let _ = std::fs::remove_file(&path);
405 }
406}
407
408fn retire_shared_block(target: &RulesTarget, home: &std::path::Path) {
414 let shared = build_rules_targets(home, crate::core::config::RulesInjection::Shared);
415 let Some(path) = shared
416 .iter()
417 .find(|t| t.name == target.name && t.path != target.path)
418 .filter(|t| matches!(t.format, RulesFormat::SharedMarkdown))
419 .map(|t| t.path.clone())
420 else {
421 return;
422 };
423 let Ok(content) = std::fs::read_to_string(&path) else {
424 return;
425 };
426 let file = RulesFile::parse(&content);
427 if !file.has_content() || file.is_unterminated() {
428 return;
429 }
430 let cleaned = file.without_section();
431 let outcome = if cleaned.trim().is_empty() {
432 std::fs::remove_file(&path).map_err(|e| e.to_string())
433 } else {
434 let cleaned = crate::marked_block::with_line_endings_of(
435 &content,
436 format!("{}\n", cleaned.trim_end()),
437 );
438 crate::config_io::write_atomic_with_backup(&path, &cleaned)
439 };
440 if let Err(e) = outcome {
441 tracing::warn!(
442 "could not remove the lean-ctx block from {}: {e}",
443 path.display()
444 );
445 }
446}
447
448fn is_claude_agent_key(agent_key: &str) -> bool {
449 matches!(
450 agent_key.trim().to_ascii_lowercase().as_str(),
451 "claude" | "claude-code" | "claude_code" | "claude code"
452 )
453}
454
455fn sync_claude_pointer_block(home: &std::path::Path, result: &mut InjectResult) {
456 let mode = crate::core::hook_mode::recommend_hook_mode("claude");
457 match crate::core::claude_md::sync_claude_global_rules_block(home, mode) {
458 Ok(true) => result.updated.push("Claude Code".to_string()),
459 Ok(false) => result.already.push("Claude Code".to_string()),
460 Err(error) => result.errors.push(format!("Claude Code: {error}")),
461 }
462}
463
464#[must_use]
467pub fn any_rules_marker_present(home: &std::path::Path) -> bool {
468 use crate::core::config::RulesInjection;
469 let mut seen = std::collections::HashSet::new();
470 for injection in [RulesInjection::Shared, RulesInjection::Dedicated] {
471 for target in build_rules_targets(home, injection) {
472 if !seen.insert(target.path.clone()) {
473 continue;
474 }
475 if let Ok(content) = std::fs::read_to_string(&target.path)
476 && RulesFile::parse(&content).has_content()
477 {
478 return true;
479 }
480 }
481 }
482 false
483}
484
485#[must_use]
491pub fn host_guidance_present(home: &std::path::Path) -> bool {
492 use crate::core::editor_registry::{claude_state_dir, codebuddy_state_dir};
493 any_rules_marker_present(home)
494 || pointer_block_present(&[
495 claude_state_dir(home).join("CLAUDE.md"),
496 codebuddy_state_dir(home).join("CODEBUDDY.md"),
497 ])
498}
499
500fn pointer_block_present(files: &[std::path::PathBuf]) -> bool {
501 files.iter().any(|path| {
502 std::fs::read_to_string(path)
504 .is_ok_and(|c| c.contains(crate::core::rules_canonical::AGENTS_BLOCK_START))
505 })
506}
507
508fn match_agent_name(cli_key: &str, target_name: &str) -> bool {
509 let needle = cli_key.to_lowercase();
510 let tn = target_name.to_lowercase();
511 if needle == "pi" {
512 return tn.contains("pi coding");
513 }
514 if needle == "omp" {
515 return tn.contains("oh my pi");
516 }
517 needle.contains(&tn)
518 || tn.contains(&needle)
519 || (needle.contains("cursor") && tn.contains("cursor"))
520 || (needle.contains("claude") && tn.contains("claude"))
521 || (needle.contains("codebuddy") && tn.contains("codebuddy"))
522 || (needle.contains("windsurf") && tn.contains("windsurf"))
523 || (needle.contains("codex") && tn.contains("claude"))
524 || (needle.contains("zed") && tn.contains("zed"))
525 || (needle.contains("copilot") && tn.contains("copilot"))
526 || (needle.contains("jetbrains") && tn.contains("jetbrains"))
527 || (needle.contains("kiro") && tn.contains("kiro"))
528 || (needle.contains("gemini") && tn.contains("gemini"))
529 || (needle == "opencode" && tn.contains("opencode"))
530 || (needle == "cline" && tn.contains("cline"))
531 || (needle == "roo" && tn.contains("roo"))
532 || (needle == "amp" && tn.contains("amp"))
533 || (needle == "trae" && tn.contains("trae"))
534 || (needle == "amazonq" && tn.contains("amazon"))
535 || (needle == "crush" && tn.contains("crush"))
536 || (needle == "verdent" && tn.contains("verdent"))
537 || (needle == "continue" && tn.contains("continue"))
538 || (needle == "qwen" && tn.contains("qwen"))
539 || (needle == "antigravity" && tn.contains("antigravity"))
540 || (needle == "augment" && tn.contains("augment"))
541 || (needle == "openclaw" && tn.contains("openclaw"))
542 || (needle == "grok" && tn.contains("grok"))
543 || (needle == "vscode" && (tn.contains("vs code") || tn.contains("vscode")))
544}
545
546pub fn check_rules_freshness(client_name: &str) -> Option<String> {
548 let home = dirs::home_dir()?;
549 check_rules_freshness_at_home(client_name, &home)
550}
551
552fn check_rules_freshness_at_home(client_name: &str, home: &std::path::Path) -> Option<String> {
553 let cfg = crate::core::config::Config::load();
554 if cfg.declines_rule_steering()
555 || cfg.rules_scope_effective() == crate::core::config::RulesScope::Project
556 {
557 return None;
558 }
559 let injection = cfg.rules_injection_effective();
560 let targets = build_rules_targets(home, injection);
561
562 let matched: Vec<&RulesTarget> = targets
563 .iter()
564 .filter(|t| match_agent_name(client_name, t.name))
565 .collect();
566
567 if matched.is_empty() {
568 return None;
569 }
570
571 for target in &matched {
572 if !is_tool_detected(target, home) || !detect::is_mcp_configured(target, home) {
575 continue;
576 }
577 if !target.path.exists() {
578 continue;
579 }
580 let content = std::fs::read_to_string(&target.path).ok()?;
581 let file = RulesFile::parse(&content);
582 if file.has_content() && !file.is_current() {
583 return Some(format!(
584 "[RULES OUTDATED] Your {} rules were written by an older lean-ctx version. \
585 Re-read your rules file ({}) or run `lean-ctx setup` to update, \
586 then start a new session for full compatibility.",
587 target.name,
588 target.path.display()
589 ));
590 }
591 }
592
593 None
594}
595
596pub fn collect_rules_status(home: &std::path::Path) -> Vec<RulesTargetStatus> {
597 let injection = crate::core::config::Config::load().rules_injection_effective();
598 let targets = build_rules_targets(home, injection);
599 let mut out = Vec::new();
600
601 for target in &targets {
602 let detected = is_tool_detected(target, home);
603 let path = target.path.to_string_lossy().to_string();
604
605 let state = if !detected {
606 "not_detected".to_string()
607 } else if !target.path.exists() {
608 "missing".to_string()
609 } else {
610 match std::fs::read_to_string(&target.path) {
611 Ok(content) => {
612 let file = RulesFile::parse(&content);
613 if file.has_content() {
614 if file.is_current() {
615 "up_to_date".to_string()
616 } else {
617 "outdated".to_string()
618 }
619 } else {
620 "present_without_marker".to_string()
621 }
622 }
623 Err(_) => "read_error".to_string(),
624 }
625 };
626
627 out.push(RulesTargetStatus {
628 name: target.name.to_string(),
629 detected,
630 path,
631 state,
632 note: None,
633 });
634 }
635
636 out
637}