Skip to main content

lean_ctx_ext/core/contextops/
lint.rs

1// SPDX-License-Identifier: Apache-2.0
2use serde::{Deserialize, Serialize};
3
4use super::config::RulesConfig;
5
6#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
7pub enum LintSeverity {
8    Error,
9    Warning,
10    Info,
11}
12
13impl std::fmt::Display for LintSeverity {
14    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
15        match self {
16            Self::Error => write!(f, "ERROR"),
17            Self::Warning => write!(f, "WARNING"),
18            Self::Info => write!(f, "INFO"),
19        }
20    }
21}
22
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct LintWarning {
25    pub severity: LintSeverity,
26    pub code: String,
27    pub message: String,
28    pub target: Option<String>,
29}
30
31const KNOWN_TOOLS: &[&str] = &[
32    "ctx_read",
33    "ctx_shell",
34    "ctx_search",
35    "ctx_tree",
36    "ctx_compress",
37    "ctx_edit",
38    "ctx_session",
39    "ctx_knowledge",
40    "ctx_heatmap",
41    "ctx_cost",
42    "ctx_metrics",
43    "ctx_call",
44    "ctx_callgraph",
45    "ctx_gain",
46    "ctx_provider",
47    "ctx_doc",
48    "ctx_pack",
49    "ctx_graph",
50    "ctx_multi_repo",
51    "ctx_agent",
52    "ctx_dedup",
53    "ctx_preload",
54];
55
56const REQUIRED_SECTIONS: &[&str] = &["Mode Selection", "File Editing"];
57
58pub(crate) fn lint(config: &RulesConfig, home: &std::path::Path) -> Vec<LintWarning> {
59    let mut warnings = Vec::new();
60
61    lint_core_content(&config.rules.core.content, &mut warnings);
62    lint_version(&config.rules.version, &mut warnings);
63    lint_agent_consistency(config, &mut warnings);
64    lint_targets(home, &mut warnings);
65
66    warnings
67}
68
69fn lint_core_content(content: &str, warnings: &mut Vec<LintWarning>) {
70    if content.trim().is_empty() {
71        warnings.push(LintWarning {
72            severity: LintSeverity::Error,
73            code: "EMPTY_CORE".to_string(),
74            message: "Core rules content is empty".to_string(),
75            target: None,
76        });
77        return;
78    }
79
80    for section in REQUIRED_SECTIONS {
81        if !content.contains(section) {
82            warnings.push(LintWarning {
83                severity: LintSeverity::Warning,
84                code: "MISSING_SECTION".to_string(),
85                message: format!("Core rules missing required section: {section}"),
86                target: None,
87            });
88        }
89    }
90
91    check_tool_references(content, None, warnings);
92}
93
94fn lint_version(version: &str, warnings: &mut Vec<LintWarning>) {
95    if version.is_empty() {
96        warnings.push(LintWarning {
97            severity: LintSeverity::Error,
98            code: "NO_VERSION".to_string(),
99            message: "Rules version is not set".to_string(),
100            target: None,
101        });
102    }
103
104    let expected = format!(
105        "<!-- version: {} -->",
106        crate::core::rules_canonical::RULES_VERSION
107    );
108    if !expected.contains(version) && !version.contains("1.0") {
109        warnings.push(LintWarning {
110            severity: LintSeverity::Info,
111            code: "VERSION_MISMATCH".to_string(),
112            message: format!(
113                "Config version '{version}' does not match current rules version '{expected}'"
114            ),
115            target: None,
116        });
117    }
118}
119
120fn lint_agent_consistency(config: &RulesConfig, warnings: &mut Vec<LintWarning>) {
121    for (agent_name, agent_rules) in &config.rules.agent {
122        check_tool_references(&agent_rules.extra, Some(agent_name), warnings);
123
124        if agent_rules.extra.contains("NEVER") && config.rules.core.content.contains("ALWAYS") {
125            let never_lines: Vec<&str> = agent_rules
126                .extra
127                .lines()
128                .filter(|l| l.contains("NEVER"))
129                .collect();
130            let always_lines: Vec<&str> = config
131                .rules
132                .core
133                .content
134                .lines()
135                .filter(|l| l.contains("ALWAYS"))
136                .collect();
137
138            for never_line in &never_lines {
139                for always_line in &always_lines {
140                    if lines_reference_same_tool(never_line, always_line) {
141                        warnings.push(LintWarning {
142                            severity: LintSeverity::Warning,
143                            code: "CONFLICT".to_string(),
144                            message: format!(
145                                "Agent '{agent_name}' has NEVER rule that may conflict with core ALWAYS rule"
146                            ),
147                            target: Some(agent_name.clone()),
148                        });
149                        break;
150                    }
151                }
152            }
153        }
154    }
155}
156
157fn lint_targets(home: &std::path::Path, warnings: &mut Vec<LintWarning>) {
158    let statuses = crate::rules_inject::collect_rules_status(home);
159    for status in &statuses {
160        if status.detected && status.state == "outdated" {
161            warnings.push(LintWarning {
162                severity: LintSeverity::Warning,
163                code: "OUTDATED_TARGET".to_string(),
164                message: format!("{} has outdated rules (version mismatch)", status.name),
165                target: Some(status.name.clone()),
166            });
167        }
168    }
169}
170
171fn check_tool_references(content: &str, agent: Option<&str>, warnings: &mut Vec<LintWarning>) {
172    for word in content.split_whitespace() {
173        let cleaned = word.trim_matches(|c: char| !c.is_alphanumeric() && c != '_');
174        if cleaned.starts_with("ctx_") && !KNOWN_TOOLS.contains(&cleaned) {
175            warnings.push(LintWarning {
176                severity: LintSeverity::Warning,
177                code: "UNKNOWN_TOOL".to_string(),
178                message: format!("References unknown tool: {cleaned}"),
179                target: agent.map(String::from),
180            });
181        }
182    }
183}
184
185fn lines_reference_same_tool(line_a: &str, line_b: &str) -> bool {
186    for tool in KNOWN_TOOLS {
187        if line_a.contains(tool) && line_b.contains(tool) {
188            return true;
189        }
190    }
191    false
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197    use crate::core::contextops::config::{AgentRules, CoreRules, RulesSection};
198
199    fn make_config(core_content: &str) -> RulesConfig {
200        RulesConfig {
201            rules: RulesSection {
202                version: "1.0".to_string(),
203                core: CoreRules {
204                    content: core_content.to_string(),
205                },
206                agent: std::collections::HashMap::new(),
207            },
208        }
209    }
210
211    #[test]
212    fn lint_severity_display() {
213        assert_eq!(LintSeverity::Error.to_string(), "ERROR");
214        assert_eq!(LintSeverity::Warning.to_string(), "WARNING");
215        assert_eq!(LintSeverity::Info.to_string(), "INFO");
216    }
217
218    #[test]
219    fn lint_empty_core() {
220        let config = make_config("");
221        let home = std::path::PathBuf::from("/tmp/fake_lint_test");
222        let warnings = lint(&config, &home);
223        assert!(warnings.iter().any(|w| w.code == "EMPTY_CORE"));
224    }
225
226    #[test]
227    fn lint_missing_sections() {
228        let config = make_config("some rules without required sections");
229        let home = std::path::PathBuf::from("/tmp/fake_lint_test");
230        let warnings = lint(&config, &home);
231        let missing: Vec<_> = warnings
232            .iter()
233            .filter(|w| w.code == "MISSING_SECTION")
234            .collect();
235        assert!(!missing.is_empty());
236    }
237
238    #[test]
239    fn lint_unknown_tool() {
240        let config = make_config("## Mode Selection\n## File Editing\nUse ctx_nonexistent_tool");
241        let home = std::path::PathBuf::from("/tmp/fake_lint_test");
242        let warnings = lint(&config, &home);
243        assert!(warnings.iter().any(|w| w.code == "UNKNOWN_TOOL"));
244    }
245
246    #[test]
247    fn lint_known_tools_pass() {
248        let config = make_config("## Mode Selection\n## File Editing\nUse ctx_read and ctx_shell");
249        let home = std::path::PathBuf::from("/tmp/fake_lint_test");
250        let warnings = lint(&config, &home);
251        assert!(!warnings.iter().any(|w| w.code == "UNKNOWN_TOOL"));
252    }
253
254    #[test]
255    fn lint_conflict_detection() {
256        let mut config = make_config("## Mode Selection\n## File Editing\nALWAYS use ctx_read");
257        config.rules.agent.insert(
258            "test_agent".to_string(),
259            AgentRules {
260                extra: "NEVER use ctx_read".to_string(),
261            },
262        );
263        let home = std::path::PathBuf::from("/tmp/fake_lint_test");
264        let warnings = lint(&config, &home);
265        assert!(warnings.iter().any(|w| w.code == "CONFLICT"));
266    }
267
268    #[test]
269    fn lint_no_version() {
270        let mut config = make_config("## Mode Selection\n## File Editing\nrules");
271        config.rules.version = String::new();
272        let home = std::path::PathBuf::from("/tmp/fake_lint_test");
273        let warnings = lint(&config, &home);
274        assert!(warnings.iter().any(|w| w.code == "NO_VERSION"));
275    }
276
277    #[test]
278    fn lines_reference_same_tool_true() {
279        assert!(lines_reference_same_tool(
280            "NEVER use ctx_read for context",
281            "ALWAYS use ctx_read for editing"
282        ));
283    }
284
285    #[test]
286    fn lines_reference_same_tool_false() {
287        assert!(!lines_reference_same_tool(
288            "NEVER use ctx_read",
289            "ALWAYS use ctx_shell"
290        ));
291    }
292}