1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
// 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()
}