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    if needle == "pi" {
321        return tn.contains("pi coding");
322    }
323    if needle == "omp" {
324        return tn.contains("oh my pi");
325    }
326    needle.contains(&tn)
327        || tn.contains(&needle)
328        || (needle.contains("cursor") && tn.contains("cursor"))
329        || (needle.contains("claude") && tn.contains("claude"))
330        || (needle.contains("codebuddy") && tn.contains("codebuddy"))
331        || (needle.contains("windsurf") && tn.contains("windsurf"))
332        || (needle.contains("codex") && tn.contains("claude"))
333        || (needle.contains("zed") && tn.contains("zed"))
334        || (needle.contains("copilot") && tn.contains("copilot"))
335        || (needle.contains("jetbrains") && tn.contains("jetbrains"))
336        || (needle.contains("kiro") && tn.contains("kiro"))
337        || (needle.contains("gemini") && tn.contains("gemini"))
338        || (needle == "opencode" && tn.contains("opencode"))
339        || (needle == "cline" && tn.contains("cline"))
340        || (needle == "roo" && tn.contains("roo"))
341        || (needle == "amp" && tn.contains("amp"))
342        || (needle == "trae" && tn.contains("trae"))
343        || (needle == "amazonq" && tn.contains("amazon"))
344        || (needle == "crush" && tn.contains("crush"))
345        || (needle == "verdent" && tn.contains("verdent"))
346        || (needle == "continue" && tn.contains("continue"))
347        || (needle == "qwen" && tn.contains("qwen"))
348        || (needle == "antigravity" && tn.contains("antigravity"))
349        || (needle == "augment" && tn.contains("augment"))
350        || (needle == "openclaw" && tn.contains("openclaw"))
351        || (needle == "grok" && tn.contains("grok"))
352        || (needle == "vscode" && (tn.contains("vs code") || tn.contains("vscode")))
353}
354
355/// Check if the rules file for a given MCP client is up-to-date.
356pub fn check_rules_freshness(client_name: &str) -> Option<String> {
357    let home = dirs::home_dir()?;
358    check_rules_freshness_at_home(client_name, &home)
359}
360
361fn check_rules_freshness_at_home(client_name: &str, home: &std::path::Path) -> Option<String> {
362    let cfg = crate::core::config::Config::load();
363    if cfg.declines_rule_steering()
364        || cfg.rules_scope_effective() == crate::core::config::RulesScope::Project
365    {
366        return None;
367    }
368    let injection = cfg.rules_injection_effective();
369    let targets = build_rules_targets(home, injection);
370
371    let matched: Vec<&RulesTarget> = targets
372        .iter()
373        .filter(|t| match_agent_name(client_name, t.name))
374        .collect();
375
376    if matched.is_empty() {
377        return None;
378    }
379
380    for target in &matched {
381        // Keep freshness eligibility identical to inject_all_rules(): never
382        // advertise an automatic repair for a target the writer would skip.
383        if !is_tool_detected(target, home) || !detect::is_mcp_configured(target, home) {
384            continue;
385        }
386        if !target.path.exists() {
387            continue;
388        }
389        let content = std::fs::read_to_string(&target.path).ok()?;
390        let file = RulesFile::parse(&content);
391        if file.has_content() && !file.is_current() {
392            return Some(format!(
393                "[RULES OUTDATED] Your {} rules were written by an older lean-ctx version. \
394                 Re-read your rules file ({}) or run `lean-ctx setup` to update, \
395                 then start a new session for full compatibility.",
396                target.name,
397                target.path.display()
398            ));
399        }
400    }
401
402    None
403}
404
405pub fn collect_rules_status(home: &std::path::Path) -> Vec<RulesTargetStatus> {
406    let injection = crate::core::config::Config::load().rules_injection_effective();
407    let targets = build_rules_targets(home, injection);
408    let mut out = Vec::new();
409
410    for target in &targets {
411        let detected = is_tool_detected(target, home);
412        let path = target.path.to_string_lossy().to_string();
413
414        let state = if !detected {
415            "not_detected".to_string()
416        } else if !target.path.exists() {
417            "missing".to_string()
418        } else {
419            match std::fs::read_to_string(&target.path) {
420                Ok(content) => {
421                    let file = RulesFile::parse(&content);
422                    if file.has_content() {
423                        if file.is_current() {
424                            "up_to_date".to_string()
425                        } else {
426                            "outdated".to_string()
427                        }
428                    } else {
429                        "present_without_marker".to_string()
430                    }
431                }
432                Err(_) => "read_error".to_string(),
433            }
434        };
435
436        out.push(RulesTargetStatus {
437            name: target.name.to_string(),
438            detected,
439            path,
440            state,
441            note: None,
442        });
443    }
444
445    out
446}