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