lean-ctx-engine 3.12.2

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and proxy integrations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! Rules + SKILL.md injection for every supported agent, split by concern
//! (GL#440): `content` (payloads), `targets` (agent catalog), `detect`
//! (installation checks), `write` (atomic file surgery), `skills` (SKILL.md).
//! This hub owns the shared types and the orchestration entry points.
//!
//! Content is delegated to `core::rules_canonical` — all rule text lives
//! there as `pub const` sections.  Markers (`START_MARK`, `END_MARK`,
//! `RULES_VERSION`) are also re-exported from canonical.

use std::path::PathBuf;

use serde::{Deserialize, Serialize};

use crate::core::rules_canonical::RulesFile;
pub use crate::core::rules_canonical::{END_MARK, RULES_VERSION, START_MARK};

mod content;
mod detect;
mod skills;
mod targets;
#[cfg(test)]
mod tests;
mod write;

pub use content::cursor_mdc_document;
pub use content::{
    GEMINI_DEDICATED_CONTEXT_FILENAME, gemini_dedicated_rules_path, opencode_dedicated_rules_path,
};
pub use skills::{
    install_all_skills, install_skill_for_agent, install_skills_where, planned_skill_files,
};

/// The tool set client-neutral rule files may name: what `tools/list` offers a
/// client without quirks (the lean core when no profile is pinned). These files
/// are shared by every agent in a home or project, so no client is known.
fn shared_surface_profile(
    cfg: &crate::core::config::Config,
) -> crate::core::tool_profiles::ToolProfile {
    crate::core::tool_visibility::guidance_profile(cfg, "")
}

/// Forwarding functions — content is delegated to `core::rules_canonical`.
pub fn canonical_rules_block() -> String {
    let cfg = crate::core::config::Config::load();
    let shadow = cfg.shadow_mode;
    let level = crate::core::config::CompressionLevel::effective(&cfg);
    let profile = shared_surface_profile(&cfg);
    crate::core::rules_canonical::render(
        shadow,
        crate::core::rules_canonical::Wrapper::Shared,
        level,
        &profile,
    )
}
pub fn rules_shared_content() -> String {
    canonical_rules_block()
}
pub fn rules_dedicated_markdown() -> String {
    let cfg = crate::core::config::Config::load();
    let shadow = cfg.shadow_mode;
    let level = crate::core::config::CompressionLevel::effective(&cfg);
    let profile = shared_surface_profile(&cfg);
    crate::core::rules_canonical::render(
        shadow,
        crate::core::rules_canonical::Wrapper::Dedicated,
        level,
        &profile,
    )
}

/// Long-form rules for the on-demand project `LEAN-CTX.md` (#578). Same
/// config-driven shadow/compression handling as the dedicated render, but the
/// LONGFORM profile with the verbose teaching sections.
pub fn rules_longform_markdown() -> String {
    let cfg = crate::core::config::Config::load();
    let shadow = cfg.shadow_mode;
    let level = crate::core::config::CompressionLevel::effective(&cfg);
    let profile = shared_surface_profile(&cfg);
    crate::core::rules_canonical::render(
        shadow,
        crate::core::rules_canonical::Wrapper::Longform,
        level,
        &profile,
    )
}

