lean-ctx-engine-ext 3.12.13

LeanCTX | Engine extensions: the engine modules above the core (setup, reports, graph analysis, knowledge routing, sandboxing).
Documentation
// SPDX-License-Identifier: Apache-2.0
//! Lazily loaded Claude Code instructions for `ctx_read`.
//!
//! Claude Code loads the CLAUDE.md files at and above its working directory
//! and the `.claude/rules` files without `paths` at launch. Two kinds load
//! only when its native Read, Write or Edit touches a file:
//!
//! - `CLAUDE.md`, `.claude/CLAUDE.md` and `CLAUDE.local.md` in a
//!   subdirectory below the working directory (and that subdirectory's
//!   `AGENTS.md` when the project runs on `AGENTS.md` instead of CLAUDE.md);
//! - `.claude/rules/**/*.md` with a `paths` field matching the file, and the
//!   rules of nested `.claude/rules` directories below the project root.
//!
//! In replace mode the native Read is denied, so Claude Code never loads
//! them. This module returns exactly that lazily loaded part, in Claude
//! Code's order (outer directories first, `CLAUDE.local.md` last per
//! directory, rule files sorted by path), and never the launch-time part.
//! Directories named `.claude` (and anything inside one) are never nested
//! instruction directories: `<root>/.claude/CLAUDE.md` is launch-time.
//!
//! Paths may use `/` on every platform. On Windows `canonicalize` returns
//! verbatim (`\\?\`) paths, where `/` is not a separator, so both inputs are
//! read with `/` as a separator and every join goes by component. `source`
//! labels always use `/`, so they are the same on every platform.
//!
//! A symlinked rule file is followed like Claude Code follows it; what
//! reaches the reply still goes through the admitted rooted reader, so a
//! target outside the project contributes nothing.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Mutex;

use super::DiscoveredRule;

/// How far below a `.claude/rules` directory rule files are collected.
const MAX_RULE_DEPTH: usize = 8;

/// Which files a candidate applies to.
#[derive(Debug, Clone)]
enum Scope {
    /// Applies to every file at or below the directory it was found in.
    Subtree,
    /// Applies to files whose path below `base` matches one of `patterns`.
    Paths {
        base: PathBuf,
        patterns: Vec<String>,
    },
}

#[derive(Debug, Clone)]
struct Candidate {
    rule: DiscoveredRule,
    scope: Scope,
}

/// Keyed by (project root, directory): `source` labels are root-relative.
static DIR_CACHE: Mutex<Option<HashMap<(PathBuf, PathBuf), Vec<Candidate>>>> = Mutex::new(None);

#[cfg(test)]
pub(super) fn reset_cache() {
    *DIR_CACHE
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner) = None;
}

/// The lazily loaded instructions that apply to `file_path`.
pub(super) fn discover(file_path: &str, project_root: &str) -> Vec<DiscoveredRule> {
    let root = native(project_root);
    let file = native(file_path);
    let (root, file) = (root.as_path(), file.as_path());
    let Ok(relative) = file.strip_prefix(root) else {
        return Vec::new();
    };
    // Files of agent worktrees follow their own worktree's instructions.
    if relative.starts_with(Path::new(".claude").join("worktrees")) {
        return Vec::new();
    }
    let dir = file.parent().unwrap_or(root).to_path_buf();
    let key = (root.to_path_buf(), dir.clone());
    let candidates = {
        let cached = DIR_CACHE
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .as_ref()
            .and_then(|cache| cache.get(&key).cloned());
        cached.unwrap_or_else(|| {
            let candidates = collect(&dir, root);
            DIR_CACHE
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .get_or_insert_with(HashMap::new)
                .insert(key, candidates.clone());
            candidates
        })
    };
    candidates
        .into_iter()
        .filter(|candidate| match &candidate.scope {
            Scope::Subtree => true,
            Scope::Paths { base, patterns } => file
                .strip_prefix(base)
                .is_ok_and(|below| paths_match(patterns, base, below)),
        })
        .map(|candidate| candidate.rule)
        .collect()
}

/// `path` with every `/` read as a separator. Windows accepts `/` in an
/// ordinary path but not in a verbatim one, and `/` is never part of a
/// Windows file name.
fn native(path: &str) -> PathBuf {
    if cfg!(windows) {
        PathBuf::from(path.replace('/', "\\"))
    } else {
        PathBuf::from(path)
    }
}

/// `directory` joined with the `/`-separated `relative`, one component at a time.
fn join(directory: &Path, relative: &str) -> PathBuf {
    relative
        .split('/')
        .fold(directory.to_path_buf(), |path, part| path.join(part))
}

/// The root-relative label of `path`, `/`-separated on every platform.
fn label(relative: &Path) -> String {
    relative
        .components()
        .map(|part| part.as_os_str().to_string_lossy())
        .collect::<Vec<_>>()
        .join("/")
}

