Skip to main content

lean_ctx_ext/core/decisions/
check.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Evaluate decision `[[check]]`s against one file change.
3//!
4//! The check kinds are tree rules (docs/internal/decision-layer.md):
5//! `forbid_path`: no file may match `paths`; `forbid_regex`: no file matching
6//! `paths` may contain `pattern`; `require_regex`: at least one file matching
7//! `paths` must contain `pattern`. Weave (D4) judges a whole candidate tree.
8//! Here a check judges one file change and reports only what the change
9//! *introduces*:
10//!
11//! - `forbid_path`: the change creates a file under `paths`.
12//! - `forbid_regex`: the file holds more matches after than before.
13//! - `require_regex`: the file held a match, holds none after, and no other
14//!   file under `paths` holds one ([`OtherFiles`]).
15//!
16//! A violation already in the tree is not this change's, so the pre-edit hint
17//! and `lean-ctx decisions check` stay quiet on legacy code and the strict
18//! mode refuses only edits that make things worse.
19
20use std::path::Path;
21
22use super::{Check, CheckKind, Decision, DecisionSet};
23use crate::core::pre_edit::{PreEditFinding, PreEditInput, Severity};
24
25/// One violated check.
26#[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    /// Root-relative path of the changed file.
34    pub path: String,
35    /// The check's message, else the decision's one-line statement.
36    pub message: String,
37    /// 1-based line of the offending text in the post-change content, when known.
38    pub line: Option<usize>,
39}
40
41impl Violation {
42    /// `dec-x (Title) at path:12 [forbid_regex]: message`
43    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
57/// Whether a file other than the changed one (the `&str`, root-relative)
58/// that the check covers contains its pattern: the `require_regex` "at least
59/// one file" rule. Answer `true` when that cannot be told cheaply; a missed
60/// hint is better than a false one.
61pub type OtherFiles<'a> = &'a dyn Fn(&Decision, &Check, &str) -> bool;
62
63/// Most files a working-tree scan reads before it gives up (answering `true`).
64const MAX_SCAN_FILES: usize = 5_000;
65const MAX_SCAN_BYTES: u64 = 1_000_000;
66/// Most walk entries (files and directories, covered or not) a working-tree
67/// scan visits before it gives up (answering `true`).
68pub(crate) const MAX_WALK_ENTRIES: usize = 50_000;
69/// Deepest directory level the working-tree scan descends to.
70const MAX_WALK_DEPTH: usize = 32;
71
72/// [`OtherFiles`] over the working tree at `root` (gitignore respected).
73pub 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
124/// The first match in `after` whose text is not among `before`'s matches
125/// (by occurrence count), or the first match when that cannot be told apart.
126fn first_new_match(re: &regex::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
156/// Violations a change of `rel_path` from `before` to `after` introduces,
157/// over every active decision in `set`. `before = None`: the file is new;
158/// `after = None`: the file is deleted (a deletion violates nothing).
159/// `require_regex` looks for other files in the set's working tree.
160pub 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
174/// [`evaluate_change`] with an explicit [`OtherFiles`] (e.g. over a git tree).
175pub 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
224/// Findings for one pre-edit check of `set` under `enforce` (`hint` |
225/// `refuse` | `off`). Introduced violations become hints (refusals when
226/// strict). Path- or symbol-scoped decisions covering the file without a
227/// violation become one [`Severity::Note`] (shown by LeanCTX's edit tools,
228/// not by native hooks); repo-wide ones are left to the read suffix.
229pub 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
273/// The decisions checker registered in [`crate::core::pre_edit`]: finds the
274/// project by its `.leanctx/decisions` directory and reads `[decisions]
275/// enforce` from the config. Cheap (one directory probe per ancestor) when a
276/// project has no decisions.
277pub 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}