/// The canonical rules block lean-ctx would write for each target, keyed by the
/// target's display name.
///
/// Drift detection compares against this instead of guessing shared-vs-dedicated
/// from a target's on-disk contents: a freshly synced `SharedMarkdown` file (e.g.
/// Copilot CLI, Codex CLI) carries no user text, which a content heuristic
/// mistook for the dedicated layout and then flagged as drifted on every sync.
/// Keying by the real `RulesFormat` keeps `sync` and `diff` in agreement (#548).
pub fn expected_blocks_by_target(
    home: &std::path::Path,
) -> std::collections::HashMap<String, String> {
    let injection = crate::core::config::Config::load().rules_injection_effective();
    let cfg = crate::core::config::Config::load();
    let shadow = cfg.shadow_mode;
    let level = crate::core::config::CompressionLevel::effective(&cfg);
    build_rules_targets(home, injection)
        .into_iter()
        .map(|target| {
            // The profile `inject_rules` writes with, so a freshly synced
            // file never reads as drifted (#1008, #1849).
            let profile = write::profile_for_target(&cfg, target.name);
            let wrapper = match target.format {
                RulesFormat::SharedMarkdown => crate::core::rules_canonical::Wrapper::Shared,
                RulesFormat::DedicatedMarkdown => crate::core::rules_canonical::Wrapper::Dedicated,
                // CursorMdc embeds the render verbatim between the markers
                // (frontmatter lives outside them); the wrapper is dynamic —
                // HookCovered on hook-covered installs (GL #1153).
                RulesFormat::CursorMdc => content::cursor_wrapper_for_mdc(&target.path),
            };
            let expected = crate::core::rules_canonical::render(shadow, wrapper, level, &profile);
            (target.name.to_string(), expected)
        })
        .collect()
}

use detect::is_tool_detected;
use targets::build_rules_targets;
use write::inject_rules;

struct RulesTarget {
    name: &'static str,
    path: PathBuf,
    format: RulesFormat,
}

enum RulesFormat {
    SharedMarkdown,
    DedicatedMarkdown,
    CursorMdc,
}

#[derive(Debug, Default)]
pub struct InjectResult {
    pub injected: Vec<String>,
    pub updated: Vec<String>,
    pub already: Vec<String>,
    pub errors: Vec<String>,
    pub backed_up: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RulesTargetStatus {
    pub name: String,
    pub detected: bool,
    pub path: String,
    pub state: String,
    pub note: Option<String>,
}

enum RulesResult {
    Updated,
    AlreadyPresent,
}

pub fn inject_all_rules(home: &std::path::Path) -> InjectResult {
    inject_rules_where(home, &|_| true)
}

/// Agent key (as `init --agent` / `setup --agents` spell it) that owns a
/// rules target, so a setup agent selection can filter rules files too.
fn rules_agent_key(target_name: &str) -> Option<&'static str> {
    Some(match target_name {
        "Gemini CLI" => "gemini",
        "VS Code" => "vscode",
        "Copilot CLI" => "copilot",
        "Cursor" => "cursor",
        "Windsurf" => "windsurf",
        "Zed" => "zed",
        "Cline" => "cline",
        "Roo Code" => "roo",
        "OpenCode" => "opencode",
        "Continue" => "continue",
        "Amp" => "amp",
        "Qwen Code" => "qwen",
        "Trae" => "trae",
        "Amazon Q Developer" => "amazonq",
        "JetBrains IDEs" => "jetbrains",
        "Antigravity" => "antigravity",
        "Pi Coding Agent" => "pi",
        "AWS Kiro" => "kiro",
        "Verdent" => "verdent",
        "Crush" => "crush",
        "Augment" => "augment",
        "OpenClaw" => "openclaw",
        "Codex CLI" => "codex",
        "Grok" => "grok",
        "Oh My Pi" => "omp",
        "Hermes Agent" => "hermes",
        "Qoder" => "qoder",
        _ => return None,
    })
}

/// Rules files a setup run would write for the agents `allows` admits: the
/// installed tools' targets plus the Claude Code pointer block. Writes nothing.
/// The real run additionally skips tools whose MCP entry is missing (GH #1435).
#[must_use]
pub fn planned_rules_files(
    home: &std::path::Path,
    allows: &dyn Fn(&str) -> bool,
) -> Vec<(String, PathBuf)> {
    let cfg = crate::core::config::Config::load();
    let injection = cfg.rules_injection_effective();
    if cfg.rules_scope_effective() == crate::core::config::RulesScope::Project
        || injection == crate::core::config::RulesInjection::Off
    {
        return Vec::new();
    }
    let mut files = Vec::new();
    if injection == crate::core::config::RulesInjection::Shared
        && allows("claude")
        && detect::is_named_agent_ready("Claude Code", home)
    {
        files.push((
            "Claude Code".to_string(),
            crate::core::editor_registry::claude_state_dir(home).join("CLAUDE.md"),
        ));
    }
    for target in build_rules_targets(home, injection) {
        if rules_agent_key(target.name).is_some_and(allows) && is_tool_detected(&target, home) {
            files.push((target.name.to_string(), target.path));
        }
    }
    files
}