/// All candidates for files directly in `dir`, outer directories first.
fn collect(dir: &Path, root: &Path) -> Vec<Candidate> {
    let mut chain: Vec<&Path> = dir
        .ancestors()
        .take_while(|ancestor| ancestor.starts_with(root))
        .collect();
    chain.reverse();
    let agents_mode = project_uses_agents_md(root);

    let mut candidates = Vec::new();
    for directory in chain {
        let nested = directory != root;
        // `<root>/.claude` and everything inside it hold the root's own
        // configuration, never a nested instruction directory.
        if nested
            && directory
                .strip_prefix(root)
                .is_ok_and(|below| below.components().any(|c| c.as_os_str() == ".claude"))
        {
            continue;
        }
        if nested {
            collect_instruction_files(directory, root, agents_mode, &mut candidates);
        }
        collect_rule_files(directory, root, nested, &mut candidates);
    }
    candidates
}

/// Claude Code reads `AGENTS.md` only when no CLAUDE.md file exists at or
/// above its working directory (`~/.claude/CLAUDE.md` does not count).
fn project_uses_agents_md(root: &Path) -> bool {
    !join(root, ".claude/CLAUDE.md").is_file()
        && !root
            .ancestors()
            .any(|dir| dir.join("CLAUDE.md").is_file() || dir.join("CLAUDE.local.md").is_file())
}

fn collect_instruction_files(
    directory: &Path,
    root: &Path,
    agents_mode: bool,
    candidates: &mut Vec<Candidate>,
) {
    let claude_files = ["CLAUDE.md", ".claude/CLAUDE.md", "CLAUDE.local.md"];
    let has_claude_file = claude_files
        .iter()
        .any(|name| join(directory, name).is_file());
    let names: &[&str] = if has_claude_file {
        &claude_files
    } else if agents_mode {
        &["AGENTS.md", ".claude/AGENTS.md"]
    } else {
        &[]
    };
    for name in names {
        if let Some(rule) = read_rule(&join(directory, name), root) {
            candidates.push(Candidate {
                rule,
                scope: Scope::Subtree,
            });
        }
    }
}

/// `.claude/rules` of `directory`. At the project root only path-scoped
/// rules are lazy; in a nested directory unscoped rules are lazy too.
fn collect_rule_files(
    directory: &Path,
    root: &Path,
    nested: bool,
    candidates: &mut Vec<Candidate>,
) {
    let rules_dir = join(directory, ".claude/rules");
    if !rules_dir.is_dir() {
        return;
    }
    let mut files = Vec::new();
    markdown_files(&rules_dir, 0, &mut files);
    files.sort();
    for path in files {
        let Some(rule) = read_rule(&path, root) else {
            continue;
        };
        let patterns = super::frontmatter_patterns(&rule.content, &["paths"]);
        let scope = if !patterns.is_empty() {
            Scope::Paths {
                base: directory.to_path_buf(),
                patterns,
            }
        } else if nested {
            Scope::Subtree
        } else {
            continue;
        };
        candidates.push(Candidate { rule, scope });
    }
}

fn markdown_files(dir: &Path, depth: usize, files: &mut Vec<PathBuf>) {
    if depth > MAX_RULE_DEPTH {
        return;
    }
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let Ok(kind) = entry.file_type() else {
            continue;
        };
        let path = entry.path();
        if kind.is_dir() {
            markdown_files(&path, depth + 1, files);
        } else if path.extension().is_some_and(|ext| ext == "md") {
            files.push(path);
        }
    }
}

fn read_rule(path: &Path, root: &Path) -> Option<DiscoveredRule> {
    if !path.is_file() {
        return None;
    }
    let content = std::fs::read_to_string(path).ok()?;
    if content.trim().is_empty() {
        return None;
    }
    let source = label(path.strip_prefix(root).ok()?);
    Some(DiscoveredRule { source, content })
}

/// Claude Code's `paths` semantics: a pattern without `/` matches a file
/// name at any depth, a pattern with `/` is anchored at the rule's base
/// directory and `*` does not cross `/`; `**` and `{a,b}` are supported.
/// An invalid pattern matches nothing and leaves the others working.
/// A bare directory pattern such as `src` covers that whole subtree
/// (gitignore semantics, checked against the file and its parents).
fn paths_match(patterns: &[String], base: &Path, below: &Path) -> bool {
    let mut builder = ignore::gitignore::GitignoreBuilder::new(base);
    for pattern in patterns {
        // `!` would negate in gitignore syntax; Claude Code has no negation.
        if pattern.starts_with('!') {
            continue;
        }
        let _ = builder.add_line(None, pattern);
    }
    let Ok(matcher) = builder.build() else {
        return false;
    };
    matcher
        .matched_path_or_any_parents(base.join(below), false)
        .is_ignore()
}