Skip to main content

lean_ctx_ext/core/
instruction_compiler.rs

1// SPDX-License-Identifier: Apache-2.0
2use crate::core::client_constraints;
3use crate::core::profiles;
4use crate::core::protocol::CrpMode;
5
6#[derive(Debug, Clone, serde::Serialize)]
7#[serde(rename_all = "camelCase")]
8pub struct CompiledRuleFile {
9    pub path: String,
10    pub content: String,
11}
12
13#[derive(Debug, Clone, serde::Serialize)]
14#[serde(rename_all = "camelCase")]
15pub struct CompiledInstructions {
16    pub schema_version: u32,
17    pub client: String,
18    pub profile: String,
19    pub crp_mode: String,
20    pub unified_tool_mode: bool,
21    pub mcp_instructions: String,
22    pub rules_files: Vec<CompiledRuleFile>,
23}
24
25#[derive(Debug, Clone, Copy, Default)]
26pub struct CompileOptions {
27    pub unified: bool,
28    pub include_rules_files: bool,
29    pub crp_mode_override: Option<CrpMode>,
30}
31
32pub fn compile(
33    client_id: &str,
34    profile_name: &str,
35    opts: CompileOptions,
36) -> Result<CompiledInstructions, String> {
37    let client_id = client_id.trim();
38    let profile_name = profile_name.trim();
39    if client_id.is_empty() {
40        return Err("missing client id".to_string());
41    }
42    if profile_name.is_empty() {
43        return Err("missing profile name".to_string());
44    }
45
46    let constraints = client_constraints::by_client_id(client_id);
47    if constraints.is_none() {
48        return Err(format!(
49            "unknown client '{client_id}' (use 'lean-ctx instructions --list-clients')"
50        ));
51    }
52
53    let profile = profiles::load_profile(profile_name)
54        .ok_or_else(|| format!("unknown profile '{profile_name}'"))?;
55    // Same resolver the MCP server and every tool use (#1890): the Engine seam
56    // projects `CrpMode::resolve` for this profile.
57    let crp_mode = opts.crp_mode_override.unwrap_or_else(|| {
58        CrpMode::parse(profile.engine_config().compression.crp_mode).unwrap_or(CrpMode::Off)
59    });
60
61    let mcp_instructions = crate::instructions::build_instructions_with_client_for_compiler(
62        crp_mode,
63        client_id,
64        opts.unified,
65    );
66
67    let constraints = constraints.expect("client id validated above");
68    if let Some(cap) = constraints.mcp_instructions_max_chars
69        && mcp_instructions.len() > cap
70    {
71        return Err(format!(
72            "compiled MCP instructions exceed cap for {client_id}: {} > {cap}",
73            mcp_instructions.len()
74        ));
75    }
76
77    let mut rules_files = Vec::new();
78    if opts.include_rules_files && (client_id == "claude-code" || client_id == "codebuddy") {
79        let config_dir = crate::instructions::claude_config_dir_display();
80        rules_files.push(CompiledRuleFile {
81            path: format!("{config_dir}/rules/lean-ctx.md"),
82            content: crate::rules_inject::rules_dedicated_markdown(),
83        });
84    }
85
86    Ok(CompiledInstructions {
87        schema_version: 1,
88        client: client_id.to_string(),
89        profile: profile.profile.name,
90        crp_mode: crp_mode.as_str().to_string(),
91        unified_tool_mode: opts.unified,
92        mcp_instructions,
93        rules_files,
94    })
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100
101    #[test]
102    fn compiled_instructions_are_deterministic() {
103        // The guidance reads env + Config::load(); parallel env-mutating tests
104        // would otherwise change the text between the two compiles.
105        let _lock = crate::core::data_dir::test_env_lock();
106        let a = compile(
107            "cursor",
108            "exploration",
109            CompileOptions {
110                unified: false,
111                include_rules_files: false,
112                crp_mode_override: Some(CrpMode::Tdd),
113            },
114        )
115        .unwrap();
116        let b = compile(
117            "cursor",
118            "exploration",
119            CompileOptions {
120                unified: false,
121                include_rules_files: false,
122                crp_mode_override: Some(CrpMode::Tdd),
123            },
124        )
125        .unwrap();
126        assert_eq!(a.mcp_instructions, b.mcp_instructions);
127    }
128
129    #[test]
130    fn compiles_for_all_known_clients() {
131        for c in crate::core::client_constraints::ALL_CLIENTS {
132            let out = compile(
133                c.id,
134                "exploration",
135                CompileOptions {
136                    unified: false,
137                    include_rules_files: false,
138                    crp_mode_override: Some(CrpMode::Tdd),
139                },
140            )
141            .unwrap();
142            assert!(
143                !out.mcp_instructions.trim().is_empty(),
144                "empty instructions for client {}",
145                c.id
146            );
147        }
148    }
149
150    /// #1890: `lean-ctx instructions` and the MCP server/tool layer must agree
151    /// on the CRP mode for every built-in profile (default config included).
152    #[test]
153    fn compiled_crp_mode_matches_tool_resolver() {
154        let _lock = crate::core::data_dir::test_env_lock();
155        for name in ["coder", "exploration", "bugfix", "review", "passthrough"] {
156            let out = compile("claude-code", name, CompileOptions::default()).unwrap();
157            let profile = profiles::load_profile(name).unwrap();
158            let tools = CrpMode::resolve(profile.compression.crp_mode.as_deref());
159            assert_eq!(out.crp_mode, tools.as_str(), "profile {name}");
160            let expected = crate::instructions::build_instructions_with_client_for_compiler(
161                tools,
162                "claude-code",
163                false,
164            );
165            assert_eq!(out.mcp_instructions, expected, "profile {name}");
166        }
167    }
168
169    #[test]
170    fn default_coder_profile_does_not_force_tdd() {
171        let coder = profiles::load_profile("coder").unwrap();
172        assert_eq!(coder.compression.crp_mode, None);
173    }
174
175    #[test]
176    fn claude_mcp_instructions_respect_cap() {
177        let out = compile(
178            "claude-code",
179            "exploration",
180            CompileOptions {
181                unified: false,
182                include_rules_files: false,
183                crp_mode_override: Some(CrpMode::Tdd),
184            },
185        )
186        .unwrap();
187        assert!(out.mcp_instructions.len() <= 2048);
188    }
189}