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    build_rules_targets(home, injection)
92        .into_iter()
93        .map(|target| {
94            // The profile `inject_rules` writes with, so a freshly synced
95            // file never reads as drifted (#1008, #1849).
96            let profile = write::profile_for_target(&cfg, target.name);
97            let wrapper = match target.format {
98                RulesFormat::SharedMarkdown => crate::core::rules_canonical::Wrapper::Shared,
99                RulesFormat::DedicatedMarkdown => crate::core::rules_canonical::Wrapper::Dedicated,
100                // CursorMdc embeds the render verbatim between the markers
101                // (frontmatter lives outside them); the wrapper is dynamic —
102                // HookCovered on hook-covered installs (GL #1153).
103                RulesFormat::CursorMdc => content::cursor_wrapper_for_mdc(&target.path),
104            };
105            let expected = crate::core::rules_canonical::render(shadow, wrapper, level, &profile);
106            (target.name.to_string(), expected)
107        })
108        .collect()
109}
110
111use detect::is_tool_detected;
112use targets::build_rules_targets;
113use write::inject_rules;
114
115struct RulesTarget {
116    name: &'static str,
117    path: PathBuf,
118    format: RulesFormat,
119}
120
121enum RulesFormat {
122    SharedMarkdown,
123    DedicatedMarkdown,
124    CursorMdc,
125}
126
127#[derive(Debug, Default)]
128pub struct InjectResult {
129    pub injected: Vec<String>,
130    pub updated: Vec<String>,
131    pub already: Vec<String>,
132    pub errors: Vec<String>,
133    pub backed_up: Vec<String>,
134}
135
136#[derive(Debug, Clone, Serialize, Deserialize)]
137pub struct RulesTargetStatus {
138    pub name: String,
139    pub detected: bool,
140    pub path: String,
141    pub state: String,
142    pub note: Option<String>,
143}
144
145enum RulesResult {
146    Updated,
147    AlreadyPresent,
148}
149
150pub fn inject_all_rules(home: &std::path::Path) -> InjectResult {
151    let cfg = crate::core::config::Config::load();
152    if cfg.rules_scope_effective() == crate::core::config::RulesScope::Project {
153        return InjectResult::default();
154    }
155    if cfg.rules_injection_effective() == crate::core::config::RulesInjection::Off {
156        return InjectResult::default();
157    }
158
159    let targets = build_rules_targets(home, cfg.rules_injection_effective());
160
161    let mut result = InjectResult::default();
162
163    if cfg.rules_injection_effective() == crate::core::config::RulesInjection::Shared
164        && detect::is_named_agent_ready("Claude Code", home)
165    {
166        sync_claude_pointer_block(home, &mut result);
167    }
168
169    for target in &targets {
170        if !is_tool_detected(target, home) {
171            continue;
172        }
173        // GH #1435: skip rules injection when the tool's MCP server is not
174        // configured — a rules file that mandates ctx_* tools for an agent
175        // that can't reach them is a self-contradiction.
176        if !detect::is_mcp_configured(target, home) {
177            continue;
178        }
179
180        let bak_path = target.path.with_extension(format!(
181            "{}.bak",
182            target
183                .path
184                .extension()
185                .and_then(|e| e.to_str())
186                .unwrap_or("")
187        ));
188        let bak_existed_before = bak_path.exists();
189        let bak_mtime_before = bak_existed_before
190            .then(|| {
191                std::fs::metadata(&bak_path)
192                    .ok()
193                    .and_then(|m| m.modified().ok())
194            })
195            .flatten();
196
197        match inject_rules(target) {
198            Ok(RulesResult::Updated) => {
199                result.updated.push(target.name.to_string());
200                let bak_is_new = if bak_existed_before {
201                    std::fs::metadata(&bak_path)
202                        .ok()
203                        .and_then(|m| m.modified().ok())
204                        != bak_mtime_before
205                } else {
206                    bak_path.exists()
207                };
208                if bak_is_new {
209                    result
210                        .backed_up
211                        .push(bak_path.to_string_lossy().to_string());
212                }
213            }
214            Ok(RulesResult::AlreadyPresent) => result.already.push(target.name.to_string()),
215            Err(e) => result.errors.push(format!("{}: {e}", target.name)),
216        }
217    }
218
219    result
220}
221
222/// Inject global rules for a single agent (by CLI key like "opencode", "cursor", etc.).
223pub fn inject_rules_for_agent(home: &std::path::Path, agent_key: &str) -> InjectResult {
224    let cfg = crate::core::config::Config::load();
225    if cfg.rules_scope_effective() == crate::core::config::RulesScope::Project {
226        return InjectResult::default();
227    }
228    if cfg.rules_injection_effective() == crate::core::config::RulesInjection::Off {
229        return InjectResult::default();
230    }
231
232    let targets = build_rules_targets(home, cfg.rules_injection_effective());
233    let mut result = InjectResult::default();
234
235    if cfg.rules_injection_effective() == crate::core::config::RulesInjection::Shared
236        && is_claude_agent_key(agent_key)
237    {
238        sync_claude_pointer_block(home, &mut result);
239        return result;
240    }
241
242    for target in &targets {
243        if !match_agent_name(agent_key, target.name) {
244            continue;
245        }
246
247        let bak_path = target.path.with_extension(format!(
248            "{}.bak",
249            target
250                .path
251                .extension()
252                .and_then(|e| e.to_str())
253                .unwrap_or("")
254        ));
255        let bak_existed_before = bak_path.exists();
256
257        match inject_rules(target) {
258            Ok(RulesResult::Updated) => {
259                result.updated.push(target.name.to_string());
260                if !bak_existed_before && bak_path.exists() {
261                    result
262                        .backed_up
263                        .push(bak_path.to_string_lossy().to_string());
264                }
265            }
266            Ok(RulesResult::AlreadyPresent) => result.already.push(target.name.to_string()),
267            Err(e) => result.errors.push(format!("{}: {e}", target.name)),
268        }
269    }
270
271    result
272}
273
274fn is_claude_agent_key(agent_key: &str) -> bool {
275    matches!(
276        agent_key.trim().to_ascii_lowercase().as_str(),
277        "claude" | "claude-code" | "claude_code" | "claude code"
278    )
279}
280
281fn sync_claude_pointer_block(home: &std::path::Path, result: &mut InjectResult) {
282    let mode = crate::hooks::recommend_hook_mode("claude");
283    match crate::hooks::agents::sync_claude_global_rules_block(home, mode) {
284        Ok(true) => result.updated.push("Claude Code".to_string()),
285        Ok(false) => result.already.push("Claude Code".to_string()),
286        Err(error) => result.errors.push(format!("Claude Code: {error}")),
287    }
288}
289
290/// Returns `true` if a lean-ctx rules marker is present in *any* supported
291/// agent's rules file.
292#[must_use]
293pub fn any_rules_marker_present(home: &std::path::Path) -> bool {
294    use crate::core::config::RulesInjection;
295    let mut seen = std::collections::HashSet::new();
296    for injection in [RulesInjection::Shared, RulesInjection::Dedicated] {
297        for target in build_rules_targets(home, injection) {
298            if !seen.insert(target.path.clone()) {
299                continue;
300            }
301            if let Ok(content) = std::fs::read_to_string(&target.path)
302                && RulesFile::parse(&content).has_content()
303            {
304                return true;
305            }
306        }
307    }
308    false
309}
310
311fn match_agent_name(cli_key: &str, target_name: &str) -> bool {
312    let needle = cli_key.to_lowercase();
313    let tn = target_name.to_lowercase();
314    if needle == "pi" {
315        return tn.contains("pi coding");
316    }
317    if needle == "omp" {
318        return tn.contains("oh my pi");
319    }
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 == "crush" && tn.contains("crush"))
339        || (needle == "verdent" && tn.contains("verdent"))
340        || (needle == "continue" && tn.contains("continue"))
341        || (needle == "qwen" && tn.contains("qwen"))
342        || (needle == "antigravity" && tn.contains("antigravity"))
343        || (needle == "augment" && tn.contains("augment"))
344        || (needle == "openclaw" && tn.contains("openclaw"))
345        || (needle == "grok" && tn.contains("grok"))
346        || (needle == "vscode" && (tn.contains("vs code") || tn.contains("vscode")))
347}
348
349/// Check if the rules file for a given MCP client is up-to-date.
350pub fn check_rules_freshness(client_name: &str) -> Option<String> {
351    let home = dirs::home_dir()?;
352    check_rules_freshness_at_home(client_name, &home)
353}
354
355fn check_rules_freshness_at_home(client_name: &str, home: &std::path::Path) -> Option<String> {
356    let cfg = crate::core::config::Config::load();
357    if cfg.declines_rule_steering()
358        || cfg.rules_scope_effective() == crate::core::config::RulesScope::Project
359    {
360        return None;
361    }
362    let injection = cfg.rules_injection_effective();
363    let targets = build_rules_targets(home, injection);
364
365    let matched: Vec<&RulesTarget> = targets
366        .iter()
367        .filter(|t| match_agent_name(client_name, t.name))
368        .collect();
369
370    if matched.is_empty() {
371        return None;
372    }
373
374    for target in &matched {
375        // Keep freshness eligibility identical to inject_all_rules(): never
376        // advertise an automatic repair for a target the writer would skip.
377        if !is_tool_detected(target, home) || !detect::is_mcp_configured(target, home) {
378            continue;
379        }
380        if !target.path.exists() {
381            continue;
382        }
383        let content = std::fs::read_to_string(&target.path).ok()?;
384        let file = RulesFile::parse(&content);
385        if file.has_content() && !file.is_current() {
386            return Some(format!(
387                "[RULES OUTDATED] Your {} rules were written by an older lean-ctx version. \
388                 Re-read your rules file ({}) or run `lean-ctx setup` to update, \
389                 then start a new session for full compatibility.",
390                target.name,
391                target.path.display()
392            ));
393        }
394    }
395
396    None
397}
398
399pub fn collect_rules_status(home: &std::path::Path) -> Vec<RulesTargetStatus> {
400    let injection = crate::core::config::Config::load().rules_injection_effective();
401    let targets = build_rules_targets(home, injection);
402    let mut out = Vec::new();
403
404    for target in &targets {
405        let detected = is_tool_detected(target, home);
406        let path = target.path.to_string_lossy().to_string();
407
408        let state = if !detected {
409            "not_detected".to_string()
410        } else if !target.path.exists() {
411            "missing".to_string()
412        } else {
413            match std::fs::read_to_string(&target.path) {
414                Ok(content) => {
415                    let file = RulesFile::parse(&content);
416                    if file.has_content() {
417                        if file.is_current() {
418                            "up_to_date".to_string()
419                        } else {
420                            "outdated".to_string()
421                        }
422                    } else {
423                        "present_without_marker".to_string()
424                    }
425                }
426                Err(_) => "read_error".to_string(),
427            }
428        };
429
430        out.push(RulesTargetStatus {
431            name: target.name.to_string(),
432            detected,
433            path,
434            state,
435            note: None,
436        });
437    }
438
439    out
440}