lean_ctx_ext/core/decisions/
check.rs1use std::path::Path;
21
22use super::{Check, CheckKind, Decision, DecisionSet};
23use crate::core::pre_edit::{PreEditFinding, PreEditInput, Severity};
24
25#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct Violation {
28 pub decision_id: String,
29 pub title: String,
30 pub statement: String,
31 pub check_index: usize,
32 pub kind: CheckKind,
33 pub path: String,
35 pub message: String,
37 pub line: Option<usize>,
39}
40
41impl Violation {
42 pub fn render(&self) -> String {
44 let at = self
45 .line
46 .map_or_else(|| self.path.clone(), |l| format!("{}:{l}", self.path));
47 format!(
48 "{} ({}) at {at} [{}]: {}",
49 self.decision_id,
50 self.title.trim(),
51 self.kind.as_str(),
52 self.message
53 )
54 }
55}
56
57pub type OtherFiles<'a> = &'a dyn Fn(&Decision, &Check, &str) -> bool;
62
63const MAX_SCAN_FILES: usize = 5_000;
65const MAX_SCAN_BYTES: u64 = 1_000_000;
66pub(crate) const MAX_WALK_ENTRIES: usize = 50_000;
69const MAX_WALK_DEPTH: usize = 32;
71
72pub fn worktree_other_files(root: &Path, d: &Decision, check: &Check, exclude: &str) -> bool {
74 worktree_other_files_bounded(root, d, check, exclude, MAX_WALK_ENTRIES)
75}
76
77pub(crate) fn worktree_other_files_bounded(
78 root: &Path,
79 d: &Decision,
80 check: &Check,
81 exclude: &str,
82 max_entries: usize,
83) -> bool {
84 let Some(re) = check.regex() else {
85 return true;
86 };
87 let mut seen = 0usize;
88 let mut visited = 0usize;
89 for entry in ignore::WalkBuilder::new(root)
90 .hidden(false)
91 .follow_links(false)
92 .max_depth(Some(MAX_WALK_DEPTH))
93 .build()
94 .flatten()
95 {
96 visited += 1;
97 if visited > max_entries {
98 return true;
99 }
100 if !entry.file_type().is_some_and(|t| t.is_file()) {
101 continue;
102 }
103 let Some(rel) = super::relative_path(root, entry.path()) else {
104 continue;
105 };
106 if rel == exclude || rel.starts_with(".git/") || !check.covers(d, &rel) {
107 continue;
108 }
109 seen += 1;
110 if seen > MAX_SCAN_FILES || entry.metadata().is_ok_and(|m| m.len() > MAX_SCAN_BYTES) {
111 return true;
112 }
113 if std::fs::read_to_string(entry.path()).is_ok_and(|t| re.is_match(&t)) {
114 return true;
115 }
116 }
117 false
118}
119
120fn line_of(text: &str, offset: usize) -> usize {
121 text[..offset.min(text.len())].matches('\n').count() + 1
122}
123
124fn first_new_match(re: ®ex::Regex, before: &str, after: &str) -> Option<usize> {
127 let mut seen: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
128 for m in re.find_iter(before) {
129 *seen.entry(m.as_str()).or_default() += 1;
130 }
131 let mut first = None;
132 for m in re.find_iter(after) {
133 first.get_or_insert(m.start());
134 match seen.get_mut(m.as_str()) {
135 Some(n) if *n > 0 => *n -= 1,
136 _ => return Some(m.start()),
137 }
138 }
139 first
140}
141
142fn violation(d: &Decision, i: usize, rel_path: &str, line: Option<usize>) -> Violation {
143 let check = &d.checks[i];
144 Violation {
145 decision_id: d.id.clone(),
146 title: d.title.clone(),
147 statement: d.one_line(),
148 check_index: i,
149 kind: check.kind,
150 path: rel_path.to_string(),
151 message: check.message.clone().unwrap_or_else(|| d.one_line()),
152 line,
153 }
154}
155
156pub fn evaluate_change(
161 set: &DecisionSet,
162 rel_path: &str,
163 before: Option<&str>,
164 after: Option<&str>,
165) -> Vec<Violation> {
166 let other = |d: &Decision, c: &Check, exclude: &str| {
167 set.root
168 .as_deref()
169 .is_none_or(|root| worktree_other_files(root, d, c, exclude))
170 };
171 evaluate_change_with(set, rel_path, before, after, &other)
172}
173
174pub fn evaluate_change_with(
176 set: &DecisionSet,
177 rel_path: &str,
178 before: Option<&str>,
179 after: Option<&str>,
180 other_files: OtherFiles<'_>,
181) -> Vec<Violation> {
182 let Some(after) = after else {
183 return Vec::new();
184 };
185 if before == Some(after) {
186 return Vec::new();
187 }
188 let mut out = Vec::new();
189 for d in set.active().filter(|d| set.repo_matches(d)) {
190 for (i, check) in d.checks.iter().enumerate() {
191 if !check.covers(d, rel_path) {
192 continue;
193 }
194 match check.kind {
195 CheckKind::ForbidPath => {
196 if before.is_none() {
197 out.push(violation(d, i, rel_path, None));
198 }
199 }
200 CheckKind::ForbidRegex => {
201 let Some(re) = check.regex() else { continue };
202 let before_count = before.map_or(0, |b| re.find_iter(b).count());
203 if re.find_iter(after).count() > before_count {
204 let line = first_new_match(re, before.unwrap_or_default(), after)
205 .map(|off| line_of(after, off));
206 out.push(violation(d, i, rel_path, line));
207 }
208 }
209 CheckKind::RequireRegex => {
210 let Some(re) = check.regex() else { continue };
211 if !re.is_match(after)
212 && before.is_some_and(|b| re.is_match(b))
213 && !other_files(d, check, rel_path)
214 {
215 out.push(violation(d, i, rel_path, None));
216 }
217 }
218 }
219 }
220 }
221 out
222}
223
224pub fn findings_for(
230 set: &DecisionSet,
231 rel_path: &str,
232 input: &PreEditInput<'_>,
233 enforce: &str,
234) -> Vec<PreEditFinding> {
235 if enforce == "off" {
236 return Vec::new();
237 }
238 let severity = if enforce == "refuse" {
239 Severity::Refuse
240 } else {
241 Severity::Hint
242 };
243 let violations = evaluate_change(set, rel_path, input.before, Some(input.after));
244 let mut out: Vec<PreEditFinding> = violations
245 .iter()
246 .map(|v| PreEditFinding {
247 source: "decision",
248 id: v.decision_id.clone(),
249 severity,
250 text: format!("{} — decision: {}", v.render(), v.statement),
251 })
252 .collect();
253 let scoped: Vec<&str> = set
254 .for_path(rel_path)
255 .into_iter()
256 .filter(|d| !d.is_repo_wide() && !violations.iter().any(|v| v.decision_id == d.id))
257 .map(|d| d.id.as_str())
258 .collect();
259 if !scoped.is_empty() {
260 out.push(PreEditFinding {
261 source: "decision",
262 id: scoped.join(","),
263 severity: Severity::Note,
264 text: format!(
265 "decisions in scope of {rel_path}: {} (ctx_knowledge action=decisions path={rel_path})",
266 scoped.join(", ")
267 ),
268 });
269 }
270 out
271}
272
273pub fn pre_edit_findings(input: &PreEditInput<'_>) -> Vec<PreEditFinding> {
278 let Some(root) = super::find_root(input.path) else {
279 return Vec::new();
280 };
281 let Some(rel) = super::relative_path(&root, input.path) else {
282 return Vec::new();
283 };
284 let set = super::load(&root);
285 if set.decisions.is_empty() {
286 return Vec::new();
287 }
288 let cfg = crate::core::config::Config::load();
289 findings_for(&set, &rel, input, cfg.decisions.enforce_mode())
290}