Skip to main content

lean_ctx/rules_inject/
content.rs

1//! The rules/skill payloads lean-ctx injects: shared + dedicated markdown,
2//! Cursor MDC frontmatter, and per-agent rule paths.
3//!
4//! Rule CONTENT is delegated to `core::rules_canonical` — this module only
5//! handles format dispatch and the Cursor-specific frontmatter.
6
7use std::path::{Path, PathBuf};
8
9use crate::core::rules_canonical::{self as rc, Wrapper};
10
11/// The wrapper a Cursor mdc at `mdc_path` should carry (GL #1153): the
12/// honest `HookCovered` profile when the sibling `hooks.json` (always under
13/// the same `.cursor/` dir) shows lean-ctx compressing the native tools,
14/// otherwise the full `Dedicated` mapping. Path-derived so isolated test
15/// homes and the real `~/.cursor` behave identically.
16pub(super) fn cursor_wrapper_for_mdc(mdc_path: &Path) -> Wrapper {
17    let covered = mdc_path
18        .ancestors()
19        .find(|path| {
20            path.file_name()
21                .is_some_and(|name| name == std::ffi::OsStr::new(".cursor"))
22        })
23        .is_some_and(|cursor_dir| {
24            crate::core::rules_channel::cursor_hooks_json_covers(&cursor_dir.join("hooks.json"))
25        });
26    if covered {
27        Wrapper::HookCovered
28    } else {
29        Wrapper::Dedicated
30    }
31}
32
33/// Wrap a rendered rules body in the Cursor mdc frontmatter. The description
34/// stays profile-neutral: whether native tools are replaced (Dedicated) or
35/// hook-covered (GL #1153) is stated by the body itself.
36pub fn cursor_mdc_document(body: &str) -> String {
37    format!(
38        "---\n\
39         description: \"lean-ctx: context compression layer — \
40         tool guidance in rule body.\"\n\
41         globs: **/*\n\
42         alwaysApply: true\n\
43         ---\n\n\
44         {body}"
45    )
46}
47
48/// Frontmatter every Antigravity modular rule needs: a file without a valid
49/// `trigger` is silently discarded (antigravity.google/docs/rules).
50pub(super) const ANTIGRAVITY_RULE_FRONTMATTER: &str = "---\n\
51     trigger: always_on\n\
52     description: \"lean-ctx: context compression layer, tool guidance in rule body.\"\n\
53     ---\n\n";
54
55/// Pi reaches lean-ctx through the pi-lean-ctx extension, whose own
56/// (CLI-backed, always present) tools are `ctx_grep`, `ctx_find` and `ctx_ls`;
57/// `ctx_search`, `ctx_glob` and `ctx_tree` exist there only when its MCP
58/// bridge lists them. Oh My Pi registers the lean-ctx MCP server itself, so
59/// its tool names match the canonical block and it gets no note.
60const PI_TOOL_NAMES: &str = "Pi (pi-lean-ctx), for each tool it lists: \
61Grep -> ctx_grep(pattern, path), Glob/find -> ctx_find(pattern, path), \
62ls -> ctx_ls(path); ctx_search, ctx_glob and ctx_tree also only when listed.";
63
64/// The rendered block `block` with the tool names `target_name`'s host
65/// actually exposes, when they differ from the canonical ones. A fixed line
66/// per host, so the block stays a deterministic function of the render.
67pub(super) fn with_host_tool_names(target_name: &str, block: String) -> String {
68    if target_name != "Pi Coding Agent" {
69        return block;
70    }
71    match block.rfind(rc::END_MARK) {
72        Some(end) => format!(
73            "{}\n{PI_TOOL_NAMES}\n{}",
74            block[..end].trim_end(),
75            &block[end..]
76        ),
77        None => block,
78    }
79}
80
81/// Whether `content` opens with a YAML frontmatter fence. Editors on Windows
82/// save CRLF line ends and sometimes a byte-order mark; both still count.
83pub(super) fn starts_with_frontmatter(content: &str) -> bool {
84    let content = content.strip_prefix('\u{feff}').unwrap_or(content);
85    content.starts_with("---\n") || content.starts_with("---\r\n")
86}
87
88/// Prefix `content` with the Antigravity frontmatter unless it already
89/// starts with a frontmatter block (a user may have tuned the trigger).
90pub(super) fn with_antigravity_frontmatter(content: String) -> String {
91    if starts_with_frontmatter(&content) {
92        content
93    } else {
94        format!("{ANTIGRAVITY_RULE_FRONTMATTER}{content}")
95    }
96}
97
98pub fn opencode_dedicated_rules_path(home: &std::path::Path) -> PathBuf {
99    home.join(".config/opencode/rules/lean-ctx.md")
100}
101
102pub fn antigravity_dedicated_rules_path(home: &std::path::Path) -> PathBuf {
103    home.join(".gemini/config/rules/lean-ctx.md")
104}
105
106pub fn gemini_dedicated_rules_path(home: &std::path::Path) -> PathBuf {
107    home.join(".gemini").join(GEMINI_DEDICATED_CONTEXT_FILENAME)
108}
109
110/// The `context.fileName` entry registered for Gemini in dedicated mode.
111pub const GEMINI_DEDICATED_CONTEXT_FILENAME: &str = "LEANCTX.md";