/// [`inject_all_rules`] restricted to the agents `allows` admits (by agent key).
pub fn inject_rules_where(home: &std::path::Path, allows: &dyn Fn(&str) -> bool) -> InjectResult {
    let cfg = crate::core::config::Config::load();
    if cfg.rules_scope_effective() == crate::core::config::RulesScope::Project {
        return InjectResult::default();
    }
    if cfg.rules_injection_effective() == crate::core::config::RulesInjection::Off {
        return InjectResult::default();
    }

    let targets = build_rules_targets(home, cfg.rules_injection_effective());

    let mut result = InjectResult::default();

    if cfg.rules_injection_effective() == crate::core::config::RulesInjection::Shared
        && allows("claude")
        && detect::is_named_agent_ready("Claude Code", home)
    {
        sync_claude_pointer_block(home, &mut result);
    }

    for target in &targets {
        if !rules_agent_key(target.name).is_some_and(allows) {
            continue;
        }
        if !is_tool_detected(target, home) {
            continue;
        }
        if rules_agent_key(target.name)
            .is_some_and(|key| crate::core::governor_hosts::is_installed(key, home))
        {
            continue;
        }
        // GH #1435: skip rules injection when the tool's MCP server is not
        // configured — a rules file that mandates ctx_* tools for an agent
        // that can't reach them is a self-contradiction.
        if !detect::is_mcp_configured(target, home) {
            continue;
        }

        let bak_path = target.path.with_extension(format!(
            "{}.bak",
            target
                .path
                .extension()
                .and_then(|e| e.to_str())
                .unwrap_or("")
        ));
        let bak_existed_before = bak_path.exists();
        let bak_mtime_before = bak_existed_before
            .then(|| {
                std::fs::metadata(&bak_path)
                    .ok()
                    .and_then(|m| m.modified().ok())
            })
            .flatten();

        match inject_rules(target) {
            Ok(RulesResult::Updated) => {
                result.updated.push(target.name.to_string());
                let bak_is_new = if bak_existed_before {
                    std::fs::metadata(&bak_path)
                        .ok()
                        .and_then(|m| m.modified().ok())
                        != bak_mtime_before
                } else {
                    bak_path.exists()
                };
                if bak_is_new {
                    result
                        .backed_up
                        .push(bak_path.to_string_lossy().to_string());
                }
            }
            Ok(RulesResult::AlreadyPresent) => result.already.push(target.name.to_string()),
            Err(e) => result.errors.push(format!("{}: {e}", target.name)),
        }
    }

    result
}

/// Inject global rules for a single agent (by CLI key like "opencode", "cursor", etc.).
pub fn inject_rules_for_agent(home: &std::path::Path, agent_key: &str) -> InjectResult {
    let cfg = crate::core::config::Config::load();
    if cfg.rules_scope_effective() == crate::core::config::RulesScope::Project {
        return InjectResult::default();
    }
    if cfg.rules_injection_effective() == crate::core::config::RulesInjection::Off {
        return InjectResult::default();
    }

    // The governor setup owns the host's rules channel (its short block).
    if crate::core::governor_hosts::is_installed(agent_key, home) {
        return InjectResult::default();
    }
    let targets = build_rules_targets(home, cfg.rules_injection_effective());
    let mut result = InjectResult::default();

    if cfg.rules_injection_effective() == crate::core::config::RulesInjection::Shared
        && is_claude_agent_key(agent_key)
    {
        sync_claude_pointer_block(home, &mut result);
        return result;
    }

    for target in &targets {
        if !match_agent_name(agent_key, target.name) {
            continue;
        }

        let bak_path = target.path.with_extension(format!(
            "{}.bak",
            target
                .path
                .extension()
                .and_then(|e| e.to_str())
                .unwrap_or("")
        ));
        let bak_existed_before = bak_path.exists();

        match inject_rules(target) {
            Ok(RulesResult::Updated) => {
                result.updated.push(target.name.to_string());
                if !bak_existed_before && bak_path.exists() {
                    result
                        .backed_up
                        .push(bak_path.to_string_lossy().to_string());
                }
            }
            Ok(RulesResult::AlreadyPresent) => result.already.push(target.name.to_string()),
            Err(e) => result.errors.push(format!("{}: {e}", target.name)),
        }
    }

    result
}

