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::{install_all_skills, install_skill_for_agent};
30
31/// Forwarding functions — content is delegated to `core::rules_canonical`.
32pub fn canonical_rules_block() -> String {
33    let cfg = crate::core::config::Config::load();
34    let shadow = cfg.shadow_mode;
35    let level = crate::core::config::CompressionLevel::effective(&cfg);
36    let profile = crate::core::tool_profiles::ToolProfile::from_config(&cfg);
37    crate::core::rules_canonical::render(
38        shadow,
39        crate::core::rules_canonical::Wrapper::Shared,
40        level,
41        &profile,
42    )
43}
44pub fn rules_shared_content() -> String {
45    canonical_rules_block()
46}
47pub fn rules_dedicated_markdown() -> String {
48    let cfg = crate::core::config::Config::load();
49    let shadow = cfg.shadow_mode;
50    let level = crate::core::config::CompressionLevel::effective(&cfg);
51    let profile = crate::core::tool_profiles::ToolProfile::from_config(&cfg);
52    crate::core::rules_canonical::render(
53        shadow,
54        crate::core::rules_canonical::Wrapper::Dedicated,
55        level,
56        &profile,
57    )
58}
59
60/// Long-form rules for the on-demand project `LEAN-CTX.md` (#578). Same
61/// config-driven shadow/compression handling as the dedicated render, but the
62/// LONGFORM profile with the verbose teaching sections.
63pub fn rules_longform_markdown() -> String {
64    let cfg = crate::core::config::Config::load();
65    let shadow = cfg.shadow_mode;
66    let level = crate::core::config::CompressionLevel::effective(&cfg);
67    let profile = crate::core::tool_profiles::ToolProfile::from_config(&cfg);
68    crate::core::rules_canonical::render(
69        shadow,
70        crate::core::rules_canonical::Wrapper::Longform,
71        level,
72        &profile,
73    )
74}
75
76/// The canonical rules block lean-ctx would write for each target, keyed by the
77/// target's display name.
78///
79/// Drift detection compares against this instead of guessing shared-vs-dedicated
80/// from a target's on-disk contents: a freshly synced `SharedMarkdown` file (e.g.
81/// Copilot CLI, Codex CLI) carries no user text, which a content heuristic
82/// mistook for the dedicated layout and then flagged as drifted on every sync.
83/// Keying by the real `RulesFormat` keeps `sync` and `diff` in agreement (#548).
84pub fn expected_blocks_by_target(
85    home: &std::path::Path,
86) -> std::collections::HashMap<String, String> {
87    let injection = crate::core::config::Config::load().rules_injection_effective();
88    let cfg = crate::core::config::Config::load();
89    let shadow = cfg.shadow_mode;
90    let level = crate::core::config::CompressionLevel::effective(&cfg);
91    let shared = canonical_rules_block();
92    let dedicated = rules_dedicated_markdown();
93    build_rules_targets(home, injection)
94        .into_iter()
95        .map(|target| {
96            let expected = match target.format {
97                RulesFormat::SharedMarkdown => shared.clone(),
98                RulesFormat::DedicatedMarkdown => dedicated.clone(),
99                // CursorMdc embeds the render verbatim between the markers
100                // (frontmatter lives outside them); the wrapper is dynamic —
101                // HookCovered on hook-covered installs (GL #1153).
102                RulesFormat::CursorMdc => {
103                    let profile = crate::core::tool_profiles::ToolProfile::from_config(&cfg);
104                    crate::core::rules_canonical::render(
105                        shadow,
106                        content::cursor_wrapper_for_mdc(&target.path),
107                        level,
108                        &profile,
109                    )
110                }
111            };
112            (target.name.to_string(), expected)
113        })
114        .collect()
115}
116
117use detect::is_tool_detected;
118use targets::build_rules_targets;
119use write::inject_rules;
120
121struct RulesTarget {
122    name: &'static str,
123    path: PathBuf,
124    format: RulesFormat,
125}
126
127enum RulesFormat {
128    SharedMarkdown,
129    DedicatedMarkdown,
130    CursorMdc,
131}
132
133#[derive(Debug, Default)]
134pub struct InjectResult {
135    pub injected: Vec<String>,
136    pub updated: Vec<String>,
137    pub already: Vec<String>,
138    pub errors: Vec<String>,
139    pub backed_up: Vec<String>,
140}
141
142#[derive(Debug, Clone, Serialize, Deserialize)]
143pub struct RulesTargetStatus {
144    pub name: String,
145    pub detected: bool,
146    pub path: String,
147    pub state: String,
148    pub note: Option<String>,
149}
150
151enum RulesResult {
152    Updated,
153    AlreadyPresent,
154}
155
156pub fn inject_all_rules(home: &std::path::Path) -> InjectResult {
157    let cfg = crate::core::config::Config::load();
158    if cfg.rules_scope_effective() == crate::core::config::RulesScope::Project {
159        return InjectResult::default();
160    }
161    if cfg.rules_injection_effective() == crate::core::config::RulesInjection::Off {
162        return InjectResult::default();
163    }
164
165    let targets = build_rules_targets(home, cfg.rules_injection_effective());
166
167    let mut result = InjectResult::default();
168
169    if cfg.rules_injection_effective() == crate::core::config::RulesInjection::Shared
170        && detect::is_named_agent_ready("Claude Code", home)
171    {
172        sync_claude_pointer_block(home, &mut result);
173    }
174
175    for target in &targets {
176        if !is_tool_detected(target, home) {
177            continue;
178        }
179        // GH #1435: skip rules injection when the tool's MCP server is not
180        // configured — a rules file that mandates ctx_* tools for an agent
181        // that can't reach them is a self-contradiction.
182        if !detect::is_mcp_configured(target, home) {
183            continue;
184        }
185
186        let bak_path = target.path.with_extension(format!(
187            "{}.bak",
188            target
189                .path
190                .extension()
191                .and_then(|e| e.to_str())
192                .unwrap_or("")
193        ));
194        let bak_existed_before = bak_path.exists();
195        let bak_mtime_before = bak_existed_before
196            .then(|| {
197                std::fs::metadata(&bak_path)
198                    .ok()
199                    .and_then(|m| m.modified().ok())
200            })
201            .flatten();
202
203        match inject_rules(target) {
204            Ok(RulesResult::Updated) => {
205                result.updated.push(target.name.to_string());
206                let bak_is_new = if bak_existed_before {
207                    std::fs::metadata(&bak_path)
208                        .ok()
209                        .and_then(|m| m.modified().ok())
210                        != bak_mtime_before
211                } else {
212                    bak_path.exists()
213                };
214                if bak_is_new {
215                    result
216                        .backed_up
217                        .push(bak_path.to_string_lossy().to_string());
218                }
219            }
220            Ok(RulesResult::AlreadyPresent) => result.already.push(target.name.to_string()),
221            Err(e) => result.errors.push(format!("{}: {e}", target.name)),
222        }
223    }
224
225    result
226}
227
228/// Inject global rules for a single agent (by CLI key like "opencode", "cursor", etc.).
229pub fn inject_rules_for_agent(home: &std::path::Path, agent_key: &str) -> InjectResult {
230    let cfg = crate::core::config::Config::load();
231    if cfg.rules_scope_effective() == crate::core::config::RulesScope::Project {
232        return InjectResult::default();
233    }
234    if cfg.rules_injection_effective() == crate::core::config::RulesInjection::Off {
235        return InjectResult::default();
236    }
237
238    let targets = build_rules_targets(home, cfg.rules_injection_effective());
239    let mut result = InjectResult::default();
240
241    if cfg.rules_injection_effective() == crate::core::config::RulesInjection::Shared
242        && is_claude_agent_key(agent_key)
243    {
244        sync_claude_pointer_block(home, &mut result);
245        return result;
246    }
247
248    for target in &targets {
249        if !match_agent_name(agent_key, target.name) {
250            continue;
251        }
252
253        let bak_path = target.path.with_extension(format!(
254            "{}.bak",
255            target
256                .path
257                .extension()
258                .and_then(|e| e.to_str())
259                .unwrap_or("")
260        ));
261        let bak_existed_before = bak_path.exists();
262
263        match inject_rules(target) {
264            Ok(RulesResult::Updated) => {
265                result.updated.push(target.name.to_string());
266                if !bak_existed_before && bak_path.exists() {
267                    result
268                        .backed_up
269                        .push(bak_path.to_string_lossy().to_string());
270                }
271            }
272            Ok(RulesResult::AlreadyPresent) => result.already.push(target.name.to_string()),
273            Err(e) => result.errors.push(format!("{}: {e}", target.name)),
274        }
275    }
276
277    result
278}
279
280fn is_claude_agent_key(agent_key: &str) -> bool {
281    matches!(
282        agent_key.trim().to_ascii_lowercase().as_str(),
283        "claude" | "claude-code" | "claude_code" | "claude code"
284    )
285}
286
287fn sync_claude_pointer_block(home: &std::path::Path, result: &mut InjectResult) {
288    let mode = crate::hooks::recommend_hook_mode("claude");
289    match crate::hooks::agents::sync_claude_global_rules_block(home, mode) {
290        Ok(true) => result.updated.push("Claude Code".to_string()),
291        Ok(false) => result.already.push("Claude Code".to_string()),
292        Err(error) => result.errors.push(format!("Claude Code: {error}")),
293    }
294}
295
296/// Returns `true` if a lean-ctx rules marker is present in *any* supported
297/// agent's rules file.
298#[must_use]
299pub fn any_rules_marker_present(home: &std::path::Path) -> bool {
300    use crate::core::config::RulesInjection;
301    let mut seen = std::collections::HashSet::new();
302    for injection in [RulesInjection::Shared, RulesInjection::Dedicated] {
303        for target in build_rules_targets(home, injection) {
304            if !seen.insert(target.path.clone()) {
305                continue;
306            }
307            if let Ok(content) = std::fs::read_to_string(&target.path)
308                && RulesFile::parse(&content).has_content()
309            {
310                return true;
311            }
312        }
313    }
314    false
315}
316
317fn match_agent_name(cli_key: &str, target_name: &str) -> bool {
318    let needle = cli_key.to_lowercase();
319    let tn = target_name.to_lowercase();
320    needle.contains(&tn)
321        || tn.contains(&needle)
322        || (needle.contains("cursor") && tn.contains("cursor"))
323        || (needle.contains("claude") && tn.contains("claude"))
324        || (needle.contains("codebuddy") && tn.contains("codebuddy"))
325        || (needle.contains("windsurf") && tn.contains("windsurf"))
326        || (needle.contains("codex") && tn.contains("claude"))
327        || (needle.contains("zed") && tn.contains("zed"))
328        || (needle.contains("copilot") && tn.contains("copilot"))
329        || (needle.contains("jetbrains") && tn.contains("jetbrains"))
330        || (needle.contains("kiro") && tn.contains("kiro"))
331        || (needle.contains("gemini") && tn.contains("gemini"))
332        || (needle == "opencode" && tn.contains("opencode"))
333        || (needle == "cline" && tn.contains("cline"))
334        || (needle == "roo" && tn.contains("roo"))
335        || (needle == "amp" && tn.contains("amp"))
336        || (needle == "trae" && tn.contains("trae"))
337        || (needle == "amazonq" && tn.contains("amazon"))
338        || (needle == "pi" && tn.contains("pi coding"))
339        || (needle == "crush" && tn.contains("crush"))
340        || (needle == "verdent" && tn.contains("verdent"))
341        || (needle == "continue" && tn.contains("continue"))
342        || (needle == "qwen" && tn.contains("qwen"))
343        || (needle == "antigravity" && tn.contains("antigravity"))
344        || (needle == "augment" && tn.contains("augment"))
345        || (needle == "openclaw" && tn.contains("openclaw"))
346        || (needle == "grok" && tn.contains("grok"))
347        || (needle == "vscode" && (tn.contains("vs code") || tn.contains("vscode")))
348}
349
350/// Check if the rules file for a given MCP client is up-to-date.
351pub fn check_rules_freshness(client_name: &str) -> Option<String> {
352    let home = dirs::home_dir()?;
353    let injection = crate::core::config::Config::load().rules_injection_effective();
354    if injection == crate::core::config::RulesInjection::Off {
355        return None;
356    }
357    let targets = build_rules_targets(&home, injection);
358
359    let matched: Vec<&RulesTarget> = targets
360        .iter()
361        .filter(|t| match_agent_name(client_name, t.name))
362        .collect();
363
364    if matched.is_empty() {
365        return None;
366    }
367
368    for target in &matched {
369        if !target.path.exists() {
370            continue;
371        }
372        let content = std::fs::read_to_string(&target.path).ok()?;
373        let file = RulesFile::parse(&content);
374        if file.has_content() && !file.is_current() {
375            return Some(format!(
376                "[RULES OUTDATED] Your {} rules were written by an older lean-ctx version. \
377                 Re-read your rules file ({}) or run `lean-ctx setup` to update, \
378                 then start a new session for full compatibility.",
379                target.name,
380                target.path.display()
381            ));
382        }
383    }
384
385    None
386}
387
388pub fn collect_rules_status(home: &std::path::Path) -> Vec<RulesTargetStatus> {
389    let injection = crate::core::config::Config::load().rules_injection_effective();
390    let targets = build_rules_targets(home, injection);
391    let mut out = Vec::new();
392
393    for target in &targets {
394        let detected = is_tool_detected(target, home);
395        let path = target.path.to_string_lossy().to_string();
396
397        let state = if !detected {
398            "not_detected".to_string()
399        } else if !target.path.exists() {
400            "missing".to_string()
401        } else {
402            match std::fs::read_to_string(&target.path) {
403                Ok(content) => {
404                    let file = RulesFile::parse(&content);
405                    if file.has_content() {
406                        if file.is_current() {
407                            "up_to_date".to_string()
408                        } else {
409                            "outdated".to_string()
410                        }
411                    } else {
412                        "present_without_marker".to_string()
413                    }
414                }
415                Err(_) => "read_error".to_string(),
416            }
417        };
418
419        out.push(RulesTargetStatus {
420            name: target.name.to_string(),
421            detected,
422            path,
423            state,
424            note: None,
425        });
426    }
427
428    out
429}