Skip to main content

lean_ctx/rules_inject/
mod.rs

1//! Rules + SKILL.md injection for every supported agent, split by concern
2//! (GL#440): `content` (payloads), `targets` (agent catalog), `detect`
3//! (installation checks), `write` (atomic file surgery), `skills` (SKILL.md).
4//! This hub owns the shared types and the orchestration entry points.
5//!
6//! Content is delegated to `core::rules_canonical` — all rule text lives
7//! there as `pub const` sections.  Markers (`START_MARK`, `END_MARK`,
8//! `RULES_VERSION`) are also re-exported from canonical.
9
10use 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(crate) use content::cursor_mdc_document;
26pub use content::{
27    GEMINI_DEDICATED_CONTEXT_FILENAME, gemini_dedicated_rules_path, opencode_dedicated_rules_path,
28};
29pub use skills::{
30    install_all_skills, install_skill_for_agent, install_skills_where, planned_skill_files,
31};
32
33/// The tool set client-neutral rule files may name: what `tools/list` offers a
34/// client without quirks (the lean core when no profile is pinned). These files
35/// are shared by every agent in a home or project, so no client is known.
36fn shared_surface_profile(
37    cfg: &crate::core::config::Config,
38) -> crate::core::tool_profiles::ToolProfile {
39    crate::server::tool_visibility::guidance_profile(cfg, "")
40}
41
42/// Forwarding functions — content is delegated to `core::rules_canonical`.
43pub fn canonical_rules_block() -> String {
44    let cfg = crate::core::config::Config::load();
45    let shadow = cfg.shadow_mode;
46    let level = crate::core::config::CompressionLevel::effective(&cfg);
47    let profile = shared_surface_profile(&cfg);
48    crate::core::rules_canonical::render(
49        shadow,
50        crate::core::rules_canonical::Wrapper::Shared,
51        level,
52        &profile,
53    )
54}
55pub fn rules_shared_content() -> String {
56    canonical_rules_block()
57}
58pub fn rules_dedicated_markdown() -> String {
59    let cfg = crate::core::config::Config::load();
60    let shadow = cfg.shadow_mode;
61    let level = crate::core::config::CompressionLevel::effective(&cfg);
62    let profile = shared_surface_profile(&cfg);
63    crate::core::rules_canonical::render(
64        shadow,
65        crate::core::rules_canonical::Wrapper::Dedicated,
66        level,
67        &profile,
68    )
69}
70
71/// Long-form rules for the on-demand project `LEAN-CTX.md` (#578). Same
72/// config-driven shadow/compression handling as the dedicated render, but the
73/// LONGFORM profile with the verbose teaching sections.
74pub fn rules_longform_markdown() -> String {
75    let cfg = crate::core::config::Config::load();
76    let shadow = cfg.shadow_mode;
77    let level = crate::core::config::CompressionLevel::effective(&cfg);
78    let profile = shared_surface_profile(&cfg);
79    crate::core::rules_canonical::render(
80        shadow,
81        crate::core::rules_canonical::Wrapper::Longform,
82        level,
83        &profile,
84    )
85}
86
87/// The canonical rules block lean-ctx would write for each target, keyed by the
88/// target's display name.
89///
90/// Drift detection compares against this instead of guessing shared-vs-dedicated
91/// from a target's on-disk contents: a freshly synced `SharedMarkdown` file (e.g.
92/// Copilot CLI, Codex CLI) carries no user text, which a content heuristic
93/// mistook for the dedicated layout and then flagged as drifted on every sync.
94/// Keying by the real `RulesFormat` keeps `sync` and `diff` in agreement (#548).
95pub fn expected_blocks_by_target(
96    home: &std::path::Path,
97) -> std::collections::HashMap<String, String> {
98    let injection = crate::core::config::Config::load().rules_injection_effective();
99    let cfg = crate::core::config::Config::load();
100    let shadow = cfg.shadow_mode;
101    let level = crate::core::config::CompressionLevel::effective(&cfg);
102    build_rules_targets(home, injection)
103        .into_iter()
104        .map(|target| {
105            // The profile `inject_rules` writes with, so a freshly synced
106            // file never reads as drifted (#1008, #1849).
107            let profile = write::profile_for_target(&cfg, target.name);
108            let wrapper = match target.format {
109                RulesFormat::SharedMarkdown => crate::core::rules_canonical::Wrapper::Shared,
110                RulesFormat::DedicatedMarkdown => crate::core::rules_canonical::Wrapper::Dedicated,
111                // CursorMdc embeds the render verbatim between the markers
112                // (frontmatter lives outside them); the wrapper is dynamic —
113                // HookCovered on hook-covered installs (GL #1153).
114                RulesFormat::CursorMdc => content::cursor_wrapper_for_mdc(&target.path),
115            };
116            let expected = crate::core::rules_canonical::render(shadow, wrapper, level, &profile);
117            (target.name.to_string(), expected)
118        })
119        .collect()
120}
121
122use detect::is_tool_detected;
123use targets::build_rules_targets;
124use write::inject_rules;
125
126struct RulesTarget {
127    name: &'static str,
128    path: PathBuf,
129    format: RulesFormat,
130}
131
132enum RulesFormat {
133    SharedMarkdown,
134    DedicatedMarkdown,
135    CursorMdc,
136}
137
138#[derive(Debug, Default)]
139pub struct InjectResult {
140    pub injected: Vec<String>,
141    pub updated: Vec<String>,
142    pub already: Vec<String>,
143    pub errors: Vec<String>,
144    pub backed_up: Vec<String>,
145}
146
147#[derive(Debug, Clone, Serialize, Deserialize)]
148pub struct RulesTargetStatus {
149    pub name: String,
150    pub detected: bool,
151    pub path: String,
152    pub state: String,
153    pub note: Option<String>,
154}
155
156enum RulesResult {
157    Updated,
158    AlreadyPresent,
159}
160
161pub fn inject_all_rules(home: &std::path::Path) -> InjectResult {
162    inject_rules_where(home, &|_| true)
163}
164
165/// Agent key (as `init --agent` / `setup --agents` spell it) that owns a
166/// rules target, so a setup agent selection can filter rules files too.
167fn rules_agent_key(target_name: &str) -> Option<&'static str> {
168    Some(match target_name {
169        "Gemini CLI" => "gemini",
170        "VS Code" => "vscode",
171        "Copilot CLI" => "copilot",
172        "Cursor" => "cursor",
173        "Windsurf" => "windsurf",
174        "Zed" => "zed",
175        "Cline" => "cline",
176        "Roo Code" => "roo",
177        "OpenCode" => "opencode",
178        "Continue" => "continue",
179        "Amp" => "amp",
180        "Qwen Code" => "qwen",
181        "Trae" => "trae",
182        "Amazon Q Developer" => "amazonq",
183        "JetBrains IDEs" => "jetbrains",
184        "Antigravity" => "antigravity",
185        "Pi Coding Agent" => "pi",
186        "AWS Kiro" => "kiro",
187        "Verdent" => "verdent",
188        "Crush" => "crush",
189        "Augment" => "augment",
190        "OpenClaw" => "openclaw",
191        "Codex CLI" => "codex",
192        "Grok" => "grok",
193        "Oh My Pi" => "omp",
194        "Hermes Agent" => "hermes",
195        "Qoder" => "qoder",
196        _ => return None,
197    })
198}
199
200/// Rules files a setup run would write for the agents `allows` admits: the
201/// installed tools' targets plus the Claude Code pointer block. Writes nothing.
202/// The real run additionally skips tools whose MCP entry is missing (GH #1435).
203#[must_use]
204pub fn planned_rules_files(
205    home: &std::path::Path,
206    allows: &dyn Fn(&str) -> bool,
207) -> Vec<(String, PathBuf)> {
208    let cfg = crate::core::config::Config::load();
209    let injection = cfg.rules_injection_effective();
210    if cfg.rules_scope_effective() == crate::core::config::RulesScope::Project
211        || injection == crate::core::config::RulesInjection::Off
212    {
213        return Vec::new();
214    }
215    let mut files = Vec::new();
216    if injection == crate::core::config::RulesInjection::Shared
217        && allows("claude")
218        && detect::is_named_agent_ready("Claude Code", home)
219    {
220        files.push((
221            "Claude Code".to_string(),
222            crate::core::editor_registry::claude_state_dir(home).join("CLAUDE.md"),
223        ));
224    }
225    for target in build_rules_targets(home, injection) {
226        if rules_agent_key(target.name).is_some_and(allows) && is_tool_detected(&target, home) {
227            files.push((target.name.to_string(), target.path));
228        }
229    }
230    files
231}
232
233/// [`inject_all_rules`] restricted to the agents `allows` admits (by agent key).
234pub fn inject_rules_where(home: &std::path::Path, allows: &dyn Fn(&str) -> bool) -> InjectResult {
235    let cfg = crate::core::config::Config::load();
236    if cfg.rules_scope_effective() == crate::core::config::RulesScope::Project {
237        return InjectResult::default();
238    }
239    if cfg.rules_injection_effective() == crate::core::config::RulesInjection::Off {
240        return InjectResult::default();
241    }
242
243    let targets = build_rules_targets(home, cfg.rules_injection_effective());
244
245    let mut result = InjectResult::default();
246
247    if cfg.rules_injection_effective() == crate::core::config::RulesInjection::Shared
248        && allows("claude")
249        && detect::is_named_agent_ready("Claude Code", home)
250    {
251        sync_claude_pointer_block(home, &mut result);
252    }
253
254    for target in &targets {
255        if !rules_agent_key(target.name).is_some_and(allows) {
256            continue;
257        }
258        if !is_tool_detected(target, home) {
259            continue;
260        }
261        // GH #1435: skip rules injection when the tool's MCP server is not
262        // configured — a rules file that mandates ctx_* tools for an agent
263        // that can't reach them is a self-contradiction.
264        if !detect::is_mcp_configured(target, home) {
265            continue;
266        }
267
268        let bak_path = target.path.with_extension(format!(
269            "{}.bak",
270            target
271                .path
272                .extension()
273                .and_then(|e| e.to_str())
274                .unwrap_or("")
275        ));
276        let bak_existed_before = bak_path.exists();
277        let bak_mtime_before = bak_existed_before
278            .then(|| {
279                std::fs::metadata(&bak_path)
280                    .ok()
281                    .and_then(|m| m.modified().ok())
282            })
283            .flatten();
284
285        match inject_rules(target) {
286            Ok(RulesResult::Updated) => {
287                result.updated.push(target.name.to_string());
288                let bak_is_new = if bak_existed_before {
289                    std::fs::metadata(&bak_path)
290                        .ok()
291                        .and_then(|m| m.modified().ok())
292                        != bak_mtime_before
293                } else {
294                    bak_path.exists()
295                };
296                if bak_is_new {
297                    result
298                        .backed_up
299                        .push(bak_path.to_string_lossy().to_string());
300                }
301            }
302            Ok(RulesResult::AlreadyPresent) => result.already.push(target.name.to_string()),
303            Err(e) => result.errors.push(format!("{}: {e}", target.name)),
304        }
305    }
306
307    result
308}
309
310/// Inject global rules for a single agent (by CLI key like "opencode", "cursor", etc.).
311pub fn inject_rules_for_agent(home: &std::path::Path, agent_key: &str) -> InjectResult {
312    let cfg = crate::core::config::Config::load();
313    if cfg.rules_scope_effective() == crate::core::config::RulesScope::Project {
314        return InjectResult::default();
315    }
316    if cfg.rules_injection_effective() == crate::core::config::RulesInjection::Off {
317        return InjectResult::default();
318    }
319
320    let targets = build_rules_targets(home, cfg.rules_injection_effective());
321    let mut result = InjectResult::default();
322
323    if cfg.rules_injection_effective() == crate::core::config::RulesInjection::Shared
324        && is_claude_agent_key(agent_key)
325    {
326        sync_claude_pointer_block(home, &mut result);
327        return result;
328    }
329
330    for target in &targets {
331        if !match_agent_name(agent_key, target.name) {
332            continue;
333        }
334
335        let bak_path = target.path.with_extension(format!(
336            "{}.bak",
337            target
338                .path
339                .extension()
340                .and_then(|e| e.to_str())
341                .unwrap_or("")
342        ));
343        let bak_existed_before = bak_path.exists();
344
345        match inject_rules(target) {
346            Ok(RulesResult::Updated) => {
347                result.updated.push(target.name.to_string());
348                if !bak_existed_before && bak_path.exists() {
349                    result
350                        .backed_up
351                        .push(bak_path.to_string_lossy().to_string());
352                }
353            }
354            Ok(RulesResult::AlreadyPresent) => result.already.push(target.name.to_string()),
355            Err(e) => result.errors.push(format!("{}: {e}", target.name)),
356        }
357    }
358
359    result
360}
361
362fn is_claude_agent_key(agent_key: &str) -> bool {
363    matches!(
364        agent_key.trim().to_ascii_lowercase().as_str(),
365        "claude" | "claude-code" | "claude_code" | "claude code"
366    )
367}
368
369fn sync_claude_pointer_block(home: &std::path::Path, result: &mut InjectResult) {
370    let mode = crate::hooks::recommend_hook_mode("claude");
371    match crate::hooks::agents::sync_claude_global_rules_block(home, mode) {
372        Ok(true) => result.updated.push("Claude Code".to_string()),
373        Ok(false) => result.already.push("Claude Code".to_string()),
374        Err(error) => result.errors.push(format!("Claude Code: {error}")),
375    }
376}
377
378/// Returns `true` if a lean-ctx rules marker is present in *any* supported
379/// agent's rules file.
380#[must_use]
381pub fn any_rules_marker_present(home: &std::path::Path) -> bool {
382    use crate::core::config::RulesInjection;
383    let mut seen = std::collections::HashSet::new();
384    for injection in [RulesInjection::Shared, RulesInjection::Dedicated] {
385        for target in build_rules_targets(home, injection) {
386            if !seen.insert(target.path.clone()) {
387                continue;
388            }
389            if let Ok(content) = std::fs::read_to_string(&target.path)
390                && RulesFile::parse(&content).has_content()
391            {
392                return true;
393            }
394        }
395    }
396    false
397}
398
399fn match_agent_name(cli_key: &str, target_name: &str) -> bool {
400    let needle = cli_key.to_lowercase();
401    let tn = target_name.to_lowercase();
402    if needle == "pi" {
403        return tn.contains("pi coding");
404    }
405    if needle == "omp" {
406        return tn.contains("oh my pi");
407    }
408    needle.contains(&tn)
409        || tn.contains(&needle)
410        || (needle.contains("cursor") && tn.contains("cursor"))
411        || (needle.contains("claude") && tn.contains("claude"))
412        || (needle.contains("codebuddy") && tn.contains("codebuddy"))
413        || (needle.contains("windsurf") && tn.contains("windsurf"))
414        || (needle.contains("codex") && tn.contains("claude"))
415        || (needle.contains("zed") && tn.contains("zed"))
416        || (needle.contains("copilot") && tn.contains("copilot"))
417        || (needle.contains("jetbrains") && tn.contains("jetbrains"))
418        || (needle.contains("kiro") && tn.contains("kiro"))
419        || (needle.contains("gemini") && tn.contains("gemini"))
420        || (needle == "opencode" && tn.contains("opencode"))
421        || (needle == "cline" && tn.contains("cline"))
422        || (needle == "roo" && tn.contains("roo"))
423        || (needle == "amp" && tn.contains("amp"))
424        || (needle == "trae" && tn.contains("trae"))
425        || (needle == "amazonq" && tn.contains("amazon"))
426        || (needle == "crush" && tn.contains("crush"))
427        || (needle == "verdent" && tn.contains("verdent"))
428        || (needle == "continue" && tn.contains("continue"))
429        || (needle == "qwen" && tn.contains("qwen"))
430        || (needle == "antigravity" && tn.contains("antigravity"))
431        || (needle == "augment" && tn.contains("augment"))
432        || (needle == "openclaw" && tn.contains("openclaw"))
433        || (needle == "grok" && tn.contains("grok"))
434        || (needle == "vscode" && (tn.contains("vs code") || tn.contains("vscode")))
435}
436
437/// Check if the rules file for a given MCP client is up-to-date.
438pub fn check_rules_freshness(client_name: &str) -> Option<String> {
439    let home = dirs::home_dir()?;
440    check_rules_freshness_at_home(client_name, &home)
441}
442
443fn check_rules_freshness_at_home(client_name: &str, home: &std::path::Path) -> Option<String> {
444    let cfg = crate::core::config::Config::load();
445    if cfg.declines_rule_steering()
446        || cfg.rules_scope_effective() == crate::core::config::RulesScope::Project
447    {
448        return None;
449    }
450    let injection = cfg.rules_injection_effective();
451    let targets = build_rules_targets(home, injection);
452
453    let matched: Vec<&RulesTarget> = targets
454        .iter()
455        .filter(|t| match_agent_name(client_name, t.name))
456        .collect();
457
458    if matched.is_empty() {
459        return None;
460    }
461
462    for target in &matched {
463        // Keep freshness eligibility identical to inject_all_rules(): never
464        // advertise an automatic repair for a target the writer would skip.
465        if !is_tool_detected(target, home) || !detect::is_mcp_configured(target, home) {
466            continue;
467        }
468        if !target.path.exists() {
469            continue;
470        }
471        let content = std::fs::read_to_string(&target.path).ok()?;
472        let file = RulesFile::parse(&content);
473        if file.has_content() && !file.is_current() {
474            return Some(format!(
475                "[RULES OUTDATED] Your {} rules were written by an older lean-ctx version. \
476                 Re-read your rules file ({}) or run `lean-ctx setup` to update, \
477                 then start a new session for full compatibility.",
478                target.name,
479                target.path.display()
480            ));
481        }
482    }
483
484    None
485}
486
487pub fn collect_rules_status(home: &std::path::Path) -> Vec<RulesTargetStatus> {
488    let injection = crate::core::config::Config::load().rules_injection_effective();
489    let targets = build_rules_targets(home, injection);
490    let mut out = Vec::new();
491
492    for target in &targets {
493        let detected = is_tool_detected(target, home);
494        let path = target.path.to_string_lossy().to_string();
495
496        let state = if !detected {
497            "not_detected".to_string()
498        } else if !target.path.exists() {
499            "missing".to_string()
500        } else {
501            match std::fs::read_to_string(&target.path) {
502                Ok(content) => {
503                    let file = RulesFile::parse(&content);
504                    if file.has_content() {
505                        if file.is_current() {
506                            "up_to_date".to_string()
507                        } else {
508                            "outdated".to_string()
509                        }
510                    } else {
511                        "present_without_marker".to_string()
512                    }
513                }
514                Err(_) => "read_error".to_string(),
515            }
516        };
517
518        out.push(RulesTargetStatus {
519            name: target.name.to_string(),
520            detected,
521            path,
522            state,
523            note: None,
524        });
525    }
526
527    out
528}