fn is_claude_agent_key(agent_key: &str) -> bool {
    matches!(
        agent_key.trim().to_ascii_lowercase().as_str(),
        "claude" | "claude-code" | "claude_code" | "claude code"
    )
}

fn sync_claude_pointer_block(home: &std::path::Path, result: &mut InjectResult) {
    let mode = crate::core::hook_mode::recommend_hook_mode("claude");
    match crate::core::claude_md::sync_claude_global_rules_block(home, mode) {
        Ok(true) => result.updated.push("Claude Code".to_string()),
        Ok(false) => result.already.push("Claude Code".to_string()),
        Err(error) => result.errors.push(format!("Claude Code: {error}")),
    }
}

/// Returns `true` if a lean-ctx rules marker is present in *any* supported
/// agent's rules file.
#[must_use]
pub fn any_rules_marker_present(home: &std::path::Path) -> bool {
    use crate::core::config::RulesInjection;
    let mut seen = std::collections::HashSet::new();
    for injection in [RulesInjection::Shared, RulesInjection::Dedicated] {
        for target in build_rules_targets(home, injection) {
            if !seen.insert(target.path.clone()) {
                continue;
            }
            if let Ok(content) = std::fs::read_to_string(&target.path)
                && RulesFile::parse(&content).has_content()
            {
                return true;
            }
        }
    }
    false
}

/// Whether `lean-ctx setup` has left guidance for any host: a rules target,
/// or the instruction-file block of a host that has no rules target (Claude
/// Code's `CLAUDE.md`, CodeBuddy's `CODEBUDDY.md`, #555). The "run setup" tip
/// needs this wider check: [`any_rules_marker_present`] alone never sees a
/// Claude-only installation.
#[must_use]
pub fn host_guidance_present(home: &std::path::Path) -> bool {
    use crate::core::editor_registry::{claude_state_dir, codebuddy_state_dir};
    any_rules_marker_present(home)
        || pointer_block_present(&[
            claude_state_dir(home).join("CLAUDE.md"),
            codebuddy_state_dir(home).join("CODEBUDDY.md"),
        ])
}

fn pointer_block_present(files: &[std::path::PathBuf]) -> bool {
    files.iter().any(|path| {
        // These are pointer blocks, delimited by AGENTS_BLOCK_START (#549).
        std::fs::read_to_string(path)
            .is_ok_and(|c| c.contains(crate::core::rules_canonical::AGENTS_BLOCK_START))
    })
}

