lean_ctx_ext/core/
context_lint.rs1use crate::core::tokens::count_tokens;
20
21const RETEACH_PATTERNS: &[&str] = &[
25 "as you know",
26 "please note",
27 "keep in mind",
28 "it is important to",
29 "needless to say",
30 "obviously,",
31 "completes faster than",
32 "as an example",
33];
34
35const TOOL_DESC_TOKEN_BUDGET: usize = 80;
37
38const MIN_SIGNIFICANT_LINE_CHARS: usize = 24;
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum Severity {
45 Error,
47 Warn,
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum LintKind {
54 DuplicateLine,
56 ReTeaching,
58 DuplicateToolDescription,
60 VerboseToolDescription,
62}
63
64#[derive(Debug, Clone)]
66pub struct LintFinding {
67 pub severity: Severity,
68 pub kind: LintKind,
69 pub source: String,
71 pub detail: String,
72}
73
74impl LintFinding {
75 #[must_use]
77 pub(crate) fn is_error(&self) -> bool {
78 self.severity == Severity::Error
79 }
80}
81
82fn is_content_line(line: &str) -> bool {
84 let t = line.trim();
85 !t.is_empty() && !t.starts_with("<!--") && !t.starts_with('#')
86}
87
88#[must_use]
91pub(crate) fn lint_rules_text(source: &str, text: &str) -> Vec<LintFinding> {
92 let mut findings = Vec::new();
93 let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
94 for raw in text.lines() {
95 if !is_content_line(raw) {
96 continue;
97 }
98 let line = raw.trim();
99 let lower = line.to_lowercase();
100 for pat in RETEACH_PATTERNS {
101 if lower.contains(pat) {
102 findings.push(LintFinding {
103 severity: Severity::Error,
104 kind: LintKind::ReTeaching,
105 source: source.to_string(),
106 detail: format!("low-signal re-teaching phrase {pat:?}: {line}"),
107 });
108 }
109 }
110 if line.chars().count() >= MIN_SIGNIFICANT_LINE_CHARS && !seen.insert(lower) {
111 findings.push(LintFinding {
112 severity: Severity::Error,
113 kind: LintKind::DuplicateLine,
114 source: source.to_string(),
115 detail: format!("duplicate content line: {line}"),
116 });
117 }
118 }
119 findings
120}
121
122#[must_use]
125pub(crate) fn lint_tool_descriptions(tools: &[rmcp::model::Tool]) -> Vec<LintFinding> {
126 let mut findings = Vec::new();
127 let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
128 for t in tools {
129 let desc = t.description.as_deref().unwrap_or("").trim().to_string();
130 if desc.is_empty() {
131 continue;
132 }
133 let tokens = count_tokens(&desc);
134 if tokens > TOOL_DESC_TOKEN_BUDGET {
135 findings.push(LintFinding {
136 severity: Severity::Warn,
137 kind: LintKind::VerboseToolDescription,
138 source: format!("tool:{}", t.name),
139 detail: format!(
140 "{tokens} tok description — trim to when/why + the non-obvious gotcha (budget {TOOL_DESC_TOKEN_BUDGET})"
141 ),
142 });
143 }
144 if let Some(prev) = seen.insert(desc.to_lowercase(), t.name.to_string()) {
145 findings.push(LintFinding {
146 severity: Severity::Error,
147 kind: LintKind::DuplicateToolDescription,
148 source: format!("tool:{}", t.name),
149 detail: format!("byte-identical description to tool `{prev}`"),
150 });
151 }
152 }
153 findings
154}
155
156#[must_use]
158pub fn lint_injected_context() -> Vec<LintFinding> {
159 let mut findings = lint_rules_text("rules", &crate::rules_inject::canonical_rules_block());
160 let tools = crate::core::tool_visibility::advertised_tool_defs_default();
161 findings.extend(lint_tool_descriptions(&tools));
162 findings
163}
164
165#[must_use]
167pub fn error_count(findings: &[LintFinding]) -> usize {
168 findings.iter().filter(|f| f.is_error()).count()
169}
170
171#[cfg(test)]
172mod tests {
173 use super::*;
174
175 #[test]
176 fn reteaching_phrase_is_an_error() {
177 let findings = lint_rules_text("t", "As you know, the cache stores compressed reads here.");
178 assert!(
179 findings
180 .iter()
181 .any(|f| f.kind == LintKind::ReTeaching && f.is_error())
182 );
183 }
184
185 #[test]
186 fn exact_duplicate_line_is_an_error() {
187 let text =
188 "prefer ctx_search over native grep always\nprefer ctx_search over native grep always";
189 let findings = lint_rules_text("t", text);
190 assert!(
191 findings
192 .iter()
193 .any(|f| f.kind == LintKind::DuplicateLine && f.is_error())
194 );
195 }
196
197 #[test]
198 fn terse_high_signal_text_has_no_errors() {
199 let text = "• Read/cat -> ctx_read(path, mode)\n• Grep -> ctx_search(pattern, path)";
200 assert_eq!(error_count(&lint_rules_text("t", text)), 0);
201 }
202
203 #[test]
204 fn structural_lines_are_skipped() {
205 let text = "<!-- lean-ctx-rules -->\n\n# header\n<!-- lean-ctx-rules -->\n\n# header";
207 assert_eq!(error_count(&lint_rules_text("t", text)), 0);
208 }
209
210 #[test]
214 fn live_injected_context_has_no_error_findings() {
215 let _iso = crate::core::data_dir::isolated_data_dir();
216 let findings = lint_injected_context();
217 let errors: Vec<&LintFinding> = findings.iter().filter(|f| f.is_error()).collect();
218 assert!(
219 errors.is_empty(),
220 "injected context must be high-signal, found Error findings: {errors:#?}"
221 );
222 }
223}