Skip to main content

lean_ctx_ext/core/
context_lint.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Injected-context linter (#960) — keeps lean-ctx's OWN injected context
3//! (the rules block + advertised tool descriptions) high-signal.
4//!
5//! The Nisi/WorkOS "Case" talk is the motivation: comprehensive prose and
6//! re-teaching what a competent model already knows *degrades* reasoning and
7//! burns a finite attention budget; only the non-obvious gotcha earns its
8//! tokens. This linter encodes that discipline so it can be enforced in CI and
9//! surfaced in `doctor`.
10//!
11//! Two severities:
12//! * [`Severity::Error`] — exact-duplicate rule lines and low-signal re-teaching
13//!   phrases in the rules block. These ride *every* turn, are fully under our
14//!   control, and must fail the gate.
15//! * [`Severity::Warn`] — verbose or duplicated tool descriptions. Surfaced for
16//!   triage so the ~28-tool surface can be trimmed incrementally without
17//!   blocking unrelated work.
18
19use crate::core::tokens::count_tokens;
20
21/// Low-signal phrases that re-teach what a competent model already knows: they add
22/// per-turn tokens without changing behaviour, so they must never ride the rules
23/// block. Matched case-insensitively as substrings.
24const 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
35/// A tool description longer than this is comprehensive prose, not a gotcha (Warn).
36const TOOL_DESC_TOKEN_BUDGET: usize = 80;
37
38/// Lines shorter than this are treated as structural (headers, short labels) and
39/// skipped by duplicate detection.
40const MIN_SIGNIFICANT_LINE_CHARS: usize = 24;
41
42/// Whether a finding gates CI or is merely surfaced.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum Severity {
45    /// Fails the CI gate.
46    Error,
47    /// Surfaced for triage, does not gate.
48    Warn,
49}
50
51/// The category of a lint finding.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum LintKind {
54    /// Two identical content lines in the rules block.
55    DuplicateLine,
56    /// A low-signal re-teaching phrase in the rules block.
57    ReTeaching,
58    /// Two tools advertise byte-identical descriptions.
59    DuplicateToolDescription,
60    /// A tool description exceeds the gotcha budget.
61    VerboseToolDescription,
62}
63
64/// One linter finding against the injected context.
65#[derive(Debug, Clone)]
66pub struct LintFinding {
67    pub severity: Severity,
68    pub kind: LintKind,
69    /// Where it was found (`"rules"` or `"tool:<name>"`).
70    pub source: String,
71    pub detail: String,
72}
73
74impl LintFinding {
75    /// Whether this finding gates CI.
76    #[must_use]
77    pub(crate) fn is_error(&self) -> bool {
78        self.severity == Severity::Error
79    }
80}
81
82/// A content line worth linting (skips blanks, HTML markers and `#` headers).
83fn is_content_line(line: &str) -> bool {
84    let t = line.trim();
85    !t.is_empty() && !t.starts_with("<!--") && !t.starts_with('#')
86}
87
88/// Lints a rules-block text for re-teaching phrases (Error) and exact-duplicate
89/// content lines (Error).
90#[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/// Lints advertised tool descriptions for byte-identical copies (Error) and
123/// gotcha-budget overruns (Warn).
124#[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/// Lints the live injected context this install would emit (rules + tool schemas).
157#[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/// Number of gating (Error) findings.
166#[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        // Markers, blanks and headers must not be flagged even if repeated.
206        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    /// The enforced gate: the live injected rules surface must carry zero Error
211    /// findings, proving the trim landed and guarding against future re-teaching
212    /// or duplication regressions (#960).
213    #[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}