fn match_agent_name(cli_key: &str, target_name: &str) -> bool {
    let needle = cli_key.to_lowercase();
    let tn = target_name.to_lowercase();
    if needle == "pi" {
        return tn.contains("pi coding");
    }
    if needle == "omp" {
        return tn.contains("oh my pi");
    }
    needle.contains(&tn)
        || tn.contains(&needle)
        || (needle.contains("cursor") && tn.contains("cursor"))
        || (needle.contains("claude") && tn.contains("claude"))
        || (needle.contains("codebuddy") && tn.contains("codebuddy"))
        || (needle.contains("windsurf") && tn.contains("windsurf"))
        || (needle.contains("codex") && tn.contains("claude"))
        || (needle.contains("zed") && tn.contains("zed"))
        || (needle.contains("copilot") && tn.contains("copilot"))
        || (needle.contains("jetbrains") && tn.contains("jetbrains"))
        || (needle.contains("kiro") && tn.contains("kiro"))
        || (needle.contains("gemini") && tn.contains("gemini"))
        || (needle == "opencode" && tn.contains("opencode"))
        || (needle == "cline" && tn.contains("cline"))
        || (needle == "roo" && tn.contains("roo"))
        || (needle == "amp" && tn.contains("amp"))
        || (needle == "trae" && tn.contains("trae"))
        || (needle == "amazonq" && tn.contains("amazon"))
        || (needle == "crush" && tn.contains("crush"))
        || (needle == "verdent" && tn.contains("verdent"))
        || (needle == "continue" && tn.contains("continue"))
        || (needle == "qwen" && tn.contains("qwen"))
        || (needle == "antigravity" && tn.contains("antigravity"))
        || (needle == "augment" && tn.contains("augment"))
        || (needle == "openclaw" && tn.contains("openclaw"))
        || (needle == "grok" && tn.contains("grok"))
        || (needle == "vscode" && (tn.contains("vs code") || tn.contains("vscode")))
}

/// Check if the rules file for a given MCP client is up-to-date.
pub fn check_rules_freshness(client_name: &str) -> Option<String> {
    let home = dirs::home_dir()?;
    check_rules_freshness_at_home(client_name, &home)
}

fn check_rules_freshness_at_home(client_name: &str, home: &std::path::Path) -> Option<String> {
    let cfg = crate::core::config::Config::load();
    if cfg.declines_rule_steering()
        || cfg.rules_scope_effective() == crate::core::config::RulesScope::Project
    {
        return None;
    }
    let injection = cfg.rules_injection_effective();
    let targets = build_rules_targets(home, injection);

    let matched: Vec<&RulesTarget> = targets
        .iter()
        .filter(|t| match_agent_name(client_name, t.name))
        .collect();

    if matched.is_empty() {
        return None;
    }

    for target in &matched {
        // Keep freshness eligibility identical to inject_all_rules(): never
        // advertise an automatic repair for a target the writer would skip.
        if !is_tool_detected(target, home) || !detect::is_mcp_configured(target, home) {
            continue;
        }
        if !target.path.exists() {
            continue;
        }
        let content = std::fs::read_to_string(&target.path).ok()?;
        let file = RulesFile::parse(&content);
        if file.has_content() && !file.is_current() {
            return Some(format!(
                "[RULES OUTDATED] Your {} rules were written by an older lean-ctx version. \
                 Re-read your rules file ({}) or run `lean-ctx setup` to update, \
                 then start a new session for full compatibility.",
                target.name,
                target.path.display()
            ));
        }
    }

    None
}

pub fn collect_rules_status(home: &std::path::Path) -> Vec<RulesTargetStatus> {
    let injection = crate::core::config::Config::load().rules_injection_effective();
    let targets = build_rules_targets(home, injection);
    let mut out = Vec::new();

    for target in &targets {
        let detected = is_tool_detected(target, home);
        let path = target.path.to_string_lossy().to_string();

        let state = if !detected {
            "not_detected".to_string()
        } else if !target.path.exists() {
            "missing".to_string()
        } else {
            match std::fs::read_to_string(&target.path) {
                Ok(content) => {
                    let file = RulesFile::parse(&content);
                    if file.has_content() {
                        if file.is_current() {
                            "up_to_date".to_string()
                        } else {
                            "outdated".to_string()
                        }
                    } else {
                        "present_without_marker".to_string()
                    }
                }
                Err(_) => "read_error".to_string(),
            }
        };

        out.push(RulesTargetStatus {
            name: target.name.to_string(),
            detected,
            path,
            state,
            note: None,
        });
    }

    out
}