Skip to main content

lean_ctx_ext/core/decisions/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Decision layer (D1): versioned project decisions in `.leanctx/decisions/*.toml`.
3//!
4//! A decision record names what was decided, by whom, where it applies (repos,
5//! path globs, symbols) and, optionally, machine-checkable `[[check]]`s. This
6//! module loads and validates the records (strictly: an unknown key, a bad
7//! glob or a bad regex is an error naming the file), answers scope queries and
8//! renders the deterministic context suffix for reads (#498: no timestamps,
9//! no counters, stable header, sorted by id). [`check`] evaluates the checks
10//! against a change; [`crate::core::pre_edit`] runs them before an edit.
11//!
12//! LeanCTX only detects, reports and hints. Refusing an edit is opt-in
13//! (`[decisions] enforce = "refuse"`); enforcing a land belongs to Weave.
14
15pub mod check;
16mod parse;
17#[cfg(test)]
18mod tests;
19
20use std::collections::HashMap;
21use std::path::{Path, PathBuf};
22use std::sync::{Arc, Mutex};
23
24pub use check::{OtherFiles, Violation, evaluate_change, evaluate_change_with};
25pub use parse::{NewRecord, id_from_slug, parse_decision, render_record, scaffold};
26
27/// Directory, relative to the project root, that holds one record per file.
28pub const DECISIONS_DIR: &str = ".leanctx/decisions";
29/// Header of the read/compose suffix. Stable: prompt caches key on it.
30pub const SUFFIX_HEADER: &str = "--- Decisions in scope ---";
31/// Records beyond this many are named by count only in a suffix.
32const MAX_SUFFIX_DECISIONS: usize = 8;
33/// A suffix line longer than this is cut (on a char boundary).
34const MAX_SUFFIX_LINE_CHARS: usize = 200;
35/// Files beyond this many are reported as an error, not parsed.
36const MAX_DECISION_FILES: usize = 512;
37/// A record larger than this is an error (records are short by design).
38pub const MAX_DECISION_BYTES: u64 = 64 * 1024;
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
41pub enum Status {
42    Active,
43    Superseded,
44    Revoked,
45}
46
47impl Status {
48    pub fn as_str(self) -> &'static str {
49        match self {
50            Self::Active => "active",
51            Self::Superseded => "superseded",
52            Self::Revoked => "revoked",
53        }
54    }
55}
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum CheckKind {
59    ForbidPath,
60    ForbidRegex,
61    RequireRegex,
62}
63
64impl CheckKind {
65    pub fn as_str(self) -> &'static str {
66        match self {
67            Self::ForbidPath => "forbid_path",
68            Self::ForbidRegex => "forbid_regex",
69            Self::RequireRegex => "require_regex",
70        }
71    }
72}
73
74/// A validated `[[check]]`. `paths` empty means "the decision's scope".
75#[derive(Debug, Clone)]
76pub struct Check {
77    pub kind: CheckKind,
78    pub paths: Vec<String>,
79    globs: Vec<glob::Pattern>,
80    pub pattern: Option<String>,
81    regex: Option<regex::Regex>,
82    pub message: Option<String>,
83}
84
85/// A validated decision record.
86#[derive(Debug, Clone)]
87pub struct Decision {
88    pub id: String,
89    pub title: String,
90    pub statement: String,
91    pub rationale: String,
92    pub status: Status,
93    pub supersedes: Vec<String>,
94    pub decided_by: String,
95    pub decided_at: String,
96    pub source_kind: Option<String>,
97    pub source_ref: Option<String>,
98    pub repos: Vec<String>,
99    pub paths: Vec<String>,
100    path_globs: Vec<glob::Pattern>,
101    pub symbols: Vec<String>,
102    pub checks: Vec<Check>,
103    /// `[evidence]`: the history line the record was confirmed from (§38).
104    pub evidence: Option<RecordEvidence>,
105    /// Record file, relative to the project root (forward slashes).
106    pub file: String,
107}
108
109/// The verbatim history line behind a record (`[evidence]`, contract §38).
110/// `lean-ctx decisions suggest` re-reads it: a commit that left the history or
111/// a message that no longer holds `quote` turns the record's trust to
112/// `re-check`.
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct RecordEvidence {
115    /// Commit id (lower-case hex, 7 to 64 digits).
116    pub commit: String,
117    /// The message line, verbatim.
118    pub quote: String,
119    /// `confirmed` (explicit statement) or `reconstructed` (policy wording).
120    pub trust: String,
121}
122
123/// Every record of one project, sorted by id, plus the files that failed.
124#[derive(Debug, Clone, Default)]
125pub struct DecisionSet {
126    pub decisions: Vec<Decision>,
127    /// `<file>: <reason>`, sorted. A failing file contributes no decision.
128    pub errors: Vec<String>,
129    /// Names this checkout answers to for `scope.repos` (lower case).
130    repo_names: Vec<String>,
131    /// Working tree the records were loaded from (`require_regex` scans it).
132    root: Option<PathBuf>,
133}
134
135fn match_options() -> glob::MatchOptions {
136    glob::MatchOptions {
137        case_sensitive: true,
138        require_literal_separator: true,
139        require_literal_leading_dot: false,
140    }
141}
142
143impl Check {
144    /// Whether this check looks at `rel_path` (`paths`, else the decision's).
145    pub fn covers(&self, decision: &Decision, rel_path: &str) -> bool {
146        if self.globs.is_empty() {
147            decision.covers_path(rel_path)
148        } else {
149            let opts = match_options();
150            self.globs.iter().any(|g| g.matches_with(rel_path, opts))
151        }
152    }
153
154    pub fn regex(&self) -> Option<&regex::Regex> {
155        self.regex.as_ref()
156    }
157}
158
159impl Decision {
160    /// Repo-wide: no path and no symbol scope.
161    pub fn is_repo_wide(&self) -> bool {
162        self.paths.is_empty() && self.symbols.is_empty()
163    }
164
165    /// Whether `rel_path` (root-relative, forward slashes) is in path scope.
166    /// A symbol-only decision covers no path; a repo-wide one covers all.
167    pub fn covers_path(&self, rel_path: &str) -> bool {
168        if self.is_repo_wide() {
169            return true;
170        }
171        let opts = match_options();
172        self.path_globs
173            .iter()
174            .any(|g| g.matches_with(rel_path, opts))
175    }
176
177    /// Whether `symbol` (`name` or `path::name`) is in symbol scope.
178    pub fn covers_symbol(&self, symbol: &str) -> bool {
179        self.symbols.iter().any(|s| symbol_matches(s, symbol))
180    }
181
182    /// The first non-empty line of the statement, cut to a suffix line.
183    pub fn one_line(&self) -> String {
184        let line = self
185            .statement
186            .lines()
187            .map(str::trim)
188            .find(|l| !l.is_empty())
189            .unwrap_or_default();
190        truncate_chars(line, MAX_SUFFIX_LINE_CHARS)
191    }
192}
193
194/// `a` and `b` name the same symbol: equal, or equal last `::` segment when
195/// at least one side is a bare name.
196fn symbol_matches(a: &str, b: &str) -> bool {
197    let (a, b) = (a.trim(), b.trim());
198    if a.is_empty() || b.is_empty() {
199        return false;
200    }
201    if a == b {
202        return true;
203    }
204    let last = |s: &str| s.rsplit("::").next().unwrap_or(s).to_string();
205    (!a.contains("::") || !b.contains("::")) && last(a) == last(b)
206}
207
208fn truncate_chars(s: &str, max: usize) -> String {
209    if s.chars().count() <= max {
210        return s.to_string();
211    }
212    let cut: String = s.chars().take(max.saturating_sub(1)).collect();
213    format!("{cut}…")
214}
215
216impl DecisionSet {
217    /// Decisions in force: status `active` and not superseded by another
218    /// active decision.
219    pub fn active(&self) -> impl Iterator<Item = &Decision> {
220        let superseded: Vec<&str> = self
221            .decisions
222            .iter()
223            .filter(|d| d.status == Status::Active)
224            .flat_map(|d| d.supersedes.iter().map(String::as_str))
225            .collect();
226        self.decisions
227            .iter()
228            .filter(move |d| d.status == Status::Active && !superseded.contains(&d.id.as_str()))
229    }
230
231    /// The effective status of `d` (an active record named in another active
232    /// record's `supersedes` reads as superseded).
233    pub fn effective_status(&self, d: &Decision) -> Status {
234        if d.status == Status::Active && self.active().all(|a| a.id != d.id) {
235            Status::Superseded
236        } else {
237            d.status
238        }
239    }
240
241    pub fn get(&self, id: &str) -> Option<&Decision> {
242        self.decisions.iter().find(|d| d.id == id)
243    }
244
245    /// Whether `d.scope.repos` admits this checkout.
246    pub fn repo_matches(&self, d: &Decision) -> bool {
247        d.repos.is_empty()
248            || d.repos
249                .iter()
250                .any(|r| self.repo_names.iter().any(|n| n == &r.to_lowercase()))
251    }
252
253    /// Active decisions whose scope covers `rel_path`, sorted by id.
254    pub fn for_path(&self, rel_path: &str) -> Vec<&Decision> {
255        self.active()
256            .filter(|d| self.repo_matches(d) && d.covers_path(rel_path))
257            .collect()
258    }
259
260    /// Active decisions whose symbol scope names `symbol`, sorted by id.
261    pub fn for_symbol(&self, symbol: &str) -> Vec<&Decision> {
262        self.active()
263            .filter(|d| self.repo_matches(d) && d.covers_symbol(symbol))
264            .collect()
265    }
266
267    pub fn is_empty(&self) -> bool {
268        self.decisions.is_empty() && self.errors.is_empty()
269    }
270}
271
272// ── Loading ─────────────────────────────────────────────────────────────────
273
274type Signature = Vec<(String, u64, u128)>;
275
276static CACHE: Mutex<Option<HashMap<PathBuf, (Signature, Arc<DecisionSet>)>>> = Mutex::new(None);
277
278/// Most project roots the record cache holds; a full cache is cleared before
279/// a new root is inserted (bounded state in a long-lived server).
280pub(crate) const MAX_CACHED_ROOTS: usize = 16;
281
282/// One `*.toml` entry directly in a project's [`DECISIONS_DIR`].
283#[derive(Debug, Clone, PartialEq, Eq)]
284pub struct RecordEntry {
285    /// `<root>/.leanctx/decisions/<name>`, under the root as given.
286    pub path: PathBuf,
287    /// Root-relative path with `/` separators (`.leanctx/decisions/<name>`).
288    pub rel: String,
289    /// A regular file. A symlink (to anything) or other entry is `false` and
290    /// must not be read: [`read_record`] refuses it too.
291    pub regular: bool,
292}
293
294/// The shared record collector: the `*.toml` entries directly in
295/// `<root>/.leanctx/decisions`, sorted by name, never following a symlink.
296///
297/// `Ok(None)`: the project has no such directory. `Err`: it is not a
298/// directory, or it (or a parent) resolves outside the project, e.g. a
299/// symlinked directory. Used by the local loader ([`load`]) and by
300/// `lean-ctx cloud decisions push`, so both refuse the same entries.
301pub fn list_records(root: &Path) -> Result<Option<Vec<RecordEntry>>, String> {
302    let dir = root.join(DECISIONS_DIR);
303    let meta = match std::fs::symlink_metadata(&dir) {
304        Ok(m) => m,
305        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
306        Err(e) => return Err(format!("{DECISIONS_DIR}: {e}")),
307    };
308    if !meta.is_dir() {
309        return Err(format!(
310            "{DECISIONS_DIR} is not a directory inside the project"
311        ));
312    }
313    // The directory (and each parent) must resolve inside the project.
314    let real_root =
315        std::fs::canonicalize(root).map_err(|e| format!("project root {}: {e}", root.display()))?;
316    let real = std::fs::canonicalize(&dir).map_err(|e| format!("{DECISIONS_DIR}: {e}"))?;
317    // Joined per component: a verbatim Windows path (`\\?\`) takes no `/`.
318    let expected = DECISIONS_DIR
319        .split('/')
320        .fold(real_root, |p, part| p.join(part));
321    if real != expected {
322        return Err(format!("{DECISIONS_DIR} leads outside the project"));
323    }
324    let mut entries: Vec<RecordEntry> = std::fs::read_dir(&dir)
325        .map_err(|e| format!("{DECISIONS_DIR}: {e}"))?
326        .filter_map(Result::ok)
327        .filter(|e| {
328            Path::new(&e.file_name())
329                .extension()
330                .is_some_and(|x| x == "toml")
331        })
332        .map(|e| {
333            let name = e.file_name().to_string_lossy().into_owned();
334            // `DirEntry::file_type` does not follow symlinks.
335            let regular = e.file_type().is_ok_and(|t| t.is_file());
336            RecordEntry {
337                path: dir.join(e.file_name()),
338                rel: format!("{DECISIONS_DIR}/{name}"),
339                regular,
340            }
341        })
342        .collect();
343    entries.sort_by(|a, b| a.path.cmp(&b.path));
344    Ok(Some(entries))
345}
346
347/// Read one record: opened once without following a symlink, checked on
348/// that handle and read with a bound ([`MAX_DECISION_BYTES`]), so a file
349/// swapped or grown after the directory scan cannot get through.
350pub fn read_record(file: &Path) -> Result<String, &'static str> {
351    use std::io::Read;
352    let mut options = std::fs::OpenOptions::new();
353    options.read(true);
354    #[cfg(unix)]
355    {
356        use std::os::unix::fs::OpenOptionsExt;
357        options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC);
358    }
359    #[cfg(not(unix))]
360    {
361        if std::fs::symlink_metadata(file).is_ok_and(|m| !m.file_type().is_file()) {
362            return Err("not a regular file");
363        }
364    }
365    let handle = options.open(file).map_err(|e| {
366        #[cfg(unix)]
367        {
368            if e.raw_os_error() == Some(libc::ELOOP) {
369                return "not a regular file";
370            }
371        }
372        let _ = e;
373        "unreadable"
374    })?;
375    let meta = handle.metadata().map_err(|_| "unreadable")?;
376    if !meta.is_file() {
377        return Err("not a regular file");
378    }
379    if meta.len() > MAX_DECISION_BYTES {
380        return Err("larger than 64 KiB");
381    }
382    let mut bytes = Vec::new();
383    handle
384        .take(MAX_DECISION_BYTES + 1)
385        .read_to_end(&mut bytes)
386        .map_err(|_| "unreadable")?;
387    if bytes.len() as u64 > MAX_DECISION_BYTES {
388        return Err("larger than 64 KiB");
389    }
390    String::from_utf8(bytes).map_err(|_| "not UTF-8 text")
391}
392
393fn signature(entries: &[RecordEntry]) -> Signature {
394    entries
395        .iter()
396        .map(|e| {
397            let p = &e.path;
398            let meta = std::fs::symlink_metadata(p).ok();
399            let len = meta.as_ref().map_or(0, std::fs::Metadata::len);
400            let mtime = meta
401                .and_then(|m| m.modified().ok())
402                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
403                .map_or(0, |d| d.as_nanos());
404            (p.to_string_lossy().into_owned(), len, mtime)
405        })
406        .collect()
407}
408
409/// Load (cached by file list, sizes and mtimes) the records under `root`.
410/// A project without `.leanctx/decisions` yields an empty set.
411/// A record directory that resolves outside the project, or entries that
412/// are not regular files, are reported as errors and never read.
413pub fn load(root: &Path) -> Arc<DecisionSet> {
414    let files = match list_records(root) {
415        Ok(Some(entries)) if !entries.is_empty() => entries,
416        Ok(_) => return Arc::new(DecisionSet::default()),
417        Err(e) => {
418            return Arc::new(from_records(
419                root,
420                vec![(DECISIONS_DIR.to_string(), Err(e))],
421            ));
422        }
423    };
424    let sig = signature(&files);
425    {
426        let guard = CACHE
427            .lock()
428            .unwrap_or_else(std::sync::PoisonError::into_inner);
429        if let Some((cached_sig, set)) = guard.as_ref().and_then(|c| c.get(root))
430            && *cached_sig == sig
431        {
432            return Arc::clone(set);
433        }
434    }
435    let set = Arc::new(load_uncached(root, &files));
436    let mut guard = CACHE
437        .lock()
438        .unwrap_or_else(std::sync::PoisonError::into_inner);
439    let cache = guard.get_or_insert_with(HashMap::new);
440    if !cache.contains_key(root) && cache.len() >= MAX_CACHED_ROOTS {
441        cache.clear();
442    }
443    cache.insert(root.to_path_buf(), (sig, Arc::clone(&set)));
444    set
445}
446
447#[cfg(test)]
448pub(crate) fn cached_roots() -> usize {
449    CACHE
450        .lock()
451        .unwrap_or_else(std::sync::PoisonError::into_inner)
452        .as_ref()
453        .map_or(0, HashMap::len)
454}
455
456fn load_uncached(root: &Path, files: &[RecordEntry]) -> DecisionSet {
457    let records: Vec<(String, Result<String, String>)> = files
458        .iter()
459        .take(MAX_DECISION_FILES + 1)
460        .map(|entry| {
461            let text = if entry.regular {
462                read_record(&entry.path).map_err(str::to_string)
463            } else {
464                Err("not a regular file (symlinks are not followed)".to_string())
465            };
466            (entry.rel.clone(), text)
467        })
468        .collect();
469    let mut set = from_records(root, records);
470    set.root = Some(root.to_path_buf());
471    set
472}
473
474/// A set from record texts (`(root-relative file, text or read error)`),
475/// e.g. read from a base commit. `repo_root` answers `scope.repos`. The set
476/// knows no working tree, so `require_regex` needs an explicit
477/// [`check::OtherFiles`] ([`evaluate_change_with`]).
478pub fn from_records(
479    repo_root: &Path,
480    records: Vec<(String, Result<String, String>)>,
481) -> DecisionSet {
482    let mut set = DecisionSet {
483        repo_names: repo_names(repo_root),
484        ..DecisionSet::default()
485    };
486    if records.len() > MAX_DECISION_FILES {
487        set.errors.push(format!(
488            "{DECISIONS_DIR}: more than the limit of {MAX_DECISION_FILES} record files; none loaded"
489        ));
490        return set;
491    }
492    for (rel, text) in records {
493        let stem = Path::new(&rel)
494            .file_stem()
495            .map(|s| s.to_string_lossy().into_owned())
496            .unwrap_or_default();
497        let text = match text {
498            Ok(t) if t.len() as u64 > MAX_DECISION_BYTES => {
499                set.errors.push(format!(
500                    "{rel}: {} bytes, more than the limit of {MAX_DECISION_BYTES}",
501                    t.len()
502                ));
503                continue;
504            }
505            Ok(t) => t,
506            Err(e) => {
507                set.errors.push(format!("{rel}: {e}"));
508                continue;
509            }
510        };
511        match parse_decision(&text, &stem, &rel) {
512            Ok(d) if set.decisions.iter().any(|o| o.id == d.id) => {
513                set.errors.push(format!("{rel}: duplicate id `{}`", d.id));
514            }
515            Ok(d) => set.decisions.push(d),
516            Err(e) => set.errors.push(format!("{rel}: {e}")),
517        }
518    }
519    set.decisions.sort_by(|a, b| a.id.cmp(&b.id));
520    set.errors.sort();
521    set
522}
523
524/// Names this checkout answers to: the root directory name and the `origin`
525/// remote's repository name (read from git config; no subprocess).
526fn repo_names(root: &Path) -> Vec<String> {
527    let mut names = Vec::new();
528    if let Some(name) = root.file_name() {
529        names.push(name.to_string_lossy().to_lowercase());
530    }
531    if let Some(url) = origin_url(root) {
532        let base = url
533            .trim_end_matches('/')
534            .rsplit(['/', ':'])
535            .next()
536            .unwrap_or_default()
537            .trim_end_matches(".git")
538            .to_lowercase();
539        if !base.is_empty() && !names.contains(&base) {
540            names.push(base);
541        }
542    }
543    names
544}
545
546fn git_common_dir(root: &Path) -> Option<PathBuf> {
547    let dot_git = root.join(".git");
548    if dot_git.is_dir() {
549        return Some(dot_git);
550    }
551    let text = std::fs::read_to_string(&dot_git).ok()?;
552    let gitdir = PathBuf::from(text.trim().strip_prefix("gitdir:")?.trim());
553    let gitdir = if gitdir.is_absolute() {
554        gitdir
555    } else {
556        root.join(gitdir)
557    };
558    match std::fs::read_to_string(gitdir.join("commondir")) {
559        Ok(common) => {
560            let common = PathBuf::from(common.trim());
561            Some(if common.is_absolute() {
562                common
563            } else {
564                gitdir.join(common)
565            })
566        }
567        Err(_) => Some(gitdir),
568    }
569}
570
571fn origin_url(root: &Path) -> Option<String> {
572    let config = std::fs::read_to_string(git_common_dir(root)?.join("config")).ok()?;
573    let mut in_origin = false;
574    for line in config.lines() {
575        let line = line.trim();
576        if line.starts_with('[') {
577            in_origin = line == "[remote \"origin\"]";
578        } else if in_origin
579            && let Some((key, value)) = line.split_once('=')
580            && key.trim() == "url"
581        {
582            return Some(value.trim().to_string());
583        }
584    }
585    None
586}
587
588/// The nearest ancestor of `path` (itself included when a directory) that
589/// holds a `.leanctx/decisions` directory, stopping at the first git root.
590pub fn find_root(path: &Path) -> Option<PathBuf> {
591    let start = if path.is_dir() { path } else { path.parent()? };
592    for dir in start.ancestors() {
593        if dir.join(DECISIONS_DIR).is_dir() {
594            return Some(dir.to_path_buf());
595        }
596        if dir.join(".git").exists() {
597            return None;
598        }
599    }
600    None
601}
602
603/// `path` relative to `root` with forward slashes; `None` outside `root`.
604pub fn relative_path(root: &Path, path: &Path) -> Option<String> {
605    let abs = if path.is_absolute() {
606        path.to_path_buf()
607    } else {
608        root.join(path)
609    };
610    let rel: PathBuf = if let Ok(rel) = abs.strip_prefix(root) {
611        rel.to_path_buf()
612    } else {
613        // Tolerate a symlinked root (e.g. /tmp vs /private/tmp on macOS).
614        // A file that does not exist yet canonicalizes through its parent.
615        let canon_root = root.canonicalize().ok()?;
616        let canon = abs.canonicalize().ok().or_else(|| {
617            let parent = abs.parent()?.canonicalize().ok()?;
618            Some(parent.join(abs.file_name()?))
619        })?;
620        canon.strip_prefix(&canon_root).ok()?.to_path_buf()
621    };
622    let s = rel.to_string_lossy().replace('\\', "/");
623    (!s.is_empty()).then_some(s)
624}
625
626// ── Rendering ───────────────────────────────────────────────────────────────
627
628/// One line per decision: `id: title — statement`.
629pub fn render_lines(decisions: &[&Decision]) -> String {
630    let mut out = String::new();
631    for d in decisions.iter().take(MAX_SUFFIX_DECISIONS) {
632        let line = format!("{}: {} — {}", d.id, d.title.trim(), d.one_line());
633        out.push_str(&truncate_chars(&line, MAX_SUFFIX_LINE_CHARS * 2));
634        out.push('\n');
635    }
636    if decisions.len() > MAX_SUFFIX_DECISIONS {
637        out.push_str(&format!(
638            "(+{} more: lean-ctx decisions list)\n",
639            decisions.len() - MAX_SUFFIX_DECISIONS
640        ));
641    }
642    out
643}
644
645/// Deterministic suffix for a read of `rel_paths` (deduplicated, sorted):
646/// empty when no active decision covers any of them.
647pub fn suffix_for_paths(set: &DecisionSet, rel_paths: &[&str]) -> String {
648    let mut hits: Vec<&Decision> = Vec::new();
649    for p in rel_paths {
650        for d in set.for_path(p) {
651            if !hits.iter().any(|h| h.id == d.id) {
652                hits.push(d);
653            }
654        }
655    }
656    if hits.is_empty() {
657        return String::new();
658    }
659    hits.sort_by(|a, b| a.id.cmp(&b.id));
660    format!("\n\n{SUFFIX_HEADER}\n{}", render_lines(&hits))
661        .trim_end()
662        .to_string()
663}
664
665/// The suffix for a read of `file` (absolute or root-relative). Empty when the
666/// file is outside every project with decisions.
667pub fn suffix_for_file(file: &Path) -> String {
668    let Some(root) = find_root(file) else {
669        return String::new();
670    };
671    let Some(rel) = relative_path(&root, file) else {
672        return String::new();
673    };
674    suffix_for_paths(&load(&root), &[rel.as_str()])
675}
676
677/// The read suffix for a tool reply (`ctx_read`, `ctx_compose`): empty while
678/// a gateway policy is active, since decision records are repository text
679/// that the policy did not admit as a source of this reply.
680pub fn suffix_for_read(file: &str) -> String {
681    if crate::core::policy::runtime::is_active() {
682        return String::new();
683    }
684    suffix_for_file(Path::new(file))
685}
686
687/// The suffix for paths a compose answer named, relative to `root`.
688pub fn suffix_for_root_paths(root: &Path, rel_paths: &[&str]) -> String {
689    if !root.join(DECISIONS_DIR).is_dir() || rel_paths.is_empty() {
690        return String::new();
691    }
692    suffix_for_paths(&load(root), rel_paths)
693}
694
695/// Most distinct files a compose answer contributes to its suffix.
696const MAX_COMPOSE_PATHS: usize = 64;
697
698/// The suffix for a `ctx_compose` answer: decisions covering the files it
699/// names (`path:line …` and `File: path` lines that exist under `root`).
700pub fn suffix_for_compose(root: &Path, text: &str) -> String {
701    if crate::core::policy::runtime::is_active() || !root.join(DECISIONS_DIR).is_dir() {
702        return String::new();
703    }
704    let paths = paths_named_in(root, text);
705    suffix_for_root_paths(root, &paths)
706}
707
708/// The existing files under `root` a compose answer names, in order and
709/// deduplicated: `File: path` headers and `path:line` hits (at most 64).
710pub fn paths_named_in<'a>(root: &Path, text: &'a str) -> Vec<&'a str> {
711    let mut paths: Vec<&str> = Vec::new();
712    for line in text.lines() {
713        let line = line.trim_start();
714        let candidate = match line.strip_prefix("File: ") {
715            Some(rest) => rest.split([' ', '(']).next().unwrap_or_default(),
716            None => match line.split_once(':') {
717                Some((p, rest)) if rest.starts_with(|c: char| c.is_ascii_digit()) => p,
718                _ => continue,
719            },
720        };
721        if candidate.is_empty()
722            || candidate.contains(char::is_whitespace)
723            || paths.contains(&candidate)
724            || !root.join(candidate).is_file()
725        {
726            continue;
727        }
728        paths.push(candidate);
729        if paths.len() >= MAX_COMPOSE_PATHS {
730            break;
731        }
732    }
733    paths
734}
735
736/// Full, multi-line description of one decision (CLI `show`, `ctx_knowledge`).
737pub fn describe(set: &DecisionSet, d: &Decision) -> String {
738    let mut out = format!(
739        "{} [{}] {}\n  statement: {}\n",
740        d.id,
741        set.effective_status(d).as_str(),
742        d.title.trim(),
743        d.statement.trim()
744    );
745    if !d.rationale.trim().is_empty() {
746        out.push_str(&format!("  rationale: {}\n", d.rationale.trim()));
747    }
748    out.push_str(&format!(
749        "  decided: {} by {}\n",
750        d.decided_at, d.decided_by
751    ));
752    if let (Some(kind), Some(r)) = (&d.source_kind, &d.source_ref) {
753        out.push_str(&format!("  source: {kind} {r}\n"));
754    }
755    if let Some(ev) = &d.evidence {
756        out.push_str(&format!(
757            "  evidence ({}): {} \"{}\"\n",
758            ev.trust,
759            &ev.commit[..ev.commit.len().min(12)],
760            ev.quote
761        ));
762    }
763    if !d.supersedes.is_empty() {
764        out.push_str(&format!("  supersedes: {}\n", d.supersedes.join(", ")));
765    }
766    let scope = |v: &[String]| {
767        if v.is_empty() {
768            "*".to_string()
769        } else {
770            v.join(", ")
771        }
772    };
773    out.push_str(&format!(
774        "  scope: repos={} paths={} symbols={}\n",
775        scope(&d.repos),
776        scope(&d.paths),
777        if d.symbols.is_empty() {
778            "-".to_string()
779        } else {
780            d.symbols.join(", ")
781        }
782    ));
783    for (i, c) in d.checks.iter().enumerate() {
784        out.push_str(&format!(
785            "  check[{i}]: {} paths={}{}\n",
786            c.kind.as_str(),
787            scope(&c.paths),
788            c.pattern
789                .as_deref()
790                .map(|p| format!(" pattern={p}"))
791                .unwrap_or_default()
792        ));
793    }
794    out.push_str(&format!("  file: {}\n", d.file));
795    // Records may quote git history: no escape sequence reaches a terminal.
796    out.split('\n')
797        .map(terminal_safe)
798        .collect::<Vec<_>>()
799        .join("\n")
800}
801
802/// Text for a terminal: control characters (C0, DEL, C1, so no escape
803/// sequences, also newlines) and bidi controls become `?`.
804pub fn terminal_safe(s: &str) -> String {
805    s.chars()
806        .map(|c| {
807            if c.is_control()
808                || matches!(
809                    c,
810                    '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}'
811                )
812            {
813                '?'
814            } else {
815                c
816            }
817        })
818        .collect()
819}
820
821/// The decision query of `ctx_knowledge action=decisions` and `lean-ctx
822/// decisions list`: by `path` (decisions whose scope covers it), else by
823/// `symbol`, else all records; invalid records are listed after them.
824pub fn query_text(project_root: &Path, path: Option<&str>, symbol: Option<&str>) -> String {
825    let root = find_root(project_root).unwrap_or_else(|| project_root.to_path_buf());
826    let set = load(&root);
827    if set.is_empty() {
828        return format!(
829            "No decisions in this project ({DECISIONS_DIR}/*.toml). Create one: lean-ctx decisions new <slug>"
830        );
831    }
832    let (label, hits): (String, Vec<&Decision>) = match (path, symbol) {
833        (Some(p), _) => {
834            let rel = relative_path(&root, Path::new(p))
835                .unwrap_or_else(|| p.trim_start_matches("./").to_string());
836            let hits = set.for_path(&rel);
837            (format!("in scope of {rel}"), hits)
838        }
839        (None, Some(s)) => (format!("naming symbol {s}"), set.for_symbol(s)),
840        (None, None) => ("all".to_string(), set.decisions.iter().collect()),
841    };
842    let mut out = format!("Decisions {label}: {}\n", hits.len());
843    for d in hits {
844        out.push_str(&describe(&set, d));
845    }
846    if !set.errors.is_empty() {
847        out.push_str("Invalid records (not applied):\n");
848        for e in &set.errors {
849            // Parse errors may quote record files: no terminal escapes.
850            out.push_str(&format!("  {}\n", terminal_safe(e)));
851        }
852    }
853    out.trim_end().to_string()
854}