返回 CodeWhale
project_context.rs
根目录 / crates / engine / src / project_context.rs
1 //! Project context loading for Codewhale.
2 //!
3 //! This module handles loading project-specific context files that provide
4 //! instructions and context to the AI agent. These include:
5 //!
6 //! - `AGENTS.md` - Cross-agent project instructions (canonical, highest priority)
7 //! - `.claude/instructions.md` - Claude-style hidden instructions (compat)
8 //! - `CLAUDE.md` - Claude-style instructions (compat)
9 //! - `.codewhale/instructions.md` - Hidden instructions file (compat)
10 //! - `.deepseek/instructions.md` - Hidden instructions file (legacy)
11 //!
12 //! Codewhale-specific repo authority/prioritization policy lives separately in
13 //! `.codewhale/constitution.json` and is rendered as its own higher-authority
14 //! block. The loaded content is injected into the system prompt to give the
15 //! agent context about the project's conventions, structure, and requirements.
16
17 mod budget;
18 mod constitution;
19 #[cfg(test)]
20 mod instruction_budget_tests;
21 mod pack;
22 mod types;
23
24 use std::fs;
25 use std::io::Read;
26 use std::path::{Path, PathBuf};
27
28 pub use self::budget::InstructionAssembly;
29 pub use self::budget::{
30 InstructionAction, InstructionBudgetConfig, InstructionBudgetPolicy, InstructionBudgets,
31 InstructionDetail, InstructionLimit, InstructionNotice, InstructionOrigin, InstructionRefusal,
32 InstructionScope, InstructionSegment, apply_instruction_budgets, estimate_instruction_tokens,
33 render_notice_body,
34 };
35 pub use self::constitution::load_repo_constitution_block;
36 use self::constitution::repo_constitution_candidate_paths;
37 pub use self::constitution::{RepoLawAction, RepoLawRule, load_repo_law_rules};
38 use self::pack::generate_bounded_project_overview;
39 pub use self::pack::generate_project_context_pack;
40 use self::types::ProjectContextError;
41 pub use self::types::project_instructions_source_label;
42 use self::types::repo_relative_source_label;
43 pub use self::types::{PinnedProjectInstructions, ProjectContext};
44 use codewhale_config::instruction_budget::DEFAULT_FILE_MAX_BYTES;
45
46 /// Names of project context files to look for, in priority order.
47 ///
48 /// `AGENTS.md` is the canonical cross-agent project-instructions file.
49 /// `WHALE.md` is no longer an active context surface; when present, Codewhale
50 /// reports a migration warning but ignores it. Codewhale-specific repo
51 /// authority now lives in `.codewhale/constitution.json`, not a bespoke
52 /// markdown file. `CLAUDE.md` and the `*/instructions.md` variants are
53 /// read-only compatibility fallbacks; Codewhale never creates or recommends
54 /// them.
55 const PROJECT_CONTEXT_FILES: &[&str] = &[
56 "AGENTS.md",
57 ".claude/instructions.md",
58 "CLAUDE.md",
59 ".codewhale/instructions.md",
60 ".deepseek/instructions.md",
61 ];
62
63 /// A foreign agent's instruction format. These are read only when the user
64 /// opts in by name, because a file written as law for a different tool is not
65 /// automatically law for this one — and because silently treating a file the
66 /// user never pointed at us as standing authority is an injection surface,
67 /// not a convenience.
68 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
69 pub enum ForeignInstructionFormat {
70 Claude,
71 Cursor,
72 Cline,
73 Windsurf,
74 Gemini,
75 Copilot,
76 Muse,
77 }
78
79 impl ForeignInstructionFormat {
80 pub const ALL: &'static [Self] = &[
81 Self::Claude,
82 Self::Cursor,
83 Self::Cline,
84 Self::Windsurf,
85 Self::Gemini,
86 Self::Copilot,
87 Self::Muse,
88 ];
89
90 /// Configuration spelling, as written in `project_instruction_imports`.
91 pub fn key(self) -> &'static str {
92 match self {
93 Self::Claude => "claude",
94 Self::Cursor => "cursor",
95 Self::Cline => "cline",
96 Self::Windsurf => "windsurf",
97 Self::Gemini => "gemini",
98 Self::Copilot => "copilot",
99 Self::Muse => "muse",
100 }
101 }
102
103 pub fn parse(value: &str) -> Option<Self> {
104 let value = value.trim().to_ascii_lowercase();
105 Self::ALL.iter().copied().find(|f| f.key() == value)
106 }
107
108 /// Workspace-relative instruction files this format contributes.
109 fn context_files(self) -> &'static [&'static str] {
110 match self {
111 Self::Claude => &[".claude/instructions.md", "CLAUDE.md"],
112 // The remaining formats are imported through the bounded-fragment
113 // loader in `codewhale_core::fragments`, not through this chain.
114 _ => &[],
115 }
116 }
117
118 /// Workspace-relative rules directories this format contributes.
119 fn rules_dirs(self) -> &'static [&'static str] {
120 match self {
121 Self::Claude => &[".claude/rules"],
122 _ => &[],
123 }
124 }
125
126 /// Candidates handled by the bounded-fragment loader in
127 /// `codewhale_core::fragments` rather than by the instruction chain.
128 fn fragment_candidates(self) -> &'static [&'static str] {
129 match self {
130 Self::Cursor => &[".cursorrules", ".cursor/rules"],
131 Self::Cline => &[".clinerules"],
132 Self::Windsurf => &[".windsurf/rules"],
133 Self::Gemini => &[".gemini"],
134 Self::Copilot => &[".github/copilot-instructions.md"],
135 Self::Muse => &[".github/muse-instructions.md"],
136 // Claude's files are read by the instruction chain above, so
137 // importing them here too would inject the same bytes twice.
138 Self::Claude => &[],
139 }
140 }
141 }
142
143 /// The set of foreign formats the user has explicitly opted into.
144 ///
145 /// Resolved from config once and read by the loader. Empty by default: a fresh
146 /// checkout containing a `CLAUDE.md` written for another tool contributes
147 /// nothing to Codewhale's standing instructions until someone says so.
148 #[derive(Debug, Clone, Default, PartialEq, Eq)]
149 pub struct ForeignInstructionImports {
150 enabled: std::collections::BTreeSet<&'static str>,
151 }
152
153 impl ForeignInstructionImports {
154 #[cfg(any(test, feature = "test-support"))]
155 #[must_use]
156 pub fn none() -> Self {
157 Self::default()
158 }
159
160 /// Parse configured names, returning the set plus any unrecognized names
161 /// so the caller can warn instead of silently ignoring a typo.
162 #[must_use]
163 pub fn from_config(values: &[String]) -> (Self, Vec<String>) {
164 let mut enabled = std::collections::BTreeSet::new();
165 let mut unknown = Vec::new();
166 for value in values {
167 let trimmed = value.trim();
168 if trimmed.is_empty() {
169 continue;
170 }
171 if trimmed.eq_ignore_ascii_case("all") {
172 enabled.extend(ForeignInstructionFormat::ALL.iter().map(|f| f.key()));
173 continue;
174 }
175 match ForeignInstructionFormat::parse(trimmed) {
176 Some(format) => {
177 enabled.insert(format.key());
178 }
179 None => unknown.push(trimmed.to_string()),
180 }
181 }
182 (Self { enabled }, unknown)
183 }
184
185 #[must_use]
186 pub fn is_enabled(&self, format: ForeignInstructionFormat) -> bool {
187 self.enabled.contains(format.key())
188 }
189
190 #[cfg(any(test, feature = "test-support"))]
191 #[must_use]
192 pub fn is_empty(&self) -> bool {
193 self.enabled.is_empty()
194 }
195
196 /// Enabled format keys, for provenance and diagnostics.
197 #[must_use]
198 pub fn keys(&self) -> Vec<&'static str> {
199 self.enabled.iter().copied().collect()
200 }
201 }
202
203 #[must_use]
204 pub fn fragment_candidates_for(imports: &ForeignInstructionImports) -> Vec<&'static str> {
205 let mut candidates: Vec<&'static str> = vec![".agents/AGENTS.md"];
206 for format in ForeignInstructionFormat::ALL {
207 if imports.is_enabled(*format) {
208 candidates.extend(format.fragment_candidates());
209 }
210 }
211 candidates
212 }
213
214 #[derive(Debug, Clone, PartialEq, Eq)]
215 pub struct InstructionSettings {
216 pub budget: InstructionBudgetConfig,
217 pub imports: ForeignInstructionImports,
218 pub home: Option<PathBuf>,
219 }
220
221 impl Default for InstructionSettings {
222 fn default() -> Self {
223 Self {
224 budget: InstructionBudgetConfig::default(),
225 imports: ForeignInstructionImports::default(),
226 home: codewhale_paths::user_home(),
227 }
228 }
229 }
230
231 impl InstructionSettings {
232 pub fn from_config(config: &codewhale_runtime::config::Config) -> Self {
233 Self {
234 budget: config.instruction_budget.clone().unwrap_or_default(),
235 imports: ForeignInstructionImports::from_config(&config.project_instruction_imports).0,
236 home: codewhale_paths::user_home(),
237 }
238 }
239
240 fn file_max_bytes(&self) -> u64 {
241 self.budget
242 .file_max_bytes
243 .unwrap_or(DEFAULT_FILE_MAX_BYTES)
244 .min(DEFAULT_FILE_MAX_BYTES)
245 }
246 fn claude_fallback(&self) -> bool {
247 self.budget.claude_fallback.unwrap_or(false)
248 }
249 }
250
251 /// Instruction file candidates in priority order for the active opt-in set.
252 fn context_files_for(imports: &ForeignInstructionImports) -> Vec<&'static str> {
253 // Order is priority: `load_dir_instructions` takes the first usable match
254 // in a directory. AGENTS.md leads, then Codewhale's own files, and only
255 // then anything imported from another tool — an imported CLAUDE.md must
256 // never outrank .codewhale/instructions.md the way the old flat list let
257 // it. Only an enabled import adds a foreign candidate here; the source
258 // listing adds the opt-in `claude_fallback` candidates itself.
259 let mut files: Vec<&'static str> = vec![
260 "AGENTS.md",
261 ".codewhale/instructions.md",
262 ".deepseek/instructions.md",
263 ];
264 for format in ForeignInstructionFormat::ALL {
265 if imports.is_enabled(*format) {
266 files.extend(format.context_files());
267 }
268 }
269 files
270 }
271
272 /// Rules directories for the active opt-in set.
273 fn rules_dirs_for(imports: &ForeignInstructionImports) -> Vec<&'static str> {
274 let mut dirs: Vec<&'static str> = vec![".codewhale/rules"];
275 for format in ForeignInstructionFormat::ALL {
276 if imports.is_enabled(*format) {
277 dirs.extend(format.rules_dirs());
278 }
279 }
280 dirs
281 }
282
283 fn rules_dir_has_loadable_content(workspace: &Path, rules_dir_name: &str) -> bool {
284 let rules_dir = workspace.join(rules_dir_name);
285 if fs::symlink_metadata(&rules_dir).is_ok_and(|metadata| metadata.file_type().is_symlink()) {
286 return false;
287 }
288 let Ok(entries) = fs::read_dir(rules_dir) else {
289 return false;
290 };
291 let mut candidates = entries
292 .flatten()
293 .map(|entry| entry.path())
294 .filter(|path| {
295 path.extension().is_some_and(|extension| extension == "md")
296 && context_candidate_exists(path)
297 })
298 .collect::<Vec<_>>();
299 candidates.sort();
300 candidates
301 .into_iter()
302 .take(MAX_RULES_FILES)
303 .any(|path| load_context_file(workspace, &path).is_ok())
304 }
305
306 /// Foreign instruction files that exist in the workspace but were not
307 /// imported, so the user can discover the opt-in instead of wondering why
308 /// their `CLAUDE.md` is being ignored.
309 fn unimported_foreign_warnings(
310 workspace: &Path,
311 imports: &ForeignInstructionImports,
312 ) -> Vec<String> {
313 let mut seen: Vec<&'static str> = Vec::new();
314 for format in ForeignInstructionFormat::ALL {
315 if imports.is_enabled(*format) {
316 continue;
317 }
318 let direct_context_present = format
319 .context_files()
320 .iter()
321 .any(|relative| load_context_file(workspace, &workspace.join(relative)).is_ok());
322 let rules_present = format
323 .rules_dirs()
324 .iter()
325 .any(|relative| rules_dir_has_loadable_content(workspace, relative));
326 let fragment_present =
327 codewhale_core::fragments::load_selected_project_instruction_fragment_with_reader(
328 workspace,
329 format.fragment_candidates(),
330 |path| codewhale_util::fs_confined::open_read(workspace, path),
331 )
332 .is_some();
333 // Keep discovery aligned with the loaders. A path can exist without
334 // being importable (for example an empty or unreadable file, a rules
335 // directory containing no Markdown, an oversized file, or a symlink
336 // that the loaders deliberately refuse to follow). Warning for those
337 // paths would claim there is content available to import when there is
338 // not.
339 let present = direct_context_present || rules_present || fragment_present;
340 if present {
341 seen.push(format.key());
342 }
343 }
344 if seen.is_empty() {
345 return Vec::new();
346 }
347 vec![format!(
348 "Found instruction files for {} in this workspace; they are not loaded. Codewhale reads AGENTS.md and its own instruction files by default. To import them, set project_instruction_imports = [{}] in config.",
349 seen.join(", "),
350 seen.iter()
351 .map(|key| format!("\"{key}\""))
352 .collect::<Vec<_>>()
353 .join(", ")
354 )]
355 }
356
357 /// Rules directories auto-discovered at workspace level, in priority order.
358 /// `.codewhale/rules/` is Codewhale-native; `.claude/rules/` is Claude compatibility.
359 /// All `.md` files in these directories are loaded as project rules in filename order.
360 /// Security model: same trust class as AGENTS.md — workspace-contained content only,
361 /// no absolute-path escape. Does not require #417 project-config relaxation.
362 const RULES_DIRS: &[&str] = &[".codewhale/rules", ".claude/rules"];
363
364 /// File name of the deprecated Codewhale-native instructions file.
365 const DEPRECATED_WHALE_FILENAME: &str = "WHALE.md";
366
367 /// Warning surfaced when an ignored `WHALE.md` is present.
368 const WHALE_IGNORED_WARNING: &str = "WHALE.md is ignored; move project instructions to AGENTS.md, or Codewhale-specific authority policy to .codewhale/constitution.json.";
369
370 /// User-level project instructions loaded as a fallback when the workspace and
371 /// its parents do not define project context. Any global AGENTS.md takes
372 /// priority over a global instructions.md (#3012). Within each file name,
373 /// `.codewhale/` takes priority over vendor-neutral `.agents/`, which takes
374 /// priority over legacy `.deepseek/`. Global `WHALE.md` files are ignored and
375 /// reported as migration-only diagnostics.
376 const GLOBAL_AGENTS_RELATIVE_PATH: &[&str] = &[".codewhale", "AGENTS.md"];
377 const GLOBAL_AGENTS_VENDOR_NEUTRAL_PATH: &[&str] = &[".agents", "AGENTS.md"];
378 const GLOBAL_AGENTS_LEGACY_PATH: &[&str] = &[".deepseek", "AGENTS.md"];
379 const GLOBAL_WHALE_RELATIVE_PATH: &[&str] = &[".codewhale", "WHALE.md"];
380 const GLOBAL_WHALE_VENDOR_NEUTRAL_PATH: &[&str] = &[".agents", "WHALE.md"];
381 const GLOBAL_WHALE_LEGACY_PATH: &[&str] = &[".deepseek", "WHALE.md"];
382 /// Global `instructions.md` (#3012): auto-loaded as a fallback context layer,
383 /// ranked below AGENTS.md, mirroring the project-level precedence.
384 const GLOBAL_INSTRUCTIONS_RELATIVE_PATH: &[&str] = &[".codewhale", "instructions.md"];
385 const GLOBAL_INSTRUCTIONS_VENDOR_NEUTRAL_PATH: &[&str] = &[".agents", "instructions.md"];
386 const GLOBAL_INSTRUCTIONS_LEGACY_PATH: &[&str] = &[".deepseek", "instructions.md"];
387
388 /// Maximum number of rule files loaded per rules directory.
389 ///
390 /// A safety cap, not a budget: the files it drops are reported as
391 /// `skipped (rules_cap)` instead of disappearing into a log line.
392 const MAX_RULES_FILES: usize = 50;
393
394 /// Claude-format instruction files, most authoritative first. `CLAUDE.md` is
395 /// read as a same-directory alternative to `.claude/CLAUDE.md`; `CLAUDE.local.md`
396 /// is Claude-specific and is deliberately not imported.
397 const CLAUDE_CONTEXT_FILES: &[&str] = &["CLAUDE.md", ".claude/CLAUDE.md"];
398
399 /// Render the raw segments into the single instruction string the prompt
400 /// carries: global scope first (so the workspace keeps the last word), then
401 /// the repository-root → workspace chain.
402 ///
403 /// Labels use repository-relative project paths, home-relative global paths,
404 /// and configured file names so host roots stay outside the pinned prefix.
405 #[must_use]
406 pub fn render_joined_instructions(segments: &[InstructionSegment]) -> Option<String> {
407 let global = render_instruction_scope(segments, InstructionScope::Global);
408 let project = render_instruction_scope(segments, InstructionScope::Project);
409 match (global, project) {
410 (Some(global_text), Some(project_text)) => {
411 let global_label = segments
412 .iter()
413 .find(|segment| segment.scope == InstructionScope::Global)
414 .and_then(|segment| segment.label.as_deref())
415 .map(|label| format!("<!-- global: {label} -->"))
416 .unwrap_or_else(|| "<!-- global -->".to_string());
417 Some(format!(
418 "{global_label}\n{}\n\n<!-- project (overrides global where they conflict) -->\n{}",
419 global_text.trim_end(),
420 project_text.trim_start(),
421 ))
422 }
423 (Some(text), None) | (None, Some(text)) => Some(text),
424 (None, None) => None,
425 }
426 }
427
428 fn render_instruction_scope(
429 segments: &[InstructionSegment],
430 scope: InstructionScope,
431 ) -> Option<String> {
432 let mut out = String::new();
433 for segment in segments.iter().filter(|segment| segment.scope == scope) {
434 let label = segment
435 .label
436 .clone()
437 .or_else(|| segment.path.as_ref().map(|path| path.display().to_string()))
438 .unwrap_or_else(|| scope.as_str().to_string());
439 match segment.origin {
440 InstructionOrigin::WhaleSoul => {
441 if !out.is_empty() {
442 out.push_str("\n\n");
443 }
444 out.push_str("The person wrote this whale's personality and voice in SOUL.md. Apply it within all existing permissions and policies.\n");
445 out.push_str(&serde_json::Value::String(segment.text.clone()).to_string());
446 }
447 InstructionOrigin::Configured => {
448 if !out.is_empty() {
449 out.push_str("\n\n");
450 }
451 out.push_str(&format!(
452 "<instructions source=\"{label}\">\n{}\n</instructions>",
453 segment.text.trim()
454 ));
455 }
456 _ if scope == InstructionScope::Global => {
457 if !out.is_empty() {
458 out.push_str(&format!("\n\n<!-- global instructions: {label} -->\n"));
459 }
460 out.push_str(&segment.text);
461 }
462 _ => {
463 if !out.is_empty() {
464 out.push_str(&format!(
465 "\n\n<!-- scoped instructions: {label} (overrides wider scopes where they conflict) -->\n"
466 ));
467 }
468 out.push_str(&segment.text);
469 }
470 }
471 }
472 if out.is_empty() { None } else { Some(out) }
473 }
474
475 /// Assemble both scopes for one request: read the configured `instructions`
476 /// entries fresh, apply per-scope budgets, and re-render the instruction
477 /// string.
478 ///
479 /// This is the only place configured entries are read and charged. They are
480 /// user-level authority, so they belong to the global scope, and reading them
481 /// after the cache lookup means editing one takes effect without invalidating
482 /// the file-keyed context cache.
483 pub fn assemble_instruction_block(
484 ctx: &mut ProjectContext,
485 configured: &[crate::prompts::InstructionSource],
486 budgets: &InstructionBudgets,
487 ) -> InstructionAssembly {
488 append_configured_instructions(ctx, configured, budgets.file_max_bytes);
489 let whale_soul_revision = ctx
490 .instruction_segments
491 .iter()
492 .find(|item| item.origin == InstructionOrigin::WhaleSoul)
493 .map(|item| codewhale_runtime::hashing::sha256_hex(item.text.as_bytes()));
494 let whale_soul_source_path = ctx
495 .instruction_segments
496 .iter()
497 .find(|item| item.origin == InstructionOrigin::WhaleSoul)
498 .and_then(|item| item.canonical_path.as_ref().or(item.path.as_ref()))
499 .cloned();
500 let mut budget_notices =
501 apply_instruction_budgets(&mut ctx.instruction_segments, &mut ctx.rules_block, budgets);
502 budget_notices.retain(|notice| {
503 notice.is_loss()
504 || !ctx
505 .notices
506 .iter()
507 .any(|loss| loss.is_loss() && loss.path.is_some() && loss.path == notice.path)
508 });
509 ctx.notices.append(&mut budget_notices);
510 ctx.rebuild_joined_instructions();
511
512 let global_tokens =
513 render_instruction_scope(&ctx.instruction_segments, InstructionScope::Global)
514 .as_deref()
515 .map_or(0, estimate_instruction_tokens);
516 let mut project_tokens =
517 render_instruction_scope(&ctx.instruction_segments, InstructionScope::Project)
518 .as_deref()
519 .map_or(0, estimate_instruction_tokens);
520 if let Some(rules) = ctx.rules_block.as_deref() {
521 project_tokens = project_tokens.saturating_add(estimate_instruction_tokens(rules));
522 }
523
524 InstructionAssembly {
525 whale_soul_revision,
526 whale_soul_source_path,
527 block: ctx.as_system_block(),
528 source_path: ctx.source_path.clone(),
529 constitution_source_path: ctx.constitution_source_path.clone(),
530 constitution_tokens: ctx
531 .constitution_block
532 .as_deref()
533 .map_or(0, estimate_instruction_tokens),
534 warnings: ctx.warnings.clone(),
535 prompt_range: None,
536 notices: ctx.notices.clone(),
537 global_tokens,
538 project_tokens,
539 budgets: *budgets,
540 }
541 }
542
543 pub fn append_configured_instructions(
544 ctx: &mut ProjectContext,
545 configured: &[crate::prompts::InstructionSource],
546 file_max_bytes: u64,
547 ) {
548 let (configured_segments, mut fresh_notices) =
549 configured_instruction_segments(configured, file_max_bytes);
550 let mut loaded: Vec<PathBuf> = ctx
551 .instruction_segments
552 .iter()
553 .filter_map(|segment| segment.canonical_path.clone())
554 .collect();
555 for segment in configured_segments {
556 if let Some(canonical) = segment.canonical_path.clone() {
557 if loaded.contains(&canonical) {
558 fresh_notices.push(InstructionNotice {
559 path: segment.path.clone(),
560 scope: segment.scope,
561 origin: segment.origin,
562 action: InstructionAction::Skipped,
563 bytes_kept: 0,
564 bytes_dropped: segment.text.len() as u64,
565 tokens_kept: 0,
566 tokens_dropped: estimate_instruction_tokens(&segment.text),
567 limit: InstructionLimit::DuplicatePath,
568 fallback_selected: None,
569 detail: Some(InstructionDetail::AlreadyLoaded),
570 });
571 continue;
572 }
573 loaded.push(canonical);
574 }
575 ctx.instruction_segments.push(segment);
576 }
577
578 ctx.notices.append(&mut fresh_notices);
579 ctx.rebuild_joined_instructions();
580 }
581
582 pub fn capture_instruction_context(
583 workspace: &Path,
584 configured: &[crate::prompts::InstructionSource],
585 settings: &InstructionSettings,
586 ) -> ProjectContext {
587 let mut ctx = load_project_context_with_settings(workspace, settings);
588 append_configured_instructions(&mut ctx, configured, settings.file_max_bytes());
589 ctx
590 }
591
592 /// The instruction notice a session must show before its first turn, or an
593 /// error when `policy = "refuse"` and a budget loss would have occurred.
594 ///
595 /// Deterministic from the current files and config, so the interactive start,
596 /// the headless stderr line, and a resumed session all state the same losses.
597 #[cfg(any(test, feature = "test-support"))]
598 pub fn startup_instruction_notice(
599 workspace: &Path,
600 configured: &[crate::prompts::InstructionSource],
601 window_tokens: Option<usize>,
602 output_tokens: Option<usize>,
603 settings: &InstructionSettings,
604 ) -> Result<Option<String>, String> {
605 let budgets =
606 InstructionBudgets::resolve(Some(&settings.budget), window_tokens, output_tokens)?;
607 let mut ctx = load_project_context_with_settings(workspace, settings);
608 let assembly = assemble_instruction_block(&mut ctx, configured, &budgets);
609 if budgets.policy == InstructionBudgetPolicy::Refuse
610 && let Some(loss) = assembly.notices.iter().find(|notice| {
611 notice.is_loss()
612 && matches!(
613 notice.limit,
614 InstructionLimit::ScopeBudget
615 | InstructionLimit::StaticGuard
616 | InstructionLimit::RulesBudget
617 )
618 })
619 {
620 let mut refused = loss.clone();
621 refused.action = InstructionAction::Refused;
622 return Err(format!(
623 "instruction budget refused this session (policy = \"refuse\"): {refused}"
624 ));
625 }
626 Ok(render_notice_body(&assembly.notices, "en"))
627 }
628
629 /// Read a configured instruction file without trusting its metadata length.
630 ///
631 /// Returns the text and whether the file exceeded `cap`. An over-cap file
632 /// returns no text at all: the caller reports a skip, and nothing past the
633 /// ceiling is read into memory.
634 fn read_instruction_file_bounded(path: &Path, cap: u64) -> std::io::Result<(String, bool)> {
635 use std::io::Read as _;
636
637 let file = codewhale_util::fs_confined::open_user_read(path)?;
638 if !file.metadata()?.is_file() {
639 return Err(std::io::Error::new(
640 std::io::ErrorKind::InvalidInput,
641 "not a regular file",
642 ));
643 }
644 let mut bytes = Vec::new();
645 file.take(cap.saturating_add(1)).read_to_end(&mut bytes)?;
646 if bytes.len() as u64 > cap {
647 return Ok((String::new(), true));
648 }
649 String::from_utf8(bytes)
650 .map(|text| (text, false))
651 .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
652 }
653
654 /// Read the configured `instructions = [...]` entries as global-scope
655 /// segments. Missing, empty, and over-ceiling files are reported and skipped;
656 /// they never fail the launch, and `policy = refuse` does not turn a skip into
657 /// a refusal — one bad include must not make the project unopenable.
658 fn configured_instruction_segments(
659 configured: &[crate::prompts::InstructionSource],
660 file_max_bytes: u64,
661 ) -> (Vec<InstructionSegment>, Vec<InstructionNotice>) {
662 use crate::prompts::InstructionSource;
663
664 let mut segments = Vec::new();
665 let mut notices = Vec::new();
666 for source in configured {
667 if matches!(source, InstructionSource::Inline { name, .. } if name.starts_with("runtime:"))
668 {
669 continue;
670 }
671 let (path, name, content, read_error) = match source {
672 InstructionSource::File(path) => {
673 // Bound the read on the open handle instead of trusting the
674 // metadata length: a zero-length device such as `/dev/zero`, or
675 // a file that grows after the check, must not become an
676 // unbounded read.
677 match read_instruction_file_bounded(path, file_max_bytes) {
678 Ok((_, true)) => {
679 notices.push(InstructionNotice {
680 path: Some(path.clone()),
681 scope: InstructionScope::Global,
682 origin: InstructionOrigin::Configured,
683 action: InstructionAction::Skipped,
684 bytes_kept: 0,
685 bytes_dropped: 0,
686 tokens_kept: 0,
687 tokens_dropped: 0,
688 limit: InstructionLimit::FileCeiling,
689 fallback_selected: None,
690 detail: Some(InstructionDetail::OverFileCeiling {
691 max_bytes: file_max_bytes,
692 }),
693 });
694 continue;
695 }
696 Ok((text, false)) => (Some(path.clone()), None, text, None),
697 Err(error) => (Some(path.clone()), None, String::new(), Some(error)),
698 }
699 }
700 InstructionSource::Inline { name, content } => {
701 (None, Some(name.clone()), content.clone(), None)
702 }
703 };
704 if let Some(error) = read_error {
705 notices.push(InstructionNotice {
706 path,
707 scope: InstructionScope::Global,
708 origin: InstructionOrigin::Configured,
709 action: InstructionAction::Skipped,
710 bytes_kept: 0,
711 bytes_dropped: 0,
712 tokens_kept: 0,
713 tokens_dropped: 0,
714 limit: InstructionLimit::None,
715 fallback_selected: None,
716 detail: Some(InstructionDetail::unreadable(&error)),
717 });
718 continue;
719 }
720 if content.trim().is_empty() {
721 notices.push(InstructionNotice::loss(
722 InstructionScope::Global,
723 InstructionOrigin::Configured,
724 path,
725 InstructionLimit::EmptyFile,
726 InstructionAction::Skipped,
727 ));
728 continue;
729 }
730 let content = if path.is_some() {
731 retain_file_content(
732 content,
733 InstructionScope::Global,
734 InstructionOrigin::Configured,
735 path.as_deref(),
736 &mut notices,
737 )
738 } else {
739 content
740 };
741 let label = name.or_else(|| {
742 path.as_ref().map(|path| {
743 if path.is_absolute() {
744 file_label(path)
745 } else {
746 path.to_string_lossy().replace('\\', "/")
747 }
748 })
749 });
750 let mut segment = InstructionSegment::new(
751 InstructionScope::Global,
752 InstructionOrigin::Configured,
753 path,
754 content.trim().to_string(),
755 );
756 segment.canonical_path = segment
757 .path
758 .as_deref()
759 .and_then(|path| fs::canonicalize(path).ok());
760 segment.label = label;
761 segments.push(segment);
762 }
763 (segments, notices)
764 }
765
766 fn retain_file_content(
767 content: String,
768 scope: InstructionScope,
769 origin: InstructionOrigin,
770 path: Option<&Path>,
771 notices: &mut Vec<InstructionNotice>,
772 ) -> String {
773 const CONTENT_BYTES: usize = 100 * 1024;
774 if content.len() <= CONTENT_BYTES {
775 return content;
776 }
777 let mut end = CONTENT_BYTES;
778 while !content.is_char_boundary(end) {
779 end -= 1;
780 }
781 let head = &content[..end];
782 let dropped = content.len() - end;
783 notices.push(InstructionNotice {
784 path: path.map(Path::to_path_buf),
785 scope,
786 origin,
787 action: InstructionAction::Trimmed,
788 bytes_kept: end as u64,
789 bytes_dropped: dropped as u64,
790 tokens_kept: estimate_instruction_tokens(head),
791 tokens_dropped: estimate_instruction_tokens(&content[end..]),
792 limit: InstructionLimit::FileContent,
793 fallback_selected: None,
794 detail: None,
795 });
796 format!("{head}\n\n[…instruction file truncated: {end} bytes kept, {dropped} bytes dropped…]")
797 }
798
799 /// One directory's resolved instruction segments plus the skips that produced
800 /// them.
801 #[derive(Debug, Default)]
802 struct DirInstructions {
803 segments: Vec<InstructionSegment>,
804 notices: Vec<InstructionNotice>,
805 /// Human-readable reason a candidate was refused. The notice carries the
806 /// structured form; this is the text `/context report` and the Runtime API
807 /// listing have always shown.
808 warnings: Vec<String>,
809 }
810 /// Load project context from the workspace directory.
811 ///
812 /// This searches for known project context files and loads the first one found.
813 /// Convenience wrapper that imports no foreign format.
814 ///
815 /// Production goes through [`load_project_context_with_imports`] so the import
816 /// set is explicit at the call site; this exists for tests that only care about
817 /// default behaviour.
818 #[cfg(any(test, feature = "test-support"))]
819 pub fn load_project_context(workspace: &Path) -> ProjectContext {
820 load_project_context_with_imports(workspace, &ForeignInstructionImports::default())
821 }
822
823 /// Load workspace project context under an explicit foreign-import set.
824 ///
825 /// The set is a parameter rather than a global read so a caller — and every
826 /// test — states which foreign formats are in play instead of depending on
827 /// process-wide state that parallel tests would race on. Production loads the
828 /// repository chain through `load_project_context_with_settings`, which shares
829 /// every helper here.
830 #[cfg(any(test, feature = "test-support"))]
831 pub fn load_project_context_with_imports(
832 workspace: &Path,
833 imports: &ForeignInstructionImports,
834 ) -> ProjectContext {
835 let mut ctx = ProjectContext::empty(workspace.to_path_buf());
836 let label_root = find_git_root(workspace);
837 let mut loaded: Vec<PathBuf> = Vec::new();
838 let dir = {
839 let mut scope = DirLoadContext {
840 imports,
841 file_max_bytes: DEFAULT_FILE_MAX_BYTES,
842 claude_fallback: false,
843 label_root: label_root.as_deref(),
844 loaded: &mut loaded,
845 };
846 load_dir_instructions(workspace, &mut scope)
847 };
848 if let Some(last) = dir.segments.last() {
849 ctx.source_path = last.path.clone();
850 }
851 ctx.notices.extend(dir.notices);
852 ctx.warnings.extend(dir.warnings);
853 ctx.instruction_segments.extend(dir.segments);
854
855 ctx.warnings
856 .extend(ignored_project_whale_warnings(workspace));
857 ctx.warnings
858 .extend(unimported_foreign_warnings(workspace, imports));
859
860 // Rules are workspace-scope authority. Labels are repo-relative because
861 // the block sits inside the pinned system prompt; the project scope
862 // budget charges it after the instruction chain.
863 let rules = load_rules_block(
864 workspace,
865 imports,
866 label_root.as_deref().unwrap_or(workspace),
867 DEFAULT_FILE_MAX_BYTES,
868 );
869 ctx.notices.extend(rules.notices);
870 ctx.rules_block = rules.block;
871
872 ctx.rebuild_joined_instructions();
873 ctx
874 }
875
876 /// Everything one scope directory's loader needs, so the selection rules are
877 /// stated once and shared by the workspace loader and the ancestor chain.
878 struct DirLoadContext<'a> {
879 imports: &'a ForeignInstructionImports,
880 file_max_bytes: u64,
881 /// Read `CLAUDE.md` when no `AGENTS.md`/codewhale file is usable.
882 claude_fallback: bool,
883 /// Repository root for repo-relative segment labels.
884 label_root: Option<&'a Path>,
885 /// Canonical paths already loaded by wider scopes; one physical file loads
886 /// once no matter how many scopes link to it.
887 loaded: &'a mut Vec<PathBuf>,
888 }
889
890 /// Resolve one directory's instruction files.
891 ///
892 /// Selection follows OpenCode's model with codewhale's own sources preserved:
893 /// `AGENTS.md` wins; codewhale's `.codewhale/instructions.md` (and the legacy
894 /// `.deepseek/` spelling) sit next; `CLAUDE.md` is co-read when the `claude`
895 /// import is enabled and is read as a fallback only when `claude_fallback` is
896 /// opted in. A candidate that
897 /// exists but cannot be used counts as **absent**, so the next candidate is
898 /// tried — including `CLAUDE.md`. A duplicate of an already-loaded file is
899 /// *not* absent: the content is already in the prompt from a wider scope, so
900 /// no fallback runs and the notice says `duplicate`.
901 fn load_dir_instructions(dir: &Path, scope: &mut DirLoadContext<'_>) -> DirInstructions {
902 let mut out = DirInstructions::default();
903 let mut chain: Vec<(&'static str, InstructionOrigin)> = vec![
904 ("AGENTS.md", InstructionOrigin::Agents),
905 (
906 ".codewhale/instructions.md",
907 InstructionOrigin::Instructions,
908 ),
909 (".deepseek/instructions.md", InstructionOrigin::Instructions),
910 ];
911 if scope.imports.is_enabled(ForeignInstructionFormat::Claude) {
912 chain.push((".claude/instructions.md", InstructionOrigin::Claude));
913 }
914
915 let mut primary_resolved = false;
916 let mut preferred_skipped: Option<PathBuf> = None;
917 for (filename, origin) in chain {
918 let path = dir.join(filename);
919 if !context_candidate_exists(&path) {
920 continue;
921 }
922 if is_duplicate(&path, scope.loaded) {
923 out.notices.push(duplicate_notice(origin, &path));
924 // A duplicate is not "absent": the content is already in the
925 // prompt from a wider scope, so no fallback runs for this
926 // directory.
927 primary_resolved = true;
928 break;
929 }
930 match load_context_file_limited(dir, &path, scope.file_max_bytes) {
931 Ok(content) => {
932 let pushed = push_loaded_segment(&mut out, scope, origin, &path, content);
933 if pushed
934 && let Some(preferred) = preferred_skipped.as_ref()
935 && let Some(skipped) = out
936 .notices
937 .iter_mut()
938 .find(|notice| notice.path.as_ref() == Some(preferred))
939 {
940 skipped.fallback_selected = Some(relative_label(dir, &path));
941 }
942 primary_resolved = true;
943 break;
944 }
945 Err(error) => {
946 if preferred_skipped.is_none() {
947 preferred_skipped = Some(path.clone());
948 }
949 out.warnings.push(error.to_string());
950 out.notices.push(skip_notice(origin, &path, &error));
951 }
952 }
953 }
954
955 let claude_imported = scope.imports.is_enabled(ForeignInstructionFormat::Claude);
956 let claude_paths: Vec<PathBuf> = CLAUDE_CONTEXT_FILES
957 .iter()
958 .map(|filename| dir.join(filename))
959 .filter(|path| context_candidate_exists(path))
960 .collect();
961 // An explicit import co-reads `CLAUDE.md` next to `AGENTS.md`; the default
962 // fallback runs only when nothing else in this directory loaded, and
963 // `claude_fallback = false` is an explicit opt-out.
964 let read_claude = claude_imported || (scope.claude_fallback && !primary_resolved);
965 if read_claude {
966 // Candidates are tried in order and a skipped one falls through to the
967 // next, exactly like the `AGENTS.md` chain.
968 for path in claude_paths {
969 if is_duplicate(&path, scope.loaded) {
970 out.notices
971 .push(duplicate_notice(InstructionOrigin::Claude, &path));
972 return out;
973 }
974 match load_context_file_limited(dir, &path, scope.file_max_bytes) {
975 Ok(content) => {
976 let pushed = push_loaded_segment(
977 &mut out,
978 scope,
979 InstructionOrigin::Claude,
980 &path,
981 content,
982 );
983 if pushed
984 && !primary_resolved
985 && let Some(preferred) = preferred_skipped.as_ref()
986 && let Some(skipped) = out
987 .notices
988 .iter_mut()
989 .find(|notice| notice.path.as_ref() == Some(preferred))
990 {
991 skipped.fallback_selected = Some(relative_label(dir, &path));
992 }
993 break;
994 }
995 Err(error) => {
996 out.warnings.push(error.to_string());
997 out.notices
998 .push(skip_notice(InstructionOrigin::Claude, &path, &error))
999 }
1000 }
1001 }
1002 }
1003
1004 out
1005 }
1006
1007 /// Push one loaded file as a project-scope segment, reporting a duplicate
1008 /// instead of loading the same physical file twice.
1009 fn push_loaded_segment(
1010 out: &mut DirInstructions,
1011 scope: &mut DirLoadContext<'_>,
1012 origin: InstructionOrigin,
1013 path: &Path,
1014 content: String,
1015 ) -> bool {
1016 let canonical = fs::canonicalize(path).ok();
1017 if let Some(canonical) = canonical.as_ref() {
1018 if scope.loaded.contains(canonical) {
1019 out.notices.push(InstructionNotice {
1020 path: Some(path.to_path_buf()),
1021 scope: InstructionScope::Project,
1022 origin,
1023 action: InstructionAction::Skipped,
1024 bytes_kept: 0,
1025 bytes_dropped: content.len() as u64,
1026 tokens_kept: 0,
1027 tokens_dropped: estimate_instruction_tokens(&content),
1028 limit: InstructionLimit::DuplicatePath,
1029 fallback_selected: None,
1030 detail: Some(InstructionDetail::AlreadyLoaded),
1031 });
1032 return false;
1033 }
1034 scope.loaded.push(canonical.clone());
1035 }
1036 tracing::info!(
1037 "Loaded project context from {} ({} bytes)",
1038 path.display(),
1039 content.len()
1040 );
1041 let content = retain_file_content(
1042 content,
1043 InstructionScope::Project,
1044 origin,
1045 Some(path),
1046 &mut out.notices,
1047 );
1048 let mut segment = InstructionSegment::new(
1049 InstructionScope::Project,
1050 origin,
1051 Some(path.to_path_buf()),
1052 content,
1053 );
1054 segment.canonical_path = canonical;
1055 segment.label = Some(repo_relative_source_label(path, scope.label_root));
1056 out.segments.push(segment);
1057 true
1058 }
1059
1060 /// Whether `path` names a physical file already loaded by a wider scope.
1061 fn is_duplicate(path: &Path, loaded: &[PathBuf]) -> bool {
1062 fs::canonicalize(path).is_ok_and(|canonical| loaded.contains(&canonical))
1063 }
1064
1065 fn relative_label(dir: &Path, path: &Path) -> String {
1066 path.strip_prefix(dir)
1067 .unwrap_or(path)
1068 .to_string_lossy()
1069 .replace('\\', "/")
1070 }
1071
1072 fn file_label(path: &Path) -> String {
1073 path.file_name().map_or_else(
1074 || path.display().to_string(),
1075 |name| name.to_string_lossy().into_owned(),
1076 )
1077 }
1078
1079 fn duplicate_notice(origin: InstructionOrigin, path: &Path) -> InstructionNotice {
1080 InstructionNotice {
1081 path: Some(path.to_path_buf()),
1082 scope: InstructionScope::Project,
1083 origin,
1084 action: InstructionAction::Skipped,
1085 bytes_kept: 0,
1086 bytes_dropped: 0,
1087 tokens_kept: 0,
1088 tokens_dropped: 0,
1089 limit: InstructionLimit::DuplicatePath,
1090 fallback_selected: None,
1091 detail: Some(InstructionDetail::AlreadyLoaded),
1092 }
1093 }
1094
1095 fn skip_notice(
1096 origin: InstructionOrigin,
1097 path: &Path,
1098 error: &ProjectContextError,
1099 ) -> InstructionNotice {
1100 InstructionNotice {
1101 path: Some(path.to_path_buf()),
1102 scope: InstructionScope::Project,
1103 origin,
1104 action: InstructionAction::Skipped,
1105 bytes_kept: 0,
1106 bytes_dropped: 0,
1107 tokens_kept: 0,
1108 tokens_dropped: 0,
1109 limit: error.kind(),
1110 fallback_selected: None,
1111 detail: error.detail(),
1112 }
1113 }
1114
1115 /// Load project context from the containing repository as well.
1116 ///
1117 /// Applicable instruction files resolve from the repository root down to the
1118 /// workspace (inclusive) and are assembled in that order under one aggregate
1119 /// byte budget, so wider scopes read first and the workspace keeps the last
1120 /// word. Repository identity comes from the containing checkout itself
1121 /// (Git dir/worktree traversal, [`find_git_root`]) — never from branch names
1122 /// or paths mentioned in conversation — and the chain never crosses the
1123 /// repository boundary. Outside any repository only the workspace itself is
1124 /// searched.
1125 pub fn load_project_context_with_parents(workspace: &Path) -> ProjectContext {
1126 load_project_context_with_settings(workspace, &InstructionSettings::default())
1127 }
1128
1129 pub fn load_project_context_with_settings(
1130 workspace: &Path,
1131 settings: &InstructionSettings,
1132 ) -> ProjectContext {
1133 let workspace = canonicalize_workspace_or_keep(workspace);
1134 let pre = crate::project_context_cache::compute_cache_key_with_settings(&workspace, settings);
1135 if let Some(ctx) = crate::project_context_cache::lookup(&pre) {
1136 return ctx;
1137 }
1138 let ctx = load_project_context_with_settings_uncached(&workspace, settings);
1139 let post = crate::project_context_cache::compute_cache_key_with_settings(&workspace, settings);
1140 if pre == post {
1141 crate::project_context_cache::store(pre, ctx.clone());
1142 }
1143 ctx
1144 }
1145
1146 #[cfg(test)]
1147 fn load_project_context_with_parents_cached_and_home(
1148 workspace: &Path,
1149 home_dir: Option<&Path>,
1150 ) -> ProjectContext {
1151 load_project_context_with_settings(
1152 workspace,
1153 &InstructionSettings {
1154 home: home_dir.map(Path::to_path_buf),
1155 ..Default::default()
1156 },
1157 )
1158 }
1159
1160 #[cfg(test)]
1161 fn load_project_context_with_parents_and_home(
1162 workspace: &Path,
1163 home_dir: Option<&Path>,
1164 ) -> ProjectContext {
1165 load_project_context_with_parents_cached_and_home(workspace, home_dir)
1166 }
1167
1168 fn load_project_context_with_settings_uncached(
1169 workspace: &Path,
1170 settings: &InstructionSettings,
1171 ) -> ProjectContext {
1172 let home_dir = settings.home.as_deref();
1173 let imports = &settings.imports;
1174 let workspace_canonical = canonicalize_workspace_or_keep(workspace);
1175 // Chain-segment labels sit inside the pinned system prompt, so they are
1176 // rendered repo-relative: a checkout move or recase leaves the labels —
1177 // and therefore the whole prompt prefix — byte-identical. The chain
1178 // never leaves the checkout (`context_chain_dirs`), so every labeled
1179 // path strips cleanly.
1180 let git_root = find_git_root(&workspace_canonical);
1181 let claude_fallback = settings.claude_fallback();
1182 let mut ctx = ProjectContext::empty(workspace_canonical.clone());
1183
1184 // The global layer loads first: it is the widest scope, so a project file
1185 // symlinked to it is recognised as a duplicate instead of being charged
1186 // twice.
1187 let mut loaded: Vec<PathBuf> = Vec::new();
1188 let global = load_global_agents_context(
1189 &workspace_canonical,
1190 home_dir,
1191 claude_fallback || imports.is_enabled(ForeignInstructionFormat::Claude),
1192 settings.file_max_bytes(),
1193 &mut loaded,
1194 );
1195 if let Some(global) = &global {
1196 ctx.warnings.extend(global.warnings.iter().cloned());
1197 ctx.notices.extend(global.notices.iter().cloned());
1198 }
1199
1200 // Assemble the repository-root → workspace instruction chain. The chain
1201 // directories come from Git traversal of the containing checkout, so a
1202 // linked worktree contributes its own root and files above the root —
1203 // other checkouts, unrelated parents — stay out of scope. Segments are
1204 // appended root first, so the nearest scope has the last word and is the
1205 // last thing a budget trim drops.
1206 let chain_dirs = context_chain_dirs(&workspace_canonical, git_root.as_deref(), home_dir);
1207 let mut project_segments: Vec<InstructionSegment> = Vec::new();
1208 {
1209 let mut scope = DirLoadContext {
1210 imports,
1211 file_max_bytes: settings.file_max_bytes(),
1212 claude_fallback,
1213 label_root: git_root.as_deref(),
1214 loaded: &mut loaded,
1215 };
1216 for dir in &chain_dirs {
1217 ctx.warnings.extend(ignored_project_whale_warnings(dir));
1218 let dir_instructions = load_dir_instructions(dir, &mut scope);
1219 ctx.notices.extend(dir_instructions.notices);
1220 ctx.warnings.extend(dir_instructions.warnings);
1221 project_segments.extend(dir_instructions.segments);
1222 }
1223 }
1224
1225 // Unimported foreign formats stay discoverable rather than silently
1226 // ignored: the warning names the opt-in key that would read them.
1227 ctx.warnings
1228 .extend(unimported_foreign_warnings(&workspace_canonical, imports));
1229
1230 // Rules are workspace-scope authority: the chain loader never reads
1231 // ancestor rules.
1232 let rules = load_rules_block(
1233 &workspace_canonical,
1234 imports,
1235 git_root.as_deref().unwrap_or(workspace_canonical.as_path()),
1236 settings.file_max_bytes(),
1237 );
1238 ctx.notices.extend(rules.notices);
1239 ctx.rules_block = rules.block;
1240 ctx.loaded_rule_paths = rules.paths;
1241
1242 // `source_path` names the most specific source — the workspace file when
1243 // there is one, otherwise the nearest ancestor that contributed.
1244 if let Some(last) = project_segments.last() {
1245 ctx.source_path = last.path.clone();
1246 }
1247 ctx.instruction_segments = project_segments;
1248
1249 if let Some(global) = global {
1250 let mut segments = global.instruction_segments;
1251 segments.append(&mut ctx.instruction_segments);
1252 ctx.instruction_segments = segments;
1253 if ctx.source_path.is_none() {
1254 ctx.source_path = global.source_path;
1255 }
1256 }
1257 ctx.rebuild_joined_instructions();
1258
1259 // Generate a bounded in-memory fallback when no context file exists
1260 // anywhere. This keeps prompt shape stable without creating project-local
1261 // `.codewhale/` files merely because Codewhale was opened in a directory.
1262 if !ctx.has_instructions()
1263 && let Some(generated) = generate_ephemeral_context(workspace)
1264 {
1265 ctx.instruction_segments.push(InstructionSegment::new(
1266 InstructionScope::Project,
1267 InstructionOrigin::Instructions,
1268 None,
1269 generated,
1270 ));
1271 ctx.source_path = None;
1272 ctx.rebuild_joined_instructions();
1273 }
1274
1275 // Load the Codewhale-specific repo authority policy
1276 // (.codewhale/constitution.json) independently of the prose instructions —
1277 // it is a distinct, higher-authority artifact and may exist with or without
1278 // an AGENTS.md. Legacy WHALE.md files are ignored and reported as
1279 // migration-only diagnostics.
1280 let (constitution_block, constitution_source_path, constitution_warnings) =
1281 load_repo_constitution_block(workspace);
1282 ctx.warnings.extend(constitution_warnings);
1283 ctx.constitution_block = constitution_block;
1284 ctx.constitution_source_path = constitution_source_path;
1285
1286 ctx
1287 }
1288
1289 /// Assemble the workspace rules block. Labels are repo-relative because the
1290 /// block sits inside the pinned system prompt.
1291 fn load_rules_block(
1292 workspace: &Path,
1293 imports: &ForeignInstructionImports,
1294 label_root: &Path,
1295 file_max_bytes: u64,
1296 ) -> RulesLoad {
1297 let mut block = String::new();
1298 let mut notices = Vec::new();
1299 let mut paths = Vec::new();
1300 for rules_dir in rules_dirs_for(imports) {
1301 let rules = load_rules_from_dir(workspace, rules_dir, file_max_bytes);
1302 notices.extend(rules.notices);
1303 for (path, content) in rules.entries {
1304 if !block.is_empty() {
1305 block.push('\n');
1306 }
1307 block.push_str(&format!(
1308 "<project_rule source=\"{}\">\n{}\n</project_rule>",
1309 repo_relative_source_label(&path, Some(label_root)),
1310 content.trim()
1311 ));
1312 paths.push(path);
1313 }
1314 }
1315 RulesLoad {
1316 block: if block.is_empty() { None } else { Some(block) },
1317 notices,
1318 paths,
1319 }
1320 }
1321
1322 /// One rules directory pass: the loaded files and the skips that produced
1323 /// them. A rules overflow or an unreadable file is a reported skip, never a
1324 /// silent drop.
1325 struct RulesDirLoad {
1326 entries: Vec<(PathBuf, String)>,
1327 notices: Vec<InstructionNotice>,
1328 }
1329
1330 /// The assembled rules block plus the skips from every rules directory.
1331 struct RulesLoad {
1332 block: Option<String>,
1333 notices: Vec<InstructionNotice>,
1334 paths: Vec<PathBuf>,
1335 }
1336
1337 pub fn project_context_cache_candidate_paths(
1338 workspace: &Path,
1339 home_dir: Option<&Path>,
1340 ) -> Vec<(PathBuf, Option<PathBuf>)> {
1341 let workspace = canonicalize_workspace_or_keep(workspace);
1342 let mut paths = Vec::new();
1343
1344 // Enumerate the superset of instruction candidates, not just the ones the
1345 // active opt-in set loads: a `CLAUDE.md` that is *not* imported still
1346 // decides whether the "not loaded" warning fires, so its content has to
1347 // invalidate the cache too. The cache key carries the loading settings, so
1348 // a changed opt-in set never reuses an entry and over-enumerating here
1349 // only ever costs an extra reload.
1350 let repo_root = find_git_root(&workspace);
1351 for dir in context_chain_dirs(&workspace, repo_root.as_deref(), home_dir) {
1352 for filename in PROJECT_CONTEXT_FILES {
1353 paths.push((dir.join(filename), Some(dir.clone())));
1354 }
1355 // `CLAUDE.md` / `.claude/CLAUDE.md` decide the selection even when the
1356 // `claude` import is off (`claude_fallback`), so their content must
1357 // invalidate the cache too. `PROJECT_CONTEXT_FILES` already carries
1358 // `CLAUDE.md`; the hidden spelling is added here.
1359 paths.push((dir.join(".claude/CLAUDE.md"), Some(dir.clone())));
1360 paths.push((dir.join(DEPRECATED_WHALE_FILENAME), Some(dir.clone())));
1361 }
1362
1363 if let Some(home) = home_dir {
1364 for candidate in global_context_relative_paths() {
1365 paths.push((join_relative_components(home, candidate), None));
1366 }
1367 // Last-resort global `~/.claude/CLAUDE.md` (#6526).
1368 paths.push((
1369 join_relative_components(home, &[".claude", "CLAUDE.md"]),
1370 None,
1371 ));
1372 for candidate in legacy_global_whale_relative_paths() {
1373 paths.push((join_relative_components(home, candidate), None));
1374 }
1375 }
1376
1377 paths.extend(
1378 repo_constitution_candidate_paths(&workspace)
1379 .into_iter()
1380 .map(|path| {
1381 let root = path.parent().and_then(Path::parent).map(Path::to_path_buf);
1382 (path, root)
1383 }),
1384 );
1385
1386 // Include auto-discovered rules directory files so cache invalidates
1387 // when rules change (not just when AGENTS.md changes).
1388 for rules_dir in RULES_DIRS {
1389 let dir_path = workspace.join(rules_dir);
1390 // Skip symlinked rules directories (same guard as load_rules_from_dir)
1391 if fs::symlink_metadata(&dir_path)
1392 .map(|m| m.file_type().is_symlink())
1393 .unwrap_or(false)
1394 {
1395 continue;
1396 }
1397 if let Ok(entries) = std::fs::read_dir(&dir_path) {
1398 for entry in entries.flatten() {
1399 let path = entry.path();
1400 if path.extension().is_some_and(|ext| ext == "md") {
1401 paths.push((path, Some(workspace.clone())));
1402 }
1403 }
1404 }
1405 }
1406
1407 // The warning for unimported foreign formats is part of the cached
1408 // ProjectContext. Fingerprint exactly the safe, capped fragment files the
1409 // bounded loader can select so creating, changing, removing, or making one
1410 // unusable invalidates a previously cached warning decision. Enumerating
1411 // every format is intentional: changing the opt-in set clears the cache,
1412 // and the superset keeps disabled-format discovery correct.
1413 for format in ForeignInstructionFormat::ALL {
1414 paths.extend(
1415 codewhale_core::fragments::selected_project_instruction_candidate_files(
1416 &workspace,
1417 format.fragment_candidates(),
1418 )
1419 .into_iter()
1420 .map(|path| (path, Some(workspace.clone()))),
1421 );
1422 }
1423
1424 paths
1425 }
1426
1427 fn global_context_relative_paths() -> [&'static [&'static str]; 6] {
1428 [
1429 GLOBAL_AGENTS_RELATIVE_PATH,
1430 GLOBAL_AGENTS_VENDOR_NEUTRAL_PATH,
1431 GLOBAL_AGENTS_LEGACY_PATH,
1432 GLOBAL_INSTRUCTIONS_RELATIVE_PATH,
1433 GLOBAL_INSTRUCTIONS_VENDOR_NEUTRAL_PATH,
1434 GLOBAL_INSTRUCTIONS_LEGACY_PATH,
1435 ]
1436 }
1437
1438 fn legacy_global_whale_relative_paths() -> [&'static [&'static str]; 3] {
1439 [
1440 GLOBAL_WHALE_RELATIVE_PATH,
1441 GLOBAL_WHALE_VENDOR_NEUTRAL_PATH,
1442 GLOBAL_WHALE_LEGACY_PATH,
1443 ]
1444 }
1445
1446 fn join_relative_components(base: &Path, relative: &[&str]) -> PathBuf {
1447 let mut path = base.to_path_buf();
1448 for component in relative {
1449 path.push(component);
1450 }
1451 path
1452 }
1453
1454 fn ignored_project_whale_warnings(dir: &Path) -> Vec<String> {
1455 let path = dir.join(DEPRECATED_WHALE_FILENAME);
1456 ignored_whale_warning_for_path(&path).into_iter().collect()
1457 }
1458
1459 fn ignored_global_whale_warnings(home: &Path) -> Vec<String> {
1460 legacy_global_whale_relative_paths()
1461 .iter()
1462 .filter_map(|candidate| {
1463 let path = join_relative_components(home, candidate);
1464 ignored_whale_warning_for_path(&path)
1465 })
1466 .collect()
1467 }
1468
1469 fn ignored_whale_warning_for_path(path: &Path) -> Option<String> {
1470 context_candidate_exists(path)
1471 .then(|| format!("{WHALE_IGNORED_WARNING} Ignored file: {}", path.display()))
1472 }
1473
1474 fn canonicalize_workspace_or_keep(workspace: &Path) -> PathBuf {
1475 fs::canonicalize(workspace).unwrap_or_else(|_| workspace.to_path_buf())
1476 }
1477
1478 /// Find the root of the checkout that contains `dir`.
1479 ///
1480 /// Walks upward looking for a `.git` entry, following Git's own discovery
1481 /// semantics: a `.git` directory must hold `HEAD`, and a `.git` file must be
1482 /// a `gitdir:` pointer (a linked worktree). A linked worktree is therefore
1483 /// its own root — the main checkout is reachable only through that pointer,
1484 /// never through directory heuristics, branch names, or paths mentioned in
1485 /// conversation. This is the single source of truth for repository identity
1486 /// in project-context scope resolution.
1487 pub fn find_git_root(dir: &Path) -> Option<PathBuf> {
1488 let mut current = dir.to_path_buf();
1489 loop {
1490 let git_entry = current.join(".git");
1491 if is_git_metadata_entry(&git_entry) {
1492 return Some(current);
1493 }
1494 match current.parent() {
1495 Some(parent) if parent != current => current = parent.to_path_buf(),
1496 _ => return None,
1497 }
1498 }
1499 }
1500
1501 fn is_git_metadata_entry(path: &Path) -> bool {
1502 if path.is_dir() {
1503 return path.join("HEAD").is_file();
1504 }
1505
1506 fs::read_to_string(path)
1507 .map(|content| content.trim_start().starts_with("gitdir:"))
1508 .unwrap_or(false)
1509 }
1510
1511 /// Directories whose instruction files apply to `workspace`, ordered from the
1512 /// repository root down to the workspace (inclusive).
1513 ///
1514 /// Repository identity comes from the containing checkout itself
1515 /// ([`find_git_root`]), passed in as `repo_root` so the chain bounds and the
1516 /// chain-segment labels are derived from one and the same walk; the chain
1517 /// never crosses the repository boundary, so sibling checkouts and unrelated
1518 /// parents stay out of scope. Outside any repository (`repo_root` is `None`)
1519 /// only the workspace itself is searched. When `home_dir` is an ancestor it
1520 /// remains an outer boundary the walk never leaves.
1521 fn context_chain_dirs(
1522 workspace: &Path,
1523 repo_root: Option<&Path>,
1524 home_dir: Option<&Path>,
1525 ) -> Vec<PathBuf> {
1526 let mut stop = repo_root
1527 .map(Path::to_path_buf)
1528 .unwrap_or_else(|| workspace.to_path_buf());
1529
1530 if let Some(home) = home_dir {
1531 let home = canonicalize_workspace_or_keep(home);
1532 // Clamp only when the walk would otherwise leave the user's home
1533 // (home sits between the workspace and the repository root).
1534 if workspace.starts_with(&home) && home.starts_with(&stop) {
1535 stop = home;
1536 }
1537 }
1538
1539 let mut dirs = Vec::new();
1540 let mut cursor = workspace.to_path_buf();
1541 loop {
1542 dirs.push(cursor.clone());
1543 if cursor == stop {
1544 break;
1545 }
1546 match cursor.parent() {
1547 Some(parent) if parent != cursor => cursor = parent.to_path_buf(),
1548 _ => break,
1549 }
1550 }
1551 dirs.reverse();
1552 dirs
1553 }
1554
1555 fn load_global_agents_context(
1556 workspace: &Path,
1557 home_dir: Option<&Path>,
1558 claude_fallback: bool,
1559 file_max_bytes: u64,
1560 loaded: &mut Vec<PathBuf>,
1561 ) -> Option<ProjectContext> {
1562 let home = home_dir?;
1563
1564 // Priority order (AGENTS.md preferred; instructions.md next, #3012):
1565 // 1. ~/.codewhale/AGENTS.md (canonical)
1566 // 2. ~/.agents/AGENTS.md (vendor-neutral fallback)
1567 // 3. ~/.deepseek/AGENTS.md (legacy fallback)
1568 // 4. ~/.codewhale/instructions.md (canonical)
1569 // 5. ~/.agents/instructions.md (vendor-neutral fallback)
1570 // 6. ~/.deepseek/instructions.md (legacy fallback)
1571 // 7. ~/.claude/CLAUDE.md (last resort, `claude_fallback` only)
1572 //
1573 // A candidate that exists but cannot be used counts as absent and the
1574 // next one is tried. Global WHALE.md files are ignored and reported as
1575 // migration-only diagnostics, never loaded as fallback law.
1576 let mut warnings = ignored_global_whale_warnings(home);
1577 let mut notices: Vec<InstructionNotice> = Vec::new();
1578 let mut global_preferred_skipped: Option<PathBuf> = None;
1579 let mut chosen: Option<(PathBuf, String, InstructionOrigin)> = None;
1580
1581 for (index, candidate) in global_context_relative_paths().iter().enumerate() {
1582 let origin = if index < 3 {
1583 InstructionOrigin::Agents
1584 } else {
1585 InstructionOrigin::Instructions
1586 };
1587 let path = join_relative_components(home, candidate);
1588 if !context_candidate_exists(&path) {
1589 continue;
1590 }
1591 match load_global_context_file_limited(&path, file_max_bytes) {
1592 Ok(content) => {
1593 chosen = Some((path, content, origin));
1594 break;
1595 }
1596 Err(error) => {
1597 warnings.push(error.to_string());
1598 if global_preferred_skipped.is_none() {
1599 global_preferred_skipped = Some(path.clone());
1600 }
1601 notices.push(InstructionNotice {
1602 path: Some(path.clone()),
1603 scope: InstructionScope::Global,
1604 origin,
1605 action: InstructionAction::Skipped,
1606 bytes_kept: 0,
1607 bytes_dropped: 0,
1608 tokens_kept: 0,
1609 tokens_dropped: 0,
1610 limit: error.kind(),
1611 fallback_selected: None,
1612 detail: error.detail(),
1613 });
1614 }
1615 }
1616 }
1617
1618 // `~/.claude/CLAUDE.md` is the last resort: foreign files never outrank
1619 // codewhale's own, so it is read only when none of the six candidates
1620 // loaded.
1621 if chosen.is_none() && claude_fallback {
1622 let path = join_relative_components(home, &[".claude", "CLAUDE.md"]);
1623 if context_candidate_exists(&path) {
1624 match load_global_context_file_limited(&path, file_max_bytes) {
1625 Ok(content) => {
1626 chosen = Some((path, content, InstructionOrigin::Claude));
1627 }
1628 Err(error) => {
1629 warnings.push(error.to_string());
1630 notices.push(InstructionNotice {
1631 path: Some(path.clone()),
1632 scope: InstructionScope::Global,
1633 origin: InstructionOrigin::Claude,
1634 action: InstructionAction::Skipped,
1635 bytes_kept: 0,
1636 bytes_dropped: 0,
1637 tokens_kept: 0,
1638 tokens_dropped: 0,
1639 limit: error.kind(),
1640 fallback_selected: None,
1641 detail: error.detail(),
1642 });
1643 }
1644 }
1645 }
1646 }
1647
1648 let mut ctx = ProjectContext::empty(workspace.to_path_buf());
1649 ctx.warnings = warnings;
1650 ctx.notices = notices;
1651 if let Some((path, content, origin)) = chosen {
1652 if let Some(preferred) = global_preferred_skipped.as_ref()
1653 && let Some(skipped) = ctx
1654 .notices
1655 .iter_mut()
1656 .find(|notice| notice.path.as_ref() == Some(preferred))
1657 {
1658 skipped.fallback_selected = Some(relative_label(home, &path));
1659 }
1660 let content = retain_file_content(
1661 content,
1662 InstructionScope::Global,
1663 origin,
1664 Some(&path),
1665 &mut ctx.notices,
1666 );
1667 let canonical = fs::canonicalize(&path).ok();
1668 if let Some(canonical) = canonical.as_ref() {
1669 loaded.push(canonical.clone());
1670 }
1671 let mut segment = InstructionSegment::new(
1672 InstructionScope::Global,
1673 origin,
1674 Some(path.clone()),
1675 content,
1676 );
1677 segment.canonical_path = canonical;
1678 segment.label = Some(relative_label(home, &path));
1679 ctx.instruction_segments = vec![segment];
1680 ctx.source_path = Some(path);
1681 ctx.rebuild_joined_instructions();
1682 }
1683
1684 if ctx.instruction_segments.is_empty() && ctx.warnings.is_empty() && ctx.notices.is_empty() {
1685 return None;
1686 }
1687 Some(ctx)
1688 }
1689
1690 /// Generate ephemeral context from the project tree. Returns the generated
1691 /// content on success without writing workspace files.
1692 fn generate_ephemeral_context(workspace: &Path) -> Option<String> {
1693 let overview = generate_bounded_project_overview(workspace)?;
1694
1695 Some(format!(
1696 "# Project Context (Auto-generated, ephemeral)\n\n\
1697 > This context was generated in memory by Codewhale.\n\
1698 > No .codewhale/instructions.md file was written.\n\n\
1699 {overview}"
1700 ))
1701 }
1702
1703 /// Load a context file with size checking; links must resolve inside its scope root.
1704 fn load_context_file(root: &Path, path: &Path) -> Result<String, ProjectContextError> {
1705 load_context_file_limited(root, path, DEFAULT_FILE_MAX_BYTES)
1706 }
1707
1708 fn load_context_file_limited(
1709 root: &Path,
1710 path: &Path,
1711 cap: u64,
1712 ) -> Result<String, ProjectContextError> {
1713 let file =
1714 codewhale_util::fs_confined::open_read_linked_within(root, path).map_err(|source| {
1715 ProjectContextError::Read {
1716 path: path.to_path_buf(),
1717 source,
1718 }
1719 })?;
1720 read_context_file(file, path, cap)
1721 }
1722
1723 fn read_context_file(file: fs::File, path: &Path, cap: u64) -> Result<String, ProjectContextError> {
1724 let metadata = file
1725 .metadata()
1726 .map_err(|source| ProjectContextError::Metadata {
1727 path: path.to_path_buf(),
1728 source,
1729 })?;
1730 if metadata.len() > cap {
1731 return Err(ProjectContextError::TooLarge {
1732 path: path.to_path_buf(),
1733 size: metadata.len(),
1734 max: usize::try_from(cap).unwrap_or(usize::MAX),
1735 });
1736 }
1737
1738 let mut bytes = Vec::new();
1739 file.take(cap.min(DEFAULT_FILE_MAX_BYTES).saturating_add(1))
1740 .read_to_end(&mut bytes)
1741 .map_err(|source| ProjectContextError::Read {
1742 path: path.to_path_buf(),
1743 source,
1744 })?;
1745 if bytes.len() as u64 > cap {
1746 return Err(ProjectContextError::TooLarge {
1747 path: path.to_path_buf(),
1748 size: bytes.len() as u64,
1749 max: cap as usize,
1750 });
1751 }
1752 let content = String::from_utf8(bytes).map_err(|error| ProjectContextError::Read {
1753 path: path.to_path_buf(),
1754 source: std::io::Error::new(std::io::ErrorKind::InvalidData, error),
1755 })?;
1756
1757 // Basic validation
1758 if content.trim().is_empty() {
1759 return Err(ProjectContextError::Empty {
1760 path: path.to_path_buf(),
1761 });
1762 }
1763
1764 Ok(content)
1765 }
1766
1767 fn context_candidate_exists(path: &Path) -> bool {
1768 fs::symlink_metadata(path).is_ok_and(|metadata| {
1769 let file_type = metadata.file_type();
1770 file_type.is_file() || file_type.is_symlink()
1771 })
1772 }
1773
1774 /// Scan a rules directory for `.md` files and load them in filename order.
1775 /// Missing or unreadable directories return nothing (no error).
1776 /// Each file is verified through `load_context_file` (size check, symlink safety).
1777 ///
1778 /// A directory beyond [`MAX_RULES_FILES`] used to be truncated with a
1779 /// `tracing::warn!` only, which made an over-cap workspace look like it had
1780 /// fewer rules than it does. The overflow is now a reported skip.
1781 fn load_rules_from_dir(
1782 workspace: &Path,
1783 rules_dir_name: &str,
1784 file_max_bytes: u64,
1785 ) -> RulesDirLoad {
1786 let rules_dir = workspace.join(rules_dir_name);
1787 let mut out = RulesDirLoad {
1788 entries: Vec::new(),
1789 notices: Vec::new(),
1790 };
1791
1792 // Refuse a symlinked rules directory: the real .md files behind it
1793 // would pass per-file is_symlink checks and be read from outside the
1794 // workspace subtree — same escape class as #417.
1795 if fs::symlink_metadata(&rules_dir)
1796 .map(|m| m.file_type().is_symlink())
1797 .unwrap_or(false)
1798 {
1799 tracing::warn!(
1800 target: "project_context",
1801 dir = %rules_dir.display(),
1802 "Refusing symlinked rules directory"
1803 );
1804 out.notices.push(InstructionNotice {
1805 path: Some(rules_dir),
1806 scope: InstructionScope::Project,
1807 origin: InstructionOrigin::Rules,
1808 action: InstructionAction::Skipped,
1809 bytes_kept: 0,
1810 bytes_dropped: 0,
1811 tokens_kept: 0,
1812 tokens_dropped: 0,
1813 limit: InstructionLimit::None,
1814 fallback_selected: None,
1815 detail: Some(InstructionDetail::SymlinkedRulesDir),
1816 });
1817 return out;
1818 }
1819
1820 let dir_iter = match fs::read_dir(&rules_dir) {
1821 Ok(iter) => iter,
1822 Err(_) => return out,
1823 };
1824
1825 let mut file_paths: Vec<PathBuf> = Vec::new();
1826 for entry in dir_iter.flatten() {
1827 let path = entry.path();
1828 if path.extension().is_some_and(|ext| ext == "md") && context_candidate_exists(&path) {
1829 file_paths.push(path);
1830 }
1831 }
1832
1833 // Sort by filename for deterministic order
1834 file_paths.sort_by(|a, b| {
1835 a.file_name()
1836 .unwrap_or_default()
1837 .cmp(b.file_name().unwrap_or_default())
1838 });
1839
1840 // Enforce per-directory cap, reporting the files it drops.
1841 if file_paths.len() > MAX_RULES_FILES {
1842 tracing::warn!(
1843 target: "project_context",
1844 dir = %rules_dir.display(),
1845 total = file_paths.len(),
1846 cap = MAX_RULES_FILES,
1847 "Truncating rules directory to cap"
1848 );
1849 for path in file_paths.iter().skip(MAX_RULES_FILES) {
1850 out.notices.push(InstructionNotice {
1851 path: Some(path.clone()),
1852 scope: InstructionScope::Project,
1853 origin: InstructionOrigin::Rules,
1854 action: InstructionAction::Skipped,
1855 bytes_kept: 0,
1856 bytes_dropped: file_len(path).unwrap_or(0),
1857 tokens_kept: 0,
1858 tokens_dropped: 0,
1859 limit: InstructionLimit::RulesCap,
1860 fallback_selected: None,
1861 detail: Some(InstructionDetail::RulesCap {
1862 max_files: MAX_RULES_FILES,
1863 }),
1864 });
1865 }
1866 file_paths.truncate(MAX_RULES_FILES);
1867 }
1868
1869 for path in file_paths {
1870 match load_context_file_limited(workspace, &path, file_max_bytes) {
1871 Ok(content) => {
1872 tracing::info!(
1873 "Loaded project rule from {} ({} bytes)",
1874 path.display(),
1875 content.len()
1876 );
1877 let content = retain_file_content(
1878 content,
1879 InstructionScope::Project,
1880 InstructionOrigin::Rules,
1881 Some(&path),
1882 &mut out.notices,
1883 );
1884 out.entries.push((path, content));
1885 }
1886 Err(error) => {
1887 tracing::warn!(
1888 target: "project_context",
1889 ?error,
1890 ?path,
1891 "Skipping unreadable rules file"
1892 );
1893 out.notices.push(InstructionNotice {
1894 path: Some(path.clone()),
1895 scope: InstructionScope::Project,
1896 origin: InstructionOrigin::Rules,
1897 action: InstructionAction::Skipped,
1898 bytes_kept: 0,
1899 bytes_dropped: file_len(&path).unwrap_or(0),
1900 tokens_kept: 0,
1901 tokens_dropped: 0,
1902 limit: error.kind(),
1903 fallback_selected: None,
1904 detail: error.detail(),
1905 });
1906 }
1907 }
1908 }
1909
1910 out
1911 }
1912
1913 /// User-owned global instructions may intentionally resolve through links.
1914 #[cfg(all(test, unix))]
1915 fn load_global_context_file(path: &Path) -> Result<String, ProjectContextError> {
1916 load_global_context_file_limited(path, DEFAULT_FILE_MAX_BYTES)
1917 }
1918
1919 fn load_global_context_file_limited(path: &Path, cap: u64) -> Result<String, ProjectContextError> {
1920 let file = codewhale_util::fs_confined::open_user_read(path).map_err(|source| {
1921 ProjectContextError::Read {
1922 path: path.to_path_buf(),
1923 source,
1924 }
1925 })?;
1926 read_context_file(file, path, cap)
1927 }
1928
1929 /// Create a default AGENTS.md file for a project
1930 pub fn create_default_agents_md(workspace: &Path) -> std::io::Result<PathBuf> {
1931 let agents_path = workspace.join("AGENTS.md");
1932
1933 let default_content = r#"# Project Agent Instructions
1934
1935 This file provides guidance to AI agents (Codewhale, Claude Code, etc.) when working with code in this repository.
1936
1937 ## File Location
1938
1939 Save this file as `AGENTS.md` in your project root so the CLI can load it automatically.
1940
1941 ## Build and Development Commands
1942
1943 ```bash
1944 # Build
1945 # cargo build # Rust projects
1946 # npm run build # Node.js projects
1947 # python -m build # Python projects
1948
1949 # Test
1950 # cargo test # Rust
1951 # npm test # Node.js
1952 # pytest # Python
1953
1954 # Lint and Format
1955 # cargo fmt && cargo clippy # Rust
1956 # npm run lint # Node.js
1957 # ruff check . # Python
1958 ```
1959
1960 ## Architecture Overview
1961
1962 <!-- Describe your project's high-level architecture here -->
1963 <!-- Focus on the "big picture" that requires reading multiple files to understand -->
1964
1965 ### Key Components
1966
1967 <!-- List and describe the main components/modules -->
1968
1969 ### Data Flow
1970
1971 <!-- Describe how data flows through the system -->
1972
1973 ## Configuration Files
1974
1975 <!-- List important configuration files and their purposes -->
1976
1977 ## Extension Points
1978
1979 <!-- Describe how to extend the codebase (add new features, tools, etc.) -->
1980
1981 ## Commit Messages
1982
1983 Use conventional commits: `feat:`, `fix:`, `docs:`, `refactor:`, `test:`, `chore:`
1984 "#;
1985
1986 fs::write(&agents_path, default_content)?;
1987 Ok(agents_path)
1988 }
1989
1990 // === Effective instruction-source listing (#6168) ===
1991
1992 /// Which layer of the instruction stack a source belongs to.
1993 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1994 pub enum InstructionSourceKind {
1995 /// Chain candidate (`AGENTS.md`, `.codewhale/instructions.md`, opted-in
1996 /// foreign files) in a repository-root → workspace scope directory.
1997 Project,
1998 /// `.md` file inside a rules directory (`.codewhale/rules`, opted-in
1999 /// foreign rules dirs) at workspace scope.
2000 Rule,
2001 /// User-level fallback (`~/.codewhale/AGENTS.md` and friends).
2002 Global,
2003 /// File selected by the bounded foreign-fragment loader
2004 /// (`codewhale_core::fragments`) for an opted-in format.
2005 Fragment,
2006 /// Configured `instructions = [...]` file (#454).
2007 Configured,
2008 /// `.codewhale/constitution.json` authority policy.
2009 Constitution,
2010 /// Present but deliberately never loaded (deprecated `WHALE.md`).
2011 Ignored,
2012 }
2013
2014 /// Whether the prompt assembly actually consumed the file.
2015 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
2016 pub enum InstructionSourceStatus {
2017 /// Read and merged into the assembled instructions.
2018 Loaded,
2019 /// Exists, but a higher-priority candidate in the same scope won.
2020 Shadowed,
2021 /// Exists but the loader refused, could not read, or skipped it
2022 /// (empty, oversized, over the per-directory rules cap).
2023 Skipped,
2024 /// Candidate path the loader checks; nothing is there.
2025 Missing,
2026 }
2027
2028 /// One instruction-source candidate or loaded file, for the
2029 /// workspace-instructions listing route.
2030 #[derive(Debug, Clone)]
2031 pub struct InstructionSourceInfo {
2032 pub kind: InstructionSourceKind,
2033 /// Scope directory the candidate belongs to: the chain directory for
2034 /// `Project`, the workspace for `Rule`/`Fragment`/`Configured`, the home
2035 /// directory for `Global`.
2036 pub scope_dir: PathBuf,
2037 /// Candidate or actual file path, as the loader resolves it.
2038 pub path: PathBuf,
2039 /// `symlink_metadata` saw a file or symlink (same check the loader runs).
2040 pub exists: bool,
2041 pub status: InstructionSourceStatus,
2042 /// File size in bytes when it could be stat'd.
2043 pub bytes: Option<u64>,
2044 /// Loader warning produced for this path, when one exists.
2045 pub warning: Option<String>,
2046 }
2047
2048 fn file_len(path: &Path) -> Option<u64> {
2049 fs::metadata(path).ok().map(|m| m.len())
2050 }
2051
2052 fn push_candidate_entry(
2053 sources: &mut Vec<InstructionSourceInfo>,
2054 kind: InstructionSourceKind,
2055 scope_dir: &Path,
2056 path: PathBuf,
2057 scope_loaded: &mut bool,
2058 loaded: Option<&mut Vec<PathBuf>>,
2059 load: impl FnOnce(&Path) -> Result<String, ProjectContextError>,
2060 ) {
2061 let exists = context_candidate_exists(&path);
2062 let (status, warning) = if !exists {
2063 (InstructionSourceStatus::Missing, None)
2064 } else if *scope_loaded {
2065 (InstructionSourceStatus::Shadowed, None)
2066 } else if loaded
2067 .as_deref()
2068 .is_some_and(|loaded| is_duplicate(&path, loaded))
2069 {
2070 *scope_loaded = true;
2071 (
2072 InstructionSourceStatus::Skipped,
2073 Some("already loaded by a wider scope".to_string()),
2074 )
2075 } else {
2076 match load(&path) {
2077 Ok(_) => {
2078 *scope_loaded = true;
2079 if let Some(loaded) = loaded
2080 && let Ok(canonical) = fs::canonicalize(&path)
2081 {
2082 loaded.push(canonical);
2083 }
2084 (InstructionSourceStatus::Loaded, None)
2085 }
2086 Err(error) => (InstructionSourceStatus::Skipped, Some(error.to_string())),
2087 }
2088 };
2089 sources.push(InstructionSourceInfo {
2090 kind,
2091 scope_dir: scope_dir.to_path_buf(),
2092 exists,
2093 bytes: file_len(&path),
2094 path,
2095 status,
2096 warning,
2097 });
2098 }
2099
2100 /// Enumerate the effective instruction sources for `workspace` (#6168).
2101 ///
2102 /// Mirrors the loaders above — same candidate order, same existence and
2103 /// readability checks — so the listing reports what prompt assembly actually
2104 /// picks up: precedence, shadowing, opt-in imports, and refusal warnings.
2105 /// Read-only; it never creates or modifies files. `configured` is the
2106 /// resolved `instructions = [...]` array (`Config::instructions_paths`);
2107 /// `home_dir` gates the global layer exactly as
2108 /// `load_project_context_with_parents_and_home` does.
2109 ///
2110 /// Known limit: statuses describe file selection, not the per-scope token
2111 /// budget — `assemble_instruction_block` can still trim or drop a loaded
2112 /// source at render time without changing its `Loaded` status here. The
2113 /// trim/skip notices on `ProjectContext` are the budget-side truth.
2114 #[must_use]
2115 #[cfg(any(test, feature = "test-support"))]
2116 pub fn project_instruction_sources(
2117 workspace: &Path,
2118 home_dir: Option<&Path>,
2119 configured: &[PathBuf],
2120 ) -> Vec<InstructionSourceInfo> {
2121 project_instruction_sources_with_settings(
2122 workspace,
2123 &InstructionSettings {
2124 home: home_dir.map(Path::to_path_buf),
2125 ..Default::default()
2126 },
2127 configured,
2128 )
2129 }
2130
2131 pub fn project_instruction_sources_with_settings(
2132 workspace: &Path,
2133 settings: &InstructionSettings,
2134 configured: &[PathBuf],
2135 ) -> Vec<InstructionSourceInfo> {
2136 let home_dir = settings.home.as_deref();
2137 let imports = &settings.imports;
2138 let workspace = canonicalize_workspace_or_keep(workspace);
2139 let mut sources = Vec::new();
2140 let mut loaded = Vec::new();
2141 let _ = load_global_agents_context(
2142 &workspace,
2143 home_dir,
2144 settings.claude_fallback() || imports.is_enabled(ForeignInstructionFormat::Claude),
2145 settings.file_max_bytes(),
2146 &mut loaded,
2147 );
2148
2149 // Repository-root → workspace instruction chain. Same dir order the
2150 // loader assembles, so wider scopes list first.
2151 let repo_root = find_git_root(&workspace);
2152 for dir in context_chain_dirs(&workspace, repo_root.as_deref(), home_dir) {
2153 let whale = dir.join(DEPRECATED_WHALE_FILENAME);
2154 if context_candidate_exists(&whale) {
2155 sources.push(InstructionSourceInfo {
2156 kind: InstructionSourceKind::Ignored,
2157 scope_dir: dir.clone(),
2158 path: whale.clone(),
2159 exists: true,
2160 status: InstructionSourceStatus::Skipped,
2161 bytes: file_len(&whale),
2162 warning: Some(WHALE_IGNORED_WARNING.to_string()),
2163 });
2164 }
2165 let claude_imported = imports.is_enabled(ForeignInstructionFormat::Claude);
2166 let mut scope_loaded = false;
2167 for filename in context_files_for(imports)
2168 .into_iter()
2169 .filter(|filename| !CLAUDE_CONTEXT_FILES.contains(filename))
2170 {
2171 push_candidate_entry(
2172 &mut sources,
2173 InstructionSourceKind::Project,
2174 &dir,
2175 dir.join(filename),
2176 &mut scope_loaded,
2177 Some(&mut loaded),
2178 |path| load_context_file_limited(&dir, path, settings.file_max_bytes()),
2179 );
2180 }
2181 let mut claude_loaded = !claude_imported && scope_loaded;
2182 if claude_imported || settings.claude_fallback() {
2183 for filename in CLAUDE_CONTEXT_FILES {
2184 push_candidate_entry(
2185 &mut sources,
2186 InstructionSourceKind::Project,
2187 &dir,
2188 dir.join(filename),
2189 &mut claude_loaded,
2190 Some(&mut loaded),
2191 |path| load_context_file_limited(&dir, path, settings.file_max_bytes()),
2192 );
2193 }
2194 }
2195 }
2196
2197 // Workspace-scope rules directories — the chain loader never reads
2198 // ancestor rules, so only the workspace contributes them.
2199 for rules_dir_name in rules_dirs_for(imports) {
2200 let rules_dir = workspace.join(rules_dir_name);
2201 if fs::symlink_metadata(&rules_dir)
2202 .map(|m| m.file_type().is_symlink())
2203 .unwrap_or(false)
2204 {
2205 // Same refusal as `load_rules_from_dir`, surfaced rather than
2206 // logged-and-dropped.
2207 sources.push(InstructionSourceInfo {
2208 kind: InstructionSourceKind::Rule,
2209 scope_dir: workspace.clone(),
2210 path: rules_dir,
2211 exists: true,
2212 status: InstructionSourceStatus::Skipped,
2213 bytes: None,
2214 warning: Some("refusing symlinked rules directory".to_string()),
2215 });
2216 continue;
2217 }
2218 let Ok(dir_entries) = fs::read_dir(&rules_dir) else {
2219 continue;
2220 };
2221 let mut file_paths: Vec<PathBuf> = dir_entries
2222 .flatten()
2223 .map(|entry| entry.path())
2224 .filter(|path| {
2225 path.extension().is_some_and(|ext| ext == "md") && context_candidate_exists(path)
2226 })
2227 .collect();
2228 file_paths.sort_by(|a, b| {
2229 a.file_name()
2230 .unwrap_or_default()
2231 .cmp(b.file_name().unwrap_or_default())
2232 });
2233 for (index, path) in file_paths.into_iter().enumerate() {
2234 let (status, warning) = if index >= MAX_RULES_FILES {
2235 (
2236 InstructionSourceStatus::Skipped,
2237 Some(format!(
2238 "beyond the per-directory rules cap of {MAX_RULES_FILES} files"
2239 )),
2240 )
2241 } else {
2242 match load_context_file_limited(&workspace, &path, settings.file_max_bytes()) {
2243 Ok(_) => (InstructionSourceStatus::Loaded, None),
2244 Err(error) => (InstructionSourceStatus::Skipped, Some(error.to_string())),
2245 }
2246 };
2247 sources.push(InstructionSourceInfo {
2248 kind: InstructionSourceKind::Rule,
2249 scope_dir: workspace.clone(),
2250 path: path.clone(),
2251 exists: true,
2252 status,
2253 bytes: file_len(&path),
2254 warning,
2255 });
2256 }
2257 }
2258
2259 // User-level fallback layer.
2260 if let Some(home) = home_dir {
2261 for relative in legacy_global_whale_relative_paths() {
2262 let path = join_relative_components(home, relative);
2263 if context_candidate_exists(&path) {
2264 sources.push(InstructionSourceInfo {
2265 kind: InstructionSourceKind::Ignored,
2266 scope_dir: home.to_path_buf(),
2267 path: path.clone(),
2268 exists: true,
2269 status: InstructionSourceStatus::Skipped,
2270 bytes: file_len(&path),
2271 warning: Some(WHALE_IGNORED_WARNING.to_string()),
2272 });
2273 }
2274 }
2275 let mut scope_loaded = false;
2276 for relative in global_context_relative_paths() {
2277 push_candidate_entry(
2278 &mut sources,
2279 InstructionSourceKind::Global,
2280 home,
2281 join_relative_components(home, relative),
2282 &mut scope_loaded,
2283 None,
2284 |path| load_global_context_file_limited(path, settings.file_max_bytes()),
2285 );
2286 }
2287 if settings.claude_fallback() || imports.is_enabled(ForeignInstructionFormat::Claude) {
2288 push_candidate_entry(
2289 &mut sources,
2290 InstructionSourceKind::Global,
2291 home,
2292 home.join(".claude/CLAUDE.md"),
2293 &mut scope_loaded,
2294 None,
2295 |path| load_global_context_file_limited(path, settings.file_max_bytes()),
2296 );
2297 }
2298 }
2299
2300 // Opted-in foreign fragments — enumerate the declared candidates, then
2301 // mark the files the bounded loader's own selection walk picks.
2302 let fragment_candidates = fragment_candidates_for(imports);
2303 let fragment_loaded = |path: &Path| {
2304 codewhale_util::fs_confined::open_read(&workspace, path)
2305 .ok()
2306 .and_then(codewhale_core::fragments::read_project_instruction_file)
2307 .is_some()
2308 };
2309 let selected: std::collections::BTreeSet<PathBuf> =
2310 codewhale_core::fragments::selected_project_instruction_candidate_files(
2311 &workspace,
2312 &fragment_candidates,
2313 )
2314 .into_iter()
2315 .collect();
2316 let mut emitted = std::collections::BTreeSet::new();
2317 for candidate in &fragment_candidates {
2318 let path = workspace.join(candidate);
2319 if !path.exists() {
2320 sources.push(InstructionSourceInfo {
2321 kind: InstructionSourceKind::Fragment,
2322 scope_dir: workspace.clone(),
2323 path,
2324 exists: false,
2325 status: InstructionSourceStatus::Missing,
2326 bytes: None,
2327 warning: None,
2328 });
2329 continue;
2330 }
2331 // A directory candidate's loadable files are the selected entries
2332 // underneath it; report those rather than the directory itself.
2333 let members: Vec<PathBuf> = selected
2334 .iter()
2335 .filter(|file| file.starts_with(&path))
2336 .cloned()
2337 .collect();
2338 if path.is_dir() {
2339 if members.is_empty() {
2340 sources.push(InstructionSourceInfo {
2341 kind: InstructionSourceKind::Fragment,
2342 scope_dir: workspace.clone(),
2343 path,
2344 exists: true,
2345 status: InstructionSourceStatus::Skipped,
2346 bytes: None,
2347 warning: Some(
2348 "no loadable .md files selected under this directory".to_string(),
2349 ),
2350 });
2351 }
2352 for file in members {
2353 emitted.insert(file.clone());
2354 let loaded = fragment_loaded(&file);
2355 sources.push(InstructionSourceInfo {
2356 kind: InstructionSourceKind::Fragment,
2357 scope_dir: workspace.clone(),
2358 path: file.clone(),
2359 exists: true,
2360 status: if loaded {
2361 InstructionSourceStatus::Loaded
2362 } else {
2363 InstructionSourceStatus::Skipped
2364 },
2365 bytes: file_len(&file),
2366 warning: None,
2367 });
2368 }
2369 } else {
2370 emitted.insert(path.clone());
2371 let selected_file = selected.contains(&path);
2372 let loaded = selected_file && fragment_loaded(&path);
2373 sources.push(InstructionSourceInfo {
2374 kind: InstructionSourceKind::Fragment,
2375 scope_dir: workspace.clone(),
2376 path: path.clone(),
2377 exists: true,
2378 status: if loaded {
2379 InstructionSourceStatus::Loaded
2380 } else if selected_file {
2381 InstructionSourceStatus::Skipped
2382 } else {
2383 // Exists but not selected — e.g. a symlink the walk refuses.
2384 InstructionSourceStatus::Skipped
2385 },
2386 bytes: file_len(&path),
2387 warning: if selected_file && !loaded {
2388 Some("selected but empty or unreadable".to_string())
2389 } else {
2390 None
2391 },
2392 });
2393 }
2394 }
2395 // Selected files not attributed to a listed candidate (nested rules dir
2396 // members) still get reported.
2397 for file in selected.iter().filter(|file| !emitted.contains(*file)) {
2398 let loaded = fragment_loaded(file);
2399 sources.push(InstructionSourceInfo {
2400 kind: InstructionSourceKind::Fragment,
2401 scope_dir: workspace.clone(),
2402 path: file.clone(),
2403 exists: true,
2404 status: if loaded {
2405 InstructionSourceStatus::Loaded
2406 } else {
2407 InstructionSourceStatus::Skipped
2408 },
2409 bytes: file_len(file),
2410 warning: None,
2411 });
2412 }
2413
2414 // Configured `instructions = [...]` files (#454) — resolved paths, in
2415 // declared order. The renderer skips missing/empty files with a warning.
2416 for path in configured {
2417 let exists = context_candidate_exists(path);
2418 let (status, warning) = if is_duplicate(path, &loaded) {
2419 (
2420 InstructionSourceStatus::Skipped,
2421 Some("already loaded by another instruction source".to_string()),
2422 )
2423 } else {
2424 match load_global_context_file_limited(path, settings.file_max_bytes()) {
2425 Ok(content) if !content.trim().is_empty() => {
2426 if let Ok(canonical) = fs::canonicalize(path) {
2427 loaded.push(canonical);
2428 }
2429 (InstructionSourceStatus::Loaded, None)
2430 }
2431 Ok(_) => (
2432 InstructionSourceStatus::Skipped,
2433 Some("empty instructions file".to_string()),
2434 ),
2435 Err(error) => (
2436 InstructionSourceStatus::Skipped,
2437 Some(format!("unreadable instructions file: {error}")),
2438 ),
2439 }
2440 };
2441 sources.push(InstructionSourceInfo {
2442 kind: InstructionSourceKind::Configured,
2443 scope_dir: workspace.clone(),
2444 path: path.clone(),
2445 exists,
2446 status,
2447 bytes: file_len(path),
2448 warning,
2449 });
2450 }
2451
2452 // `.codewhale/constitution.json`, workspace → repository root. The loader
2453 // stops at the first existing candidate whether it parses or not, so
2454 // later candidates — even ones that exist — are never evaluated.
2455 let (_block, constitution_source, _warnings) = load_repo_constitution_block(&workspace);
2456 let mut seen_existing = false;
2457 for path in repo_constitution_candidate_paths(&workspace) {
2458 let exists = context_candidate_exists(&path);
2459 let status = if !exists {
2460 InstructionSourceStatus::Missing
2461 } else if seen_existing {
2462 InstructionSourceStatus::Shadowed
2463 } else {
2464 seen_existing = true;
2465 if constitution_source.as_deref() == Some(path.as_path()) {
2466 InstructionSourceStatus::Loaded
2467 } else {
2468 InstructionSourceStatus::Skipped
2469 }
2470 };
2471 sources.push(InstructionSourceInfo {
2472 kind: InstructionSourceKind::Constitution,
2473 scope_dir: workspace.clone(),
2474 path: path.clone(),
2475 exists,
2476 status,
2477 bytes: file_len(&path),
2478 warning: None,
2479 });
2480 }
2481
2482 sources
2483 }
2484
2485 // === Unit Tests ===
2486
2487 #[cfg(test)]
2488 mod tests {
2489 use super::*;
2490 use tempfile::tempdir;
2491
2492 #[cfg(unix)]
2493 #[test]
2494 fn confined_global_context_refuses_a_directory_target() {
2495 let home = tempdir().unwrap();
2496 let path = home.path().join("AGENTS.md");
2497 std::os::unix::fs::symlink("/", &path).unwrap();
2498 assert!(load_global_context_file(&path).is_err());
2499 }
2500
2501 #[cfg(unix)]
2502 #[test]
2503 fn confined_context_refuses_linked_parent_directories() {
2504 for directory in [".codewhale", ".deepseek"] {
2505 let workspace = tempdir().unwrap();
2506 let outside = tempdir().unwrap();
2507 fs::write(
2508 outside.path().join("instructions.md"),
2509 "separate instructions",
2510 )
2511 .unwrap();
2512 fs::create_dir(outside.path().join("rules")).unwrap();
2513 fs::write(outside.path().join("rules/rule.md"), "separate rule").unwrap();
2514 fs::write(
2515 outside.path().join("constitution.json"),
2516 r#"{"purpose":"separate purpose"}"#,
2517 )
2518 .unwrap();
2519 std::os::unix::fs::symlink(outside.path(), workspace.path().join(directory)).unwrap();
2520 let context = load_project_context_with_imports(
2521 workspace.path(),
2522 &ForeignInstructionImports::none(),
2523 );
2524 assert!(context.instructions.is_none());
2525 assert!(context.rules_block.is_none());
2526 assert!(load_repo_constitution_block(workspace.path()).0.is_none());
2527 }
2528 }
2529
2530 #[test]
2531 fn test_load_project_context_empty() {
2532 let tmp = tempdir().expect("tempdir");
2533 let ctx = load_project_context(tmp.path());
2534
2535 assert!(!ctx.has_instructions());
2536 assert!(ctx.source_path.is_none());
2537 }
2538
2539 #[test]
2540 fn test_load_project_context_agents_md() {
2541 let tmp = tempdir().expect("tempdir");
2542 let agents_path = tmp.path().join("AGENTS.md");
2543 fs::write(&agents_path, "# Test Instructions\n\nFollow these rules.").expect("write");
2544
2545 let ctx = load_project_context(tmp.path());
2546
2547 assert!(ctx.has_instructions());
2548 assert!(
2549 ctx.instructions
2550 .as_ref()
2551 .unwrap()
2552 .contains("Test Instructions")
2553 );
2554 assert_eq!(ctx.source_path, Some(agents_path));
2555 }
2556
2557 #[cfg(unix)]
2558 #[test]
2559 fn project_context_rejects_symlinked_agents_md() {
2560 let workspace = tempdir().expect("workspace tempdir");
2561 let outside = tempdir().expect("outside tempdir");
2562 let outside_agents = outside.path().join("AGENTS.md");
2563 fs::write(&outside_agents, "outside instructions").expect("write outside agents");
2564 std::os::unix::fs::symlink(&outside_agents, workspace.path().join("AGENTS.md"))
2565 .expect("symlink agents");
2566
2567 let ctx = load_project_context(workspace.path());
2568
2569 assert!(
2570 !ctx.has_instructions(),
2571 "symlinked project instructions must not be loaded: {:?}",
2572 ctx.instructions
2573 );
2574 assert!(
2575 ctx.warnings.iter().any(|w| w.contains("symlinked")),
2576 "expected symlink warning, got {:?}",
2577 ctx.warnings
2578 );
2579 }
2580
2581 #[cfg(unix)]
2582 #[test]
2583 fn project_context_follows_agents_md_linked_within_the_workspace() {
2584 let workspace = tempdir().expect("workspace tempdir");
2585 let operator = workspace.path().join("ops/operator");
2586 fs::create_dir_all(&operator).expect("mkdir operator");
2587 fs::write(operator.join("AGENTS.md"), "Shared operator rules").expect("write agents");
2588 std::os::unix::fs::symlink("ops/operator/AGENTS.md", workspace.path().join("AGENTS.md"))
2589 .expect("symlink agents");
2590
2591 let ctx = load_project_context(workspace.path());
2592
2593 assert!(
2594 ctx.instructions
2595 .as_deref()
2596 .is_some_and(|text| text.contains("Shared operator rules")),
2597 "an in-workspace AGENTS.md link must load: {:?}",
2598 ctx.warnings
2599 );
2600 assert!(ctx.warnings.is_empty(), "{:?}", ctx.warnings);
2601 }
2602
2603 #[test]
2604 fn test_load_project_context_priority() {
2605 let tmp = tempdir().expect("tempdir");
2606
2607 // Create both files - AGENTS.md should take priority
2608 fs::write(tmp.path().join("AGENTS.md"), "AGENTS content").expect("write");
2609 let claude_dir = tmp.path().join(".claude");
2610 fs::create_dir(&claude_dir).expect("mkdir");
2611 fs::write(claude_dir.join("instructions.md"), "CLAUDE content").expect("write");
2612
2613 let ctx = load_project_context(tmp.path());
2614
2615 assert!(ctx.has_instructions());
2616 assert!(
2617 ctx.instructions
2618 .as_ref()
2619 .unwrap()
2620 .contains("AGENTS content")
2621 );
2622 }
2623
2624 #[test]
2625 fn test_load_project_context_hidden_dir() {
2626 let tmp = tempdir().expect("tempdir");
2627 let hidden_dir = tmp.path().join(".deepseek");
2628 fs::create_dir(&hidden_dir).expect("mkdir");
2629 fs::write(hidden_dir.join("instructions.md"), "Hidden instructions").expect("write");
2630
2631 let ctx = load_project_context(tmp.path());
2632
2633 assert!(ctx.has_instructions());
2634 assert!(
2635 ctx.instructions
2636 .as_ref()
2637 .unwrap()
2638 .contains("Hidden instructions")
2639 );
2640 }
2641
2642 #[test]
2643 fn test_as_system_block() {
2644 let tmp = tempdir().expect("tempdir");
2645 let agents_path = tmp.path().join("AGENTS.md");
2646 fs::write(&agents_path, "Test content").expect("write");
2647
2648 let ctx = load_project_context(tmp.path());
2649 let block = ctx.as_system_block().expect("block");
2650
2651 assert!(block.contains("<project_instructions"));
2652 assert!(block.contains("Test content"));
2653 assert!(block.contains("</project_instructions>"));
2654 }
2655
2656 #[test]
2657 fn project_instructions_source_label_falls_back_to_project() {
2658 use crate::project_context::project_instructions_source_label;
2659 assert_eq!(
2660 project_instructions_source_label(None),
2661 "project",
2662 "a missing source path keeps the historical literal label"
2663 );
2664 assert_eq!(
2665 project_instructions_source_label(Some(std::path::Path::new("/etc/AGENTS.md"))),
2666 "AGENTS.md"
2667 );
2668 }
2669
2670 #[test]
2671 fn project_instructions_source_is_file_name_not_absolute_path() {
2672 // The source label sits inside the pinned system prompt: loading the
2673 // same AGENTS.md from a different directory must leave the
2674 // instructions block byte-identical, so a move emits no spurious
2675 // `<context_update>` history append and no absolute path enters a
2676 // provider-bound label. Scope note: ancestor-chain and project-rule
2677 // labels are repo-relative for the same reason; this test pins the
2678 // file-name spelling of the workspace-level block.
2679 let dir_a = tempdir().expect("tempdir a");
2680 let dir_b = tempdir().expect("tempdir b");
2681 fs::write(dir_a.path().join("AGENTS.md"), "Pinned content").expect("write a");
2682 fs::write(dir_b.path().join("AGENTS.md"), "Pinned content").expect("write b");
2683
2684 let block_a = load_project_context(dir_a.path())
2685 .as_system_block()
2686 .expect("block a");
2687 let block_b = load_project_context(dir_b.path())
2688 .as_system_block()
2689 .expect("block b");
2690 assert_eq!(
2691 block_a, block_b,
2692 "a directory move must not change the project instructions block"
2693 );
2694 assert!(block_a.contains("source=\"AGENTS.md\""));
2695 assert!(
2696 !block_a.contains(&dir_a.path().display().to_string()),
2697 "absolute paths must not enter prompt source labels"
2698 );
2699 }
2700
2701 #[test]
2702 fn repo_relative_source_label_falls_back_when_path_is_outside_root() {
2703 use crate::project_context::repo_relative_source_label;
2704 use std::path::Path;
2705 // The absolute fallback is an escape hatch for a path the loader
2706 // cannot place under the checkout — unreachable by construction —
2707 // so it must degrade to a displayable spelling, never panic or
2708 // invent a wrong relative label.
2709 assert_eq!(
2710 repo_relative_source_label(
2711 Path::new("/repo/crates/tui/AGENTS.md"),
2712 Some(Path::new("/repo"))
2713 ),
2714 "crates/tui/AGENTS.md"
2715 );
2716 // On unix the backslashes are literal filename bytes, on Windows they
2717 // are separators — either way the label must come out forward-slashed,
2718 // and this assertion is the only check that can see it off Windows.
2719 assert_eq!(
2720 repo_relative_source_label(
2721 Path::new("/repo/crates\\tui\\AGENTS.md"),
2722 Some(Path::new("/repo"))
2723 ),
2724 "crates/tui/AGENTS.md",
2725 "backslash separators are normalized to forward slashes"
2726 );
2727 assert_eq!(
2728 repo_relative_source_label(Path::new("/elsewhere/AGENTS.md"), Some(Path::new("/repo"))),
2729 "/elsewhere/AGENTS.md",
2730 "a path outside the root falls back to the absolute spelling"
2731 );
2732 assert_eq!(
2733 repo_relative_source_label(Path::new("/repo/AGENTS.md"), None),
2734 "/repo/AGENTS.md",
2735 "a missing root falls back to the absolute spelling"
2736 );
2737 }
2738
2739 #[test]
2740 fn chain_segment_labels_are_repo_relative_not_absolute() {
2741 let tmp = tempdir().expect("tempdir");
2742 let home = tempdir().expect("home tempdir");
2743
2744 // A two-level chain inside one checkout: the repo root carries the
2745 // wide scope, `crates/tui` the workspace scope.
2746 let repo = tmp.path().join("repo");
2747 fs::create_dir_all(repo.join(".git")).expect("mkdir .git");
2748 fs::write(repo.join(".git").join("HEAD"), "ref: refs/heads/main\n").expect("write HEAD");
2749 fs::write(repo.join("AGENTS.md"), "ROOT-SCOPE instructions").expect("write root agents");
2750
2751 let workspace = repo.join("crates").join("tui");
2752 fs::create_dir_all(&workspace).expect("mkdir workspace");
2753 fs::write(workspace.join("AGENTS.md"), "WORKSPACE-SCOPE instructions")
2754 .expect("write workspace agents");
2755
2756 let ctx = load_project_context_with_parents_and_home(&workspace, Some(home.path()));
2757 let instructions = ctx.instructions.as_ref().expect("chain instructions");
2758
2759 assert!(instructions.contains("ROOT-SCOPE instructions"));
2760 assert!(instructions.contains("WORKSPACE-SCOPE instructions"));
2761 assert!(
2762 instructions.contains("<!-- scoped instructions: crates/tui/AGENTS.md"),
2763 "the chain segment label must be repo-relative, got: {instructions}"
2764 );
2765 assert!(
2766 !instructions.contains(&tmp.path().display().to_string()),
2767 "absolute paths must not enter chain segment labels: {instructions}"
2768 );
2769 }
2770
2771 #[test]
2772 fn project_rule_labels_are_repo_relative_not_absolute() {
2773 let tmp = tempdir().expect("tempdir");
2774 let repo = tmp.path().join("repo");
2775 fs::create_dir_all(repo.join(".git")).expect("mkdir .git");
2776 fs::write(repo.join(".git").join("HEAD"), "ref: refs/heads/main\n").expect("write HEAD");
2777 let rules_dir = repo.join(".codewhale/rules");
2778 fs::create_dir_all(&rules_dir).expect("mkdir rules");
2779 fs::write(
2780 rules_dir.join("security.md"),
2781 "# Security\nNo hardcoded secrets.",
2782 )
2783 .expect("write rule");
2784
2785 let ctx = load_project_context(&repo);
2786 let rules = ctx.rules_block.as_ref().expect("rules block");
2787
2788 assert!(
2789 rules.contains("<project_rule source=\".codewhale/rules/security.md\">"),
2790 "the rule label must be repo-relative, got: {rules}"
2791 );
2792 assert!(
2793 !rules.contains(&tmp.path().display().to_string()),
2794 "absolute paths must not enter rule source labels: {rules}"
2795 );
2796 }
2797
2798 #[test]
2799 fn prompt_block_is_pinned_across_checkout_moves() {
2800 // The whole reason for repo-relative labels: the same repository
2801 // tree checked out at two different absolute locations must render
2802 // byte-identical system blocks (chain segment + rules included), so
2803 // a move or recase neither appends a spurious `<context_update>`
2804 // history entry nor invalidates the provider's prompt KV prefix.
2805 let mut moved_block: Option<String> = None;
2806 for location in ["checkout-a", "checkout-b"] {
2807 let root = tempdir().expect(location);
2808 let repo = root.path().join("repo");
2809 fs::create_dir_all(repo.join(".git")).expect("mkdir .git");
2810 fs::write(repo.join(".git").join("HEAD"), "ref: refs/heads/main\n")
2811 .expect("write HEAD");
2812 fs::write(repo.join("AGENTS.md"), "ROOT-SCOPE instructions").expect("write root");
2813
2814 let workspace = repo.join("nested");
2815 fs::create_dir_all(&workspace).expect("mkdir nested");
2816 fs::write(workspace.join("AGENTS.md"), "NESTED-SCOPE instructions")
2817 .expect("write nested");
2818 // Rules are discovered at workspace level, so the checkout tree
2819 // must carry them under the session's workspace too.
2820 let rules_dir = workspace.join(".codewhale/rules");
2821 fs::create_dir_all(&rules_dir).expect("mkdir rules");
2822 fs::write(rules_dir.join("security.md"), "No hardcoded secrets.").expect("write rule");
2823
2824 let ctx = load_project_context_with_parents_and_home(&workspace, None);
2825 let block = ctx.as_system_block().expect("system block");
2826
2827 assert!(block.contains("<!-- scoped instructions: nested/AGENTS.md"));
2828 assert!(
2829 block.contains("<project_rule source=\"nested/.codewhale/rules/security.md\">"),
2830 "rule label must be repo-relative, got: {block}"
2831 );
2832 assert!(
2833 !block.contains(&root.path().display().to_string()),
2834 "absolute paths must not enter the pinned prompt block: {block}"
2835 );
2836 if location == "checkout-a" {
2837 moved_block = Some(block);
2838 } else {
2839 assert_eq!(
2840 moved_block.as_deref(),
2841 Some(block.as_str()),
2842 "the same tree at two locations must render byte-identical blocks"
2843 );
2844 }
2845 }
2846 }
2847
2848 #[test]
2849 fn project_rule_labels_fall_back_to_workspace_relative_without_git_root() {
2850 // Outside any repository there is no root to relativize against;
2851 // the label falls back to workspace-relative spelling, which stays
2852 // stable as long as the workspace tree itself is unchanged.
2853 let tmp = tempdir().expect("tempdir");
2854 let rules_dir = tmp.path().join(".codewhale/rules");
2855 fs::create_dir_all(&rules_dir).expect("mkdir rules");
2856 fs::write(rules_dir.join("security.md"), "No hardcoded secrets.").expect("write rule");
2857
2858 let ctx = load_project_context(tmp.path());
2859 let rules = ctx.rules_block.as_ref().expect("rules block");
2860
2861 assert!(
2862 rules.contains("<project_rule source=\".codewhale/rules/security.md\">"),
2863 "the rule label must fall back to workspace-relative, got: {rules}"
2864 );
2865 assert!(
2866 !rules.contains(&tmp.path().display().to_string()),
2867 "absolute paths must not enter rule source labels: {rules}"
2868 );
2869 }
2870
2871 #[test]
2872 fn test_empty_file_warning() {
2873 let tmp = tempdir().expect("tempdir");
2874 let agents_path = tmp.path().join("AGENTS.md");
2875 fs::write(&agents_path, " \n \n ").expect("write"); // Only whitespace
2876
2877 let ctx = load_project_context(tmp.path());
2878
2879 assert!(!ctx.has_instructions());
2880 assert!(!ctx.warnings.is_empty());
2881 }
2882
2883 #[test]
2884 fn test_create_default_agents_md() {
2885 let tmp = tempdir().expect("tempdir");
2886 let path = create_default_agents_md(tmp.path()).expect("create");
2887
2888 assert!(path.exists());
2889 let content = fs::read_to_string(&path).expect("read");
2890 assert!(content.contains("Project Agent Instructions"));
2891 }
2892
2893 #[test]
2894 fn test_load_with_parents() {
2895 let tmp = tempdir().expect("tempdir");
2896 let home = tempdir().expect("home tempdir");
2897
2898 // Create a nested structure
2899 let subdir = tmp.path().join("subproject");
2900 fs::create_dir(&subdir).expect("mkdir");
2901
2902 // Put AGENTS.md in parent
2903 fs::write(tmp.path().join("AGENTS.md"), "Parent instructions").expect("write");
2904 // Also create a real .git marker to make the parent the repo root
2905 let git_dir = tmp.path().join(".git");
2906 fs::create_dir(&git_dir).expect("mkdir .git");
2907 fs::write(git_dir.join("HEAD"), "ref: refs/heads/main\n").expect("write HEAD");
2908
2909 // Load from subdir should find parent's AGENTS.md
2910 let ctx = load_project_context_with_parents_and_home(&subdir, Some(home.path()));
2911
2912 assert!(ctx.has_instructions());
2913 assert!(
2914 ctx.instructions
2915 .as_ref()
2916 .unwrap()
2917 .contains("Parent instructions")
2918 );
2919 }
2920
2921 #[test]
2922 fn parent_search_stops_at_the_repository_root() {
2923 let tmp = tempdir().expect("tempdir");
2924 let home = tempdir().expect("home tempdir");
2925
2926 // AGENTS.md exists above the repository root. It belongs to another
2927 // scope (often another checkout) and must not leak into this one.
2928 fs::write(tmp.path().join("AGENTS.md"), "Organization instructions").expect("write");
2929
2930 // Mark repository root one level below.
2931 let repo_root = tmp.path().join("repo");
2932 fs::create_dir(&repo_root).expect("mkdir repo");
2933 let git_dir = repo_root.join(".git");
2934 fs::create_dir(&git_dir).expect("mkdir .git");
2935 fs::write(git_dir.join("HEAD"), "ref: refs/heads/main\n").expect("write HEAD");
2936
2937 let workspace = repo_root.join("apps").join("client");
2938 fs::create_dir_all(&workspace).expect("mkdir workspace");
2939
2940 let ctx = load_project_context_with_parents_and_home(&workspace, Some(home.path()));
2941 assert!(
2942 !ctx.instructions
2943 .as_deref()
2944 .is_some_and(|text| text.contains("Organization instructions")),
2945 "instruction files above the repository root must not be loaded: {:?}",
2946 ctx.instructions
2947 );
2948 assert_eq!(
2949 ctx.source_path, None,
2950 "no in-repo instruction file exists, so no source may be claimed"
2951 );
2952 assert!(
2953 !project_context_cache_candidate_paths(&workspace, Some(home.path()))
2954 .iter()
2955 .any(|(candidate, _)| candidate == &tmp.path().join("AGENTS.md")),
2956 "cache candidates must respect the repository boundary too"
2957 );
2958 }
2959
2960 #[test]
2961 fn instruction_chain_assembles_worktree_root_to_cwd_in_order_within_budget() {
2962 let tmp = tempdir().expect("tempdir");
2963 let home = tempdir().expect("home tempdir");
2964
2965 // A main checkout with its own AGENTS.md — it must stay out of the
2966 // nested worktree's instruction chain.
2967 let main = tmp.path().join("main-checkout");
2968 fs::create_dir_all(main.join(".git")).expect("mkdir main .git");
2969 fs::write(main.join(".git").join("HEAD"), "ref: refs/heads/main\n")
2970 .expect("write main HEAD");
2971 fs::write(main.join("AGENTS.md"), "MAIN-CHECKOUT-ONLY instructions")
2972 .expect("write main agents");
2973
2974 // A linked worktree: `.git` is a `gitdir:` pointer file, so the
2975 // worktree is its own repository root for instruction assembly.
2976 let lane = tmp.path().join("worktrees").join("lane");
2977 fs::create_dir_all(&lane).expect("mkdir lane");
2978 fs::write(
2979 lane.join(".git"),
2980 format!("gitdir: {}/.git/worktrees/lane\n", main.display()),
2981 )
2982 .expect("write lane gitdir pointer");
2983 fs::write(lane.join("AGENTS.md"), "WORKTREE-ROOT instructions").expect("write lane agents");
2984
2985 let nested = lane.join("crates").join("tui");
2986 fs::create_dir_all(&nested).expect("mkdir nested");
2987 fs::write(nested.join("AGENTS.md"), "NESTED-DIR instructions")
2988 .expect("write nested agents");
2989
2990 let ctx = load_project_context_with_parents_and_home(&nested, Some(home.path()));
2991
2992 let instructions = ctx.instructions.as_deref().unwrap_or("");
2993 assert!(
2994 instructions.contains("WORKTREE-ROOT instructions")
2995 && instructions.contains("NESTED-DIR instructions"),
2996 "worktree root and nested AGENTS.md must both assemble:\n{instructions}"
2997 );
2998 let root_at = instructions
2999 .find("WORKTREE-ROOT instructions")
3000 .expect("root");
3001 let nested_at = instructions
3002 .find("NESTED-DIR instructions")
3003 .expect("nested");
3004 assert!(
3005 root_at < nested_at,
3006 "repository root must read before the current directory (root={root_at}, nested={nested_at})"
3007 );
3008 assert!(
3009 !instructions.contains("MAIN-CHECKOUT-ONLY instructions"),
3010 "the main checkout's file is outside the worktree's chain:\n{instructions}"
3011 );
3012 let expected_source = fs::canonicalize(&nested)
3013 .expect("canonicalize nested")
3014 .join("AGENTS.md");
3015 assert_eq!(
3016 ctx.source_path.as_deref(),
3017 Some(expected_source.as_path()),
3018 "source_path points at the most specific (current-directory) file"
3019 );
3020 }
3021
3022 #[test]
3023 fn directory_outside_any_repository_loads_no_instruction_chain() {
3024 let tmp = tempdir().expect("tempdir");
3025 let home = tempdir().expect("home tempdir");
3026
3027 // No `.git` anywhere: the parent's AGENTS.md is outside any chain.
3028 fs::write(
3029 tmp.path().join("AGENTS.md"),
3030 "PARENT-OUTSIDE-REPO instructions",
3031 )
3032 .expect("write parent agents");
3033 let child = tmp.path().join("project");
3034 fs::create_dir_all(&child).expect("mkdir child");
3035 fs::write(child.join("AGENTS.md"), "CHILD-ONLY instructions").expect("write child agents");
3036
3037 let ctx = load_project_context_with_parents_and_home(&child, Some(home.path()));
3038
3039 let instructions = ctx.instructions.as_deref().unwrap_or("");
3040 assert!(
3041 instructions.contains("CHILD-ONLY instructions"),
3042 "the workspace's own file still loads outside a repository:\n{instructions}"
3043 );
3044 assert!(
3045 !instructions.contains("PARENT-OUTSIDE-REPO instructions"),
3046 "no ancestor chain may be assembled outside a repository:\n{instructions}"
3047 );
3048 let expected_source = fs::canonicalize(&child)
3049 .expect("canonicalize child")
3050 .join("AGENTS.md");
3051 assert_eq!(ctx.source_path.as_deref(), Some(expected_source.as_path()));
3052 }
3053
3054 #[test]
3055 fn agents_md_used_while_whale_md_is_ignored() {
3056 let tmp = tempdir().expect("tempdir");
3057 fs::write(tmp.path().join("AGENTS.md"), "AGENTS canonical").expect("write agents");
3058 fs::write(tmp.path().join("WHALE.md"), "WHALE legacy").expect("write whale");
3059
3060 let ctx = load_project_context(tmp.path());
3061 let instructions = ctx.instructions.expect("instructions loaded");
3062 assert!(instructions.contains("AGENTS canonical"), "{instructions}");
3063 assert!(!instructions.contains("WHALE legacy"), "{instructions}");
3064 assert!(
3065 ctx.warnings
3066 .iter()
3067 .any(|w| w.contains("WHALE.md is ignored")),
3068 "{:?}",
3069 ctx.warnings
3070 );
3071 }
3072
3073 #[test]
3074 fn whale_md_alone_is_ignored_with_migration_warning() {
3075 let tmp = tempdir().expect("tempdir");
3076 fs::write(tmp.path().join("WHALE.md"), "WHALE legacy body").expect("write whale");
3077
3078 let ctx = load_project_context(tmp.path());
3079 assert!(
3080 ctx.instructions.is_none(),
3081 "legacy WHALE.md must not be read"
3082 );
3083 assert!(
3084 ctx.warnings
3085 .iter()
3086 .any(|w| w.contains("WHALE.md is ignored")),
3087 "expected ignored-file warning, got {:?}",
3088 ctx.warnings
3089 );
3090 }
3091
3092 #[test]
3093 fn constitution_json_renders_authority_block() {
3094 let tmp = tempdir().expect("tempdir");
3095 fs::create_dir(tmp.path().join(".git")).expect("mkdir .git");
3096 fs::create_dir(tmp.path().join(".codewhale")).expect("mkdir .codewhale");
3097 fs::write(
3098 tmp.path().join(".codewhale").join("constitution.json"),
3099 r#"{
3100 "schema_version": 1,
3101 "authority": ["current user request", "live code and tests", "AGENTS.md"],
3102 "protected_invariants": ["keep the tool-catalog head byte-stable"],
3103 "branch_policy": "Start from live branch truth; open PRs into main",
3104 "verification_policy": { "before_claiming_done": ["run focused tests"] },
3105 "escalate_when": ["a destructive action was not authorized"]
3106 }"#,
3107 )
3108 .expect("write constitution");
3109
3110 let ctx = load_project_context_with_parents(tmp.path());
3111 let block = ctx
3112 .constitution_block
3113 .as_deref()
3114 .expect("constitution block rendered");
3115 assert!(block.contains("<codewhale_repo_constitution"));
3116 // Same origin-label convention as project_instructions: file name
3117 // only, no absolute path in the provider-bound label (the locator
3118 // stays available via constitution_source_path and /constitution).
3119 assert!(block.contains("source=\"constitution.json\""));
3120 assert!(
3121 !block.contains(&tmp.path().display().to_string()),
3122 "the constitution prompt label must not carry the absolute path"
3123 );
3124 assert!(block.contains("current user request"));
3125 assert!(block.contains("run focused tests"));
3126 assert!(block.contains("keep the tool-catalog head byte-stable"));
3127 assert!(block.contains("Start from live branch truth"));
3128 assert!(block.contains("a destructive action was not authorized"));
3129 assert!(block.contains("WHALE.md is ignored and should be migrated"));
3130 assert!(
3131 ctx.constitution_source_path
3132 .as_ref()
3133 .is_some_and(|path| path.ends_with(".codewhale/constitution.json")),
3134 "constitution source path should be visible: {:?}",
3135 ctx.constitution_source_path
3136 );
3137 // It also surfaces through the system block.
3138 assert!(
3139 ctx.as_system_block()
3140 .expect("system block")
3141 .contains("codewhale_repo_constitution")
3142 );
3143 }
3144
3145 #[test]
3146 fn stale_constitution_branch_policy_warns() {
3147 let tmp = tempdir().expect("tempdir");
3148 fs::create_dir(tmp.path().join(".git")).expect("mkdir .git");
3149 fs::create_dir(tmp.path().join(".codewhale")).expect("mkdir .codewhale");
3150 fs::write(
3151 tmp.path().join(".codewhale").join("constitution.json"),
3152 r#"{
3153 "schema_version": 1,
3154 "authority": ["current user request"],
3155 "branch_policy": "v0.8.53 work targets the codex/v0.8.53 integration branch, not main"
3156 }"#,
3157 )
3158 .expect("write constitution");
3159
3160 let ctx = load_project_context_with_parents(tmp.path());
3161 assert!(
3162 ctx.constitution_block.is_some(),
3163 "stale policy should warn but still render"
3164 );
3165 assert!(
3166 ctx.warnings
3167 .iter()
3168 .any(|warning| warning.contains("branch_policy appears stale")),
3169 "expected stale branch_policy warning, got {:?}",
3170 ctx.warnings
3171 );
3172 }
3173
3174 #[test]
3175 fn malformed_constitution_warns_without_crashing() {
3176 let tmp = tempdir().expect("tempdir");
3177 fs::create_dir(tmp.path().join(".git")).expect("mkdir .git");
3178 fs::create_dir(tmp.path().join(".codewhale")).expect("mkdir .codewhale");
3179 fs::write(
3180 tmp.path().join(".codewhale").join("constitution.json"),
3181 "{ not valid json",
3182 )
3183 .expect("write bad constitution");
3184
3185 let ctx = load_project_context_with_parents(tmp.path());
3186 assert!(
3187 ctx.constitution_block.is_none(),
3188 "no block for invalid JSON"
3189 );
3190 assert!(
3191 ctx.warnings.iter().any(|w| w.contains("Failed to parse")),
3192 "expected parse warning, got {:?}",
3193 ctx.warnings
3194 );
3195 }
3196
3197 #[cfg(unix)]
3198 #[test]
3199 fn constitution_json_rejects_symlinked_file() {
3200 let workspace = tempdir().expect("workspace tempdir");
3201 let outside = tempdir().expect("outside tempdir");
3202 fs::create_dir(workspace.path().join(".git")).expect("mkdir .git");
3203 fs::create_dir(workspace.path().join(".codewhale")).expect("mkdir .codewhale");
3204 let outside_constitution = outside.path().join("constitution.json");
3205 fs::write(
3206 &outside_constitution,
3207 r#"{"schema_version":1,"authority":["outside authority"]}"#,
3208 )
3209 .expect("write outside constitution");
3210 std::os::unix::fs::symlink(
3211 &outside_constitution,
3212 workspace
3213 .path()
3214 .join(".codewhale")
3215 .join("constitution.json"),
3216 )
3217 .expect("symlink constitution");
3218
3219 let ctx =
3220 load_project_context_with_parents_and_home(workspace.path(), Some(outside.path()));
3221
3222 assert!(
3223 ctx.constitution_block.is_none(),
3224 "symlinked constitution must not be loaded: {:?}",
3225 ctx.constitution_block
3226 );
3227 assert!(
3228 !ctx.as_system_block()
3229 .unwrap_or_default()
3230 .contains("outside authority"),
3231 "symlink target content must not reach the system block"
3232 );
3233 assert!(
3234 ctx.warnings.iter().any(|w| w.contains("symlinked")),
3235 "expected symlink warning, got {:?}",
3236 ctx.warnings
3237 );
3238 }
3239
3240 #[test]
3241 fn generated_context_is_bounded_and_ephemeral_for_many_file_workspace() {
3242 let workspace = tempdir().expect("workspace tempdir");
3243 let home = tempdir().expect("home tempdir");
3244 let noisy = workspace.path().join("aaa-many-files");
3245 fs::create_dir_all(&noisy).expect("mkdir noisy");
3246 for i in 0..1000 {
3247 fs::write(noisy.join(format!("file-{i:04}.rs")), "fn noisy() {}").expect("write noisy");
3248 }
3249 fs::create_dir_all(workspace.path().join("zzz-important")).expect("mkdir important");
3250 fs::write(
3251 workspace.path().join("zzz-important").join("main.rs"),
3252 "fn important() {}",
3253 )
3254 .expect("write important");
3255
3256 // Boundedness is a structural contract below; wall-clock time depends
3257 // on host load and is not a reliable assertion in the full suite.
3258 let ctx = load_project_context_with_parents_and_home(workspace.path(), Some(home.path()));
3259 assert!(ctx.has_instructions());
3260
3261 let generated_path = workspace.path().join(".codewhale").join("instructions.md");
3262 assert_eq!(ctx.source_path, None);
3263 assert!(
3264 !generated_path.exists(),
3265 "generated project context should stay ephemeral"
3266 );
3267 assert!(
3268 !workspace.path().join(".codewhale").exists(),
3269 "loading context should not create a .codewhale directory"
3270 );
3271 let generated = ctx.instructions.as_ref().expect("generated instructions");
3272 assert!(generated.contains("Project Context (Auto-generated, ephemeral)"));
3273 assert!(generated.contains("Bounded Project Overview"));
3274 assert!(!generated.contains("<project_context_pack>"));
3275 assert!(
3276 generated.contains("\"zzz-important/\""),
3277 "later top-level project areas should remain visible:\n{generated}"
3278 );
3279 let noisy_count = generated.matches("aaa-many-files/file-").count();
3280 assert!(
3281 noisy_count < 300,
3282 "generated context should not list the whole noisy directory; saw {noisy_count}"
3283 );
3284 assert!(
3285 !generated.contains("file-0999.rs"),
3286 "bounded context should omit the tail of the noisy directory"
3287 );
3288 }
3289
3290 #[test]
3291 fn explicit_home_bounds_parent_search_without_process_environment() {
3292 let home = tempdir().expect("home tempdir");
3293 fs::write(
3294 home.path().join("AGENTS.md"),
3295 "must not be loaded as project context",
3296 )
3297 .expect("write home AGENTS.md");
3298 let workspace = home.path().join("projects").join("demo");
3299 fs::create_dir_all(&workspace).expect("mkdir workspace");
3300
3301 let ctx = load_project_context_with_parents_and_home(&workspace, Some(home.path()));
3302
3303 assert_eq!(
3304 ctx.source_path, None,
3305 "the explicit home is the parent-search boundary, not project context"
3306 );
3307 assert!(
3308 ctx.instructions
3309 .as_deref()
3310 .is_some_and(|text| text.contains("Project Context (Auto-generated, ephemeral)")),
3311 "expected generated context, got {:?}",
3312 ctx.instructions
3313 );
3314 assert!(
3315 project_context_cache_candidate_paths(&workspace, Some(home.path()))
3316 .iter()
3317 .all(|(candidate, _)| candidate != &home.path().join("AGENTS.md")),
3318 "cache candidates must use the same explicit parent-search boundary"
3319 );
3320 }
3321
3322 #[test]
3323 fn cached_context_reflects_overwritten_agents_md() {
3324 crate::project_context_cache::clear();
3325 let workspace = tempdir().expect("workspace tempdir");
3326 let home = tempdir().expect("home tempdir");
3327 let agents = workspace.path().join("AGENTS.md");
3328 fs::write(&agents, "alpha").expect("write alpha");
3329
3330 let first =
3331 load_project_context_with_parents_cached_and_home(workspace.path(), Some(home.path()));
3332 assert!(
3333 first
3334 .instructions
3335 .as_deref()
3336 .is_some_and(|s| s.contains("alpha")),
3337 "expected alpha instructions: {:?}",
3338 first.instructions
3339 );
3340
3341 fs::write(&agents, "bravo").expect("write bravo");
3342 let second =
3343 load_project_context_with_parents_cached_and_home(workspace.path(), Some(home.path()));
3344
3345 assert!(
3346 second
3347 .instructions
3348 .as_deref()
3349 .is_some_and(|s| s.contains("bravo")),
3350 "cache must invalidate on same-length content overwrite: {:?}",
3351 second.instructions
3352 );
3353 }
3354
3355 #[test]
3356 fn cached_context_reflects_constitution_json_change() {
3357 crate::project_context_cache::clear();
3358 let workspace = tempdir().expect("workspace tempdir");
3359 let home = tempdir().expect("home tempdir");
3360 fs::create_dir(workspace.path().join(".git")).expect("mkdir git");
3361 fs::create_dir(workspace.path().join(".codewhale")).expect("mkdir codewhale");
3362 let constitution = workspace
3363 .path()
3364 .join(".codewhale")
3365 .join("constitution.json");
3366 fs::write(
3367 &constitution,
3368 r#"{"schema_version":1,"authority":["alpha authority"]}"#,
3369 )
3370 .expect("write alpha constitution");
3371
3372 let first =
3373 load_project_context_with_parents_cached_and_home(workspace.path(), Some(home.path()));
3374 assert!(
3375 first
3376 .constitution_block
3377 .as_deref()
3378 .is_some_and(|s| s.contains("alpha authority")),
3379 "expected alpha constitution block: {:?}",
3380 first.constitution_block
3381 );
3382
3383 fs::write(
3384 &constitution,
3385 r#"{"schema_version":1,"authority":["bravo authority"]}"#,
3386 )
3387 .expect("write bravo constitution");
3388 let second =
3389 load_project_context_with_parents_cached_and_home(workspace.path(), Some(home.path()));
3390
3391 assert!(
3392 second
3393 .constitution_block
3394 .as_deref()
3395 .is_some_and(|s| s.contains("bravo authority")),
3396 "cache must invalidate when constitution changes: {:?}",
3397 second.constitution_block
3398 );
3399 }
3400
3401 #[test]
3402 fn cached_generated_context_stays_ephemeral() {
3403 crate::project_context_cache::clear();
3404 let workspace = tempdir().expect("workspace tempdir");
3405 let home = tempdir().expect("home tempdir");
3406
3407 let first =
3408 load_project_context_with_parents_cached_and_home(workspace.path(), Some(home.path()));
3409 assert!(first.has_instructions());
3410 let generated_path = workspace.path().join(".codewhale").join("instructions.md");
3411 assert!(
3412 !generated_path.exists(),
3413 "first load should not write generated instructions"
3414 );
3415
3416 let second =
3417 load_project_context_with_parents_cached_and_home(workspace.path(), Some(home.path()));
3418 assert!(second.has_instructions());
3419 assert!(
3420 !generated_path.exists(),
3421 "cached generated context should remain in memory-only state"
3422 );
3423 }
3424
3425 #[test]
3426 fn test_load_global_agents_when_project_has_no_context() {
3427 let workspace = tempdir().expect("workspace tempdir");
3428 let home = tempdir().expect("home tempdir");
3429 let global_dir = home.path().join(".deepseek");
3430 fs::create_dir(&global_dir).expect("mkdir .deepseek");
3431 let global_agents = global_dir.join("AGENTS.md");
3432 fs::write(&global_agents, "Global instructions").expect("write global agents");
3433
3434 let ctx = load_project_context_with_parents_and_home(workspace.path(), Some(home.path()));
3435
3436 assert!(ctx.has_instructions());
3437 assert!(
3438 ctx.instructions
3439 .as_ref()
3440 .unwrap()
3441 .contains("Global instructions")
3442 );
3443 assert_eq!(ctx.source_path, Some(global_agents));
3444 }
3445
3446 #[test]
3447 fn test_load_global_agents_falls_back_to_vendor_neutral_path() {
3448 let workspace = tempdir().expect("workspace tempdir");
3449 let home = tempdir().expect("home tempdir");
3450 let global_dir = home.path().join(".agents");
3451 fs::create_dir(&global_dir).expect("mkdir .agents");
3452 let global_agents = global_dir.join("AGENTS.md");
3453 fs::write(&global_agents, "Vendor-neutral instructions").expect("write global agents");
3454
3455 let ctx = load_project_context_with_parents_and_home(workspace.path(), Some(home.path()));
3456
3457 assert!(ctx.has_instructions());
3458 assert!(
3459 ctx.instructions
3460 .as_ref()
3461 .unwrap()
3462 .contains("Vendor-neutral instructions")
3463 );
3464 assert_eq!(ctx.source_path, Some(global_agents));
3465 }
3466
3467 #[cfg(unix)]
3468 #[test]
3469 fn test_symlinked_global_agents_is_followed() {
3470 let workspace = tempdir().expect("workspace tempdir");
3471 let home = tempdir().expect("home tempdir");
3472 let shared = home.path().join("AGENTS.md");
3473 fs::write(&shared, "Shared global instructions").expect("write shared agents");
3474 fs::hard_link(&shared, home.path().join("shared-copy.md"))
3475 .expect("hard link global agents");
3476 let global_dir = home.path().join(".deepseek");
3477 fs::create_dir(&global_dir).expect("mkdir .deepseek");
3478 let link = global_dir.join("AGENTS.md");
3479 std::os::unix::fs::symlink(&shared, &link).expect("symlink global agents");
3480
3481 let ctx = load_project_context_with_parents_and_home(workspace.path(), Some(home.path()));
3482
3483 assert!(ctx.has_instructions());
3484 assert!(
3485 ctx.instructions
3486 .as_ref()
3487 .unwrap()
3488 .contains("Shared global instructions"),
3489 "a symlinked user-level AGENTS.md must be read: {:?}",
3490 ctx.warnings
3491 );
3492 assert_eq!(ctx.source_path, Some(link));
3493 assert!(
3494 !ctx.warnings.iter().any(|w| w.contains("symlink")),
3495 "following the user-level link must not warn: {:?}",
3496 ctx.warnings
3497 );
3498 }
3499
3500 #[cfg(unix)]
3501 #[test]
3502 fn test_symlinked_workspace_agents_is_still_refused() {
3503 let workspace = tempdir().expect("workspace tempdir");
3504 let home = tempdir().expect("home tempdir");
3505 let outside = tempdir().expect("outside tempdir");
3506 let secret = outside.path().join("secret.md");
3507 fs::write(&secret, "outside content").expect("write outside file");
3508 std::os::unix::fs::symlink(&secret, workspace.path().join("AGENTS.md"))
3509 .expect("symlink workspace agents");
3510
3511 let ctx = load_project_context_with_parents_and_home(workspace.path(), Some(home.path()));
3512
3513 assert!(
3514 ctx.instructions.is_none()
3515 || !ctx
3516 .instructions
3517 .as_ref()
3518 .unwrap()
3519 .contains("outside content"),
3520 "a workspace AGENTS.md symlink must not be followed"
3521 );
3522 }
3523
3524 #[test]
3525 fn test_codewhale_specific_path_wins_over_agents_path() {
3526 let workspace = tempdir().expect("workspace tempdir");
3527 let home = tempdir().expect("home tempdir");
3528
3529 let codewhale_dir = home.path().join(".codewhale");
3530 fs::create_dir(&codewhale_dir).expect("mkdir .codewhale");
3531 let codewhale_agents = codewhale_dir.join("AGENTS.md");
3532 fs::write(&codewhale_agents, "Codewhale-specific instructions")
3533 .expect("write codewhale agents");
3534
3535 let agents_dir = home.path().join(".agents");
3536 fs::create_dir(&agents_dir).expect("mkdir .agents");
3537 fs::write(agents_dir.join("AGENTS.md"), "Vendor-neutral instructions")
3538 .expect("write vendor-neutral agents");
3539
3540 let ctx = load_project_context_with_parents_and_home(workspace.path(), Some(home.path()));
3541
3542 assert!(ctx.has_instructions());
3543 let instructions = ctx.instructions.as_ref().unwrap();
3544 assert!(
3545 instructions.contains("Codewhale-specific instructions"),
3546 "Codewhale-specific global file should win:\n{instructions}"
3547 );
3548 assert!(
3549 !instructions.contains("Vendor-neutral instructions"),
3550 "lower-priority .agents file should be skipped:\n{instructions}"
3551 );
3552 assert_eq!(ctx.source_path, Some(codewhale_agents));
3553 }
3554
3555 #[test]
3556 fn test_global_agents_wins_over_global_whale_across_paths() {
3557 let workspace = tempdir().expect("workspace tempdir");
3558 let home = tempdir().expect("home tempdir");
3559
3560 let codewhale_dir = home.path().join(".codewhale");
3561 fs::create_dir(&codewhale_dir).expect("mkdir .codewhale");
3562 fs::write(codewhale_dir.join("WHALE.md"), "Global WHALE legacy")
3563 .expect("write codewhale whale");
3564
3565 let agents_dir = home.path().join(".agents");
3566 fs::create_dir(&agents_dir).expect("mkdir .agents");
3567 let global_agents = agents_dir.join("AGENTS.md");
3568 fs::write(&global_agents, "Global AGENTS canonical").expect("write global agents");
3569
3570 let ctx = load_project_context_with_parents_and_home(workspace.path(), Some(home.path()));
3571
3572 assert!(ctx.has_instructions());
3573 let instructions = ctx.instructions.as_ref().unwrap();
3574 assert!(
3575 instructions.contains("Global AGENTS canonical"),
3576 "global AGENTS.md should win:\n{instructions}"
3577 );
3578 assert!(
3579 !instructions.contains("Global WHALE legacy"),
3580 "global WHALE.md content should be skipped when any global AGENTS.md exists:\n{instructions}"
3581 );
3582 assert!(
3583 ctx.warnings
3584 .iter()
3585 .any(|warning| warning.contains("WHALE.md is ignored")),
3586 "ignored WHALE.md should emit migration warning: {:?}",
3587 ctx.warnings
3588 );
3589 assert_eq!(ctx.source_path, Some(global_agents));
3590 }
3591
3592 #[test]
3593 fn test_global_whale_is_ignored_when_no_global_agents_exists() {
3594 let workspace = tempdir().expect("workspace tempdir");
3595 let home = tempdir().expect("home tempdir");
3596
3597 let codewhale_dir = home.path().join(".codewhale");
3598 fs::create_dir(&codewhale_dir).expect("mkdir .codewhale");
3599 let global_whale = codewhale_dir.join("WHALE.md");
3600 fs::write(&global_whale, "Global WHALE legacy").expect("write codewhale whale");
3601
3602 let ctx = load_project_context_with_parents_and_home(workspace.path(), Some(home.path()));
3603
3604 let instructions = ctx.instructions.as_deref().unwrap_or("");
3605 assert!(
3606 !instructions.contains("Global WHALE legacy"),
3607 "legacy WHALE.md must not be read when no global AGENTS.md exists:\n{instructions}"
3608 );
3609 assert!(
3610 ctx.warnings
3611 .iter()
3612 .any(|warning| warning.contains("WHALE.md is ignored")),
3613 "expected global WHALE.md ignored warning, got {:?}",
3614 ctx.warnings
3615 );
3616 assert_ne!(ctx.source_path, Some(global_whale));
3617 }
3618
3619 #[test]
3620 fn test_global_instructions_md_is_autoloaded_while_whale_is_ignored() {
3621 // #3012: a global ~/.codewhale/instructions.md should be auto-loaded as
3622 // a fallback context layer while legacy WHALE.md remains ignored.
3623 let workspace = tempdir().expect("workspace tempdir");
3624 let home = tempdir().expect("home tempdir");
3625
3626 let codewhale_dir = home.path().join(".codewhale");
3627 fs::create_dir(&codewhale_dir).expect("mkdir .codewhale");
3628 fs::write(codewhale_dir.join("WHALE.md"), "Global WHALE legacy")
3629 .expect("write codewhale whale");
3630 let global_instructions = codewhale_dir.join("instructions.md");
3631 fs::write(&global_instructions, "Global instructions body")
3632 .expect("write global instructions");
3633
3634 let ctx = load_project_context_with_parents_and_home(workspace.path(), Some(home.path()));
3635
3636 assert!(ctx.has_instructions());
3637 let instructions = ctx.instructions.as_ref().unwrap();
3638 assert!(
3639 instructions.contains("Global instructions body"),
3640 "global instructions.md should be auto-loaded:\n{instructions}"
3641 );
3642 assert!(
3643 !instructions.contains("Global WHALE legacy"),
3644 "instructions.md should load without reading ignored WHALE.md:\n{instructions}"
3645 );
3646 assert!(
3647 ctx.warnings
3648 .iter()
3649 .any(|warning| warning.contains("WHALE.md is ignored")),
3650 "ignored WHALE.md should emit migration warning: {:?}",
3651 ctx.warnings
3652 );
3653 assert_eq!(ctx.source_path, Some(global_instructions));
3654 }
3655
3656 #[test]
3657 fn test_global_agents_outranks_global_instructions() {
3658 // #3012 precedence: AGENTS.md > instructions.md.
3659 let workspace = tempdir().expect("workspace tempdir");
3660 let home = tempdir().expect("home tempdir");
3661
3662 let codewhale_dir = home.path().join(".codewhale");
3663 fs::create_dir(&codewhale_dir).expect("mkdir .codewhale");
3664 let global_agents = codewhale_dir.join("AGENTS.md");
3665 fs::write(&global_agents, "Global AGENTS canonical").expect("write global agents");
3666 fs::write(
3667 codewhale_dir.join("instructions.md"),
3668 "Global instructions body",
3669 )
3670 .expect("write global instructions");
3671
3672 let ctx = load_project_context_with_parents_and_home(workspace.path(), Some(home.path()));
3673
3674 assert!(ctx.has_instructions());
3675 let instructions = ctx.instructions.as_ref().unwrap();
3676 assert!(
3677 instructions.contains("Global AGENTS canonical"),
3678 "global AGENTS.md should outrank instructions.md:\n{instructions}"
3679 );
3680 assert!(
3681 !instructions.contains("Global instructions body"),
3682 "instructions.md should be skipped when a global AGENTS.md exists:\n{instructions}"
3683 );
3684 assert_eq!(ctx.source_path, Some(global_agents));
3685 }
3686
3687 #[test]
3688 fn test_local_and_global_agents_merge_when_both_exist() {
3689 // #1157: when both `~/.deepseek/AGENTS.md` and a project AGENTS.md
3690 // exist, the prompt should carry user-wide preferences AND the
3691 // project's overrides — not silently drop the global file.
3692 let workspace = tempdir().expect("workspace tempdir");
3693 fs::write(workspace.path().join("AGENTS.md"), "Local instructions")
3694 .expect("write local agents");
3695
3696 let home = tempdir().expect("home tempdir");
3697 let global_dir = home.path().join(".deepseek");
3698 fs::create_dir(&global_dir).expect("mkdir .deepseek");
3699 fs::write(global_dir.join("AGENTS.md"), "Global instructions")
3700 .expect("write global agents");
3701
3702 let ctx = load_project_context_with_parents_and_home(workspace.path(), Some(home.path()));
3703
3704 assert!(ctx.has_instructions());
3705 let instructions = ctx.instructions.as_ref().unwrap();
3706 assert!(
3707 instructions.contains("Global instructions"),
3708 "global block missing from merged instructions:\n{instructions}"
3709 );
3710 assert!(
3711 instructions.contains("Local instructions"),
3712 "project block missing from merged instructions:\n{instructions}"
3713 );
3714 // Global block precedes the project block so project rules read
3715 // last and win "last word" precedence with the model.
3716 let global_at = instructions.find("Global instructions").unwrap();
3717 let local_at = instructions.find("Local instructions").unwrap();
3718 assert!(
3719 global_at < local_at,
3720 "global block must come before project block, got global={global_at} local={local_at}"
3721 );
3722 // The merged block is labelled so the model can tell the layers
3723 // apart when it needs to explain which rule it followed.
3724 assert!(
3725 instructions.contains("project (overrides global where they conflict)"),
3726 "expected labelled separator between global and project blocks"
3727 );
3728 // `source_path` keeps pointing at the more-specific file so the
3729 // user knows where to edit the workspace-level override.
3730 assert_eq!(
3731 ctx.source_path,
3732 Some(canonicalize_workspace_or_keep(workspace.path()).join("AGENTS.md"))
3733 );
3734 }
3735
3736 #[test]
3737 fn test_global_agents_only_no_project_unchanged_fallback() {
3738 // Sanity: when only the global file exists, the historical
3739 // fallback behaviour is preserved — no merge framing leaks in.
3740 let workspace = tempdir().expect("workspace tempdir");
3741 let home = tempdir().expect("home tempdir");
3742 let global_dir = home.path().join(".deepseek");
3743 fs::create_dir(&global_dir).expect("mkdir .deepseek");
3744 let global_agents = global_dir.join("AGENTS.md");
3745 fs::write(&global_agents, "Just the global instructions").expect("write global agents");
3746
3747 let ctx = load_project_context_with_parents_and_home(workspace.path(), Some(home.path()));
3748
3749 assert!(ctx.has_instructions());
3750 let instructions = ctx.instructions.as_ref().unwrap();
3751 assert!(instructions.contains("Just the global instructions"));
3752 assert!(
3753 !instructions.contains("project (overrides global"),
3754 "merge-framing label should not appear when there's nothing to merge"
3755 );
3756 assert_eq!(ctx.source_path, Some(global_agents));
3757 }
3758
3759 #[test]
3760 fn test_invalid_global_agents_warns_and_falls_back_to_generated_context() {
3761 let workspace = tempdir().expect("workspace tempdir");
3762 let home = tempdir().expect("home tempdir");
3763 let global_dir = home.path().join(".deepseek");
3764 fs::create_dir(&global_dir).expect("mkdir .deepseek");
3765 fs::write(global_dir.join("AGENTS.md"), " \n ").expect("write empty global agents");
3766
3767 let ctx = load_project_context_with_parents_and_home(workspace.path(), Some(home.path()));
3768
3769 assert!(
3770 ctx.warnings
3771 .iter()
3772 .any(|warning| warning.contains("Context file") && warning.contains("is empty")),
3773 "expected empty global AGENTS.md warning, got {:?}",
3774 ctx.warnings
3775 );
3776 assert!(ctx.has_instructions());
3777 assert!(
3778 ctx.instructions
3779 .as_ref()
3780 .unwrap()
3781 .contains("Project Context (Auto-generated, ephemeral)")
3782 );
3783 }
3784
3785 // ── Rules directory auto-discovery tests ──
3786
3787 #[test]
3788 fn rules_from_codewhale_dir_are_loaded_as_project_context() {
3789 let tmp = tempdir().expect("tempdir");
3790 let rules_dir = tmp.path().join(".codewhale/rules");
3791 fs::create_dir_all(&rules_dir).expect("mkdir rules");
3792 fs::write(
3793 rules_dir.join("security.md"),
3794 "# Security\nNo hardcoded secrets.",
3795 )
3796 .expect("write");
3797
3798 let ctx = load_project_context(tmp.path());
3799
3800 let rules = ctx.rules_block.as_ref().expect("rules_block should be set");
3801 assert!(
3802 rules.contains("Security"),
3803 "expected rules content, got: {rules}"
3804 );
3805 assert!(
3806 rules.contains("<project_rule source="),
3807 "expected <project_rule> wrapper, got: {rules}"
3808 );
3809 }
3810
3811 #[test]
3812 fn rules_are_loaded_in_filename_order() {
3813 let tmp = tempdir().expect("tempdir");
3814 let rules_dir = tmp.path().join(".codewhale/rules");
3815 fs::create_dir_all(&rules_dir).expect("mkdir rules");
3816 fs::write(rules_dir.join("zzz.md"), "last").expect("write");
3817 fs::write(rules_dir.join("aaa.md"), "first").expect("write");
3818 fs::write(rules_dir.join("mmm.md"), "middle").expect("write");
3819
3820 let ctx = load_project_context(tmp.path());
3821 let rules = ctx.rules_block.as_ref().unwrap();
3822
3823 let pos_aaa = rules.find("first").unwrap();
3824 let pos_mmm = rules.find("middle").unwrap();
3825 let pos_zzz = rules.find("last").unwrap();
3826 assert!(pos_aaa < pos_mmm, "aaa should come before mmm");
3827 assert!(pos_mmm < pos_zzz, "mmm should come before zzz");
3828 }
3829
3830 #[test]
3831 fn claude_rules_load_only_when_explicitly_imported() {
3832 let tmp = tempdir().expect("tempdir");
3833 let rules_dir = tmp.path().join(".claude/rules");
3834 fs::create_dir_all(&rules_dir).expect("mkdir rules");
3835 fs::write(rules_dir.join("style.md"), "Use tabs").expect("write");
3836
3837 // Default: another tool's rules directory is not Codewhale's law.
3838 let ctx = load_project_context_with_imports(tmp.path(), &ForeignInstructionImports::none());
3839 assert!(
3840 ctx.rules_block.is_none(),
3841 "an un-imported .claude/rules must contribute nothing: {:?}",
3842 ctx.rules_block
3843 );
3844 assert!(
3845 ctx.warnings
3846 .iter()
3847 .any(|w| w.contains("claude") && w.contains("project_instruction_imports")),
3848 "the user must be told the files exist and how to import them: {:?}",
3849 ctx.warnings
3850 );
3851
3852 // Opted in by name: loaded, and ranked after Codewhale's own.
3853 let (imports, unknown) = ForeignInstructionImports::from_config(&["claude".to_string()]);
3854 assert!(unknown.is_empty());
3855 let ctx = load_project_context_with_imports(tmp.path(), &imports);
3856 let rules = ctx.rules_block.as_ref().expect("rules should be loaded");
3857 assert!(rules.contains("Use tabs"), "expected .claude/rules/ import");
3858 }
3859
3860 #[test]
3861 fn fragment_backed_foreign_instructions_warn_until_imported() {
3862 let tmp = tempdir().expect("tempdir");
3863 fs::write(tmp.path().join(".cursorrules"), "Cursor-only law").expect("write cursor");
3864 let copilot_dir = tmp.path().join(".github");
3865 fs::create_dir_all(&copilot_dir).expect("mkdir github");
3866 fs::write(
3867 copilot_dir.join("copilot-instructions.md"),
3868 "Copilot-only law",
3869 )
3870 .expect("write copilot");
3871
3872 let ctx = load_project_context_with_imports(tmp.path(), &ForeignInstructionImports::none());
3873 let warning = ctx
3874 .warnings
3875 .iter()
3876 .find(|warning| warning.contains("project_instruction_imports"))
3877 .expect("foreign fragment warning");
3878 assert!(warning.contains("cursor"), "{warning}");
3879 assert!(warning.contains("copilot"), "{warning}");
3880
3881 let (imports, unknown) =
3882 ForeignInstructionImports::from_config(&["cursor".to_string(), "copilot".to_string()]);
3883 assert!(unknown.is_empty());
3884 let ctx = load_project_context_with_imports(tmp.path(), &imports);
3885 assert!(
3886 ctx.warnings
3887 .iter()
3888 .all(|warning| !warning.contains("project_instruction_imports")),
3889 "opted-in formats must not keep warning: {:?}",
3890 ctx.warnings
3891 );
3892 }
3893
3894 #[test]
3895 fn unusable_foreign_fragments_do_not_claim_importable_instructions() {
3896 let tmp = tempdir().expect("tempdir");
3897 fs::write(tmp.path().join(".cursorrules"), " \n").expect("write empty cursor file");
3898 let cursor_rules = tmp.path().join(".cursor/rules");
3899 fs::create_dir_all(&cursor_rules).expect("mkdir cursor rules");
3900 fs::write(cursor_rules.join("settings.json"), "{}").expect("write non-markdown file");
3901
3902 let ctx = load_project_context_with_imports(tmp.path(), &ForeignInstructionImports::none());
3903 assert!(
3904 ctx.warnings
3905 .iter()
3906 .all(|warning| !warning.contains("project_instruction_imports")),
3907 "empty and non-Markdown fragments are not importable: {:?}",
3908 ctx.warnings
3909 );
3910 }
3911
3912 #[test]
3913 fn unusable_direct_foreign_instructions_do_not_claim_importable_content() {
3914 let tmp = tempdir().expect("tempdir");
3915 fs::write(tmp.path().join("CLAUDE.md"), "\n\t ").expect("write empty claude file");
3916 let claude_rules = tmp.path().join(".claude/rules");
3917 fs::create_dir_all(&claude_rules).expect("mkdir claude rules");
3918 fs::write(claude_rules.join("settings.json"), "{}").expect("write non-markdown file");
3919
3920 let ctx = load_project_context_with_imports(tmp.path(), &ForeignInstructionImports::none());
3921 assert!(
3922 ctx.warnings
3923 .iter()
3924 .all(|warning| !warning.contains("project_instruction_imports")),
3925 "empty files and rules directories without Markdown are not importable: {:?}",
3926 ctx.warnings
3927 );
3928 }
3929
3930 #[cfg(unix)]
3931 #[test]
3932 fn symlinked_foreign_fragment_does_not_claim_importable_instructions() {
3933 use std::os::unix::fs::symlink;
3934
3935 let tmp = tempdir().expect("tempdir");
3936 let outside = tempdir().expect("outside tempdir");
3937 let outside_claude = outside.path().join("CLAUDE.md");
3938 fs::write(&outside_claude, "outside Claude law").expect("write outside Claude file");
3939 let outside_rules = outside.path().join("rules");
3940 fs::create_dir_all(&outside_rules).expect("mkdir outside rules");
3941 fs::write(outside_rules.join("law.md"), "outside law").expect("write outside rule");
3942 fs::create_dir_all(tmp.path().join(".cursor")).expect("mkdir cursor");
3943 fs::create_dir_all(tmp.path().join(".claude")).expect("mkdir claude");
3944 symlink(&outside_rules, tmp.path().join(".cursor/rules")).expect("symlink cursor rules");
3945 symlink(&outside_rules, tmp.path().join(".claude/rules")).expect("symlink claude rules");
3946 symlink(&outside_claude, tmp.path().join("CLAUDE.md")).expect("symlink Claude file");
3947
3948 let ctx = load_project_context_with_imports(tmp.path(), &ForeignInstructionImports::none());
3949 assert!(
3950 ctx.warnings
3951 .iter()
3952 .all(|warning| !warning.contains("project_instruction_imports")),
3953 "the bounded loader rejects symlinked foreign fragments: {:?}",
3954 ctx.warnings
3955 );
3956 }
3957
3958 #[test]
3959 fn foreign_instruction_imports_parse_names_and_report_typos() {
3960 let (imports, unknown) = ForeignInstructionImports::from_config(&[]);
3961 assert!(imports.is_empty(), "default imports nothing");
3962 assert!(unknown.is_empty());
3963
3964 let (imports, unknown) = ForeignInstructionImports::from_config(&[
3965 "Claude".to_string(),
3966 " cursor ".to_string(),
3967 "clawed".to_string(),
3968 ]);
3969 assert!(imports.is_enabled(ForeignInstructionFormat::Claude));
3970 assert!(imports.is_enabled(ForeignInstructionFormat::Cursor));
3971 assert!(!imports.is_enabled(ForeignInstructionFormat::Gemini));
3972 assert_eq!(unknown, vec!["clawed".to_string()], "typos are reported");
3973
3974 let (all, _) = ForeignInstructionImports::from_config(&["all".to_string()]);
3975 for format in ForeignInstructionFormat::ALL {
3976 assert!(
3977 all.is_enabled(*format),
3978 "{} missing from `all`",
3979 format.key()
3980 );
3981 }
3982 assert_eq!(all.keys().len(), ForeignInstructionFormat::ALL.len());
3983 }
3984
3985 #[test]
3986 fn codewhale_instructions_outrank_an_imported_claude_file() {
3987 // On the previous default list CLAUDE.md sat at rank 3 and
3988 // .codewhale/instructions.md at rank 4, so another tool's file won.
3989 let tmp = tempdir().expect("tempdir");
3990 fs::create_dir_all(tmp.path().join(".codewhale")).expect("mkdir codewhale");
3991 fs::write(
3992 tmp.path().join(".codewhale/instructions.md"),
3993 "CODEWHALE-OWN",
3994 )
3995 .expect("write codewhale");
3996 fs::write(tmp.path().join("CLAUDE.md"), "CLAUDE-FILE").expect("write claude");
3997
3998 let (imports, _) = ForeignInstructionImports::from_config(&["claude".to_string()]);
3999 let files = context_files_for(&imports);
4000 let cw = files
4001 .iter()
4002 .position(|f| *f == ".codewhale/instructions.md")
4003 .expect("codewhale file in list");
4004 let cl = files
4005 .iter()
4006 .position(|f| *f == "CLAUDE.md")
4007 .expect("claude file in list");
4008 assert!(
4009 cl > cw,
4010 "Codewhale's own instruction file must outrank an imported CLAUDE.md: {files:?}"
4011 );
4012 }
4013
4014 #[test]
4015 fn rules_directory_missing_does_not_crash() {
4016 let tmp = tempdir().expect("tempdir");
4017 // No .codewhale/rules/ or .claude/rules/ directories exist
4018 let ctx = load_project_context(tmp.path());
4019 // Rules block should be None when no rules directories exist
4020 assert!(
4021 ctx.rules_block.is_none(),
4022 "rules_block should be None when no rules exist"
4023 );
4024 }
4025
4026 #[test]
4027 fn rules_coexist_with_agents_md() {
4028 let tmp = tempdir().expect("tempdir");
4029 fs::write(tmp.path().join("AGENTS.md"), "Main project instructions").expect("write");
4030 let rules_dir = tmp.path().join(".codewhale/rules");
4031 fs::create_dir_all(&rules_dir).expect("mkdir rules");
4032 fs::write(rules_dir.join("extra.md"), "Extra rule").expect("write");
4033
4034 let ctx = load_project_context(tmp.path());
4035 let instructions = ctx.instructions.as_ref().unwrap();
4036 let rules = ctx.rules_block.as_ref().unwrap();
4037
4038 assert!(
4039 instructions.contains("Main project instructions"),
4040 "AGENTS.md content missing"
4041 );
4042 assert!(rules.contains("Extra rule"), "rules content missing");
4043 // AGENTS.md should come first in system block
4044 let block = ctx.as_system_block().unwrap();
4045 let pos_agents = block.find("Main project instructions").unwrap();
4046 let pos_rule = block.find("Extra rule").unwrap();
4047 assert!(pos_agents < pos_rule, "AGENTS.md should precede rules");
4048 }
4049
4050 #[test]
4051 fn non_md_files_in_rules_dir_are_ignored() {
4052 let tmp = tempdir().expect("tempdir");
4053 let rules_dir = tmp.path().join(".codewhale/rules");
4054 fs::create_dir_all(&rules_dir).expect("mkdir rules");
4055 fs::write(rules_dir.join("notes.txt"), "should be ignored").expect("write");
4056 fs::write(rules_dir.join("valid.md"), "loaded").expect("write");
4057
4058 let ctx = load_project_context(tmp.path());
4059 let rules = ctx.rules_block.as_ref().unwrap();
4060
4061 assert!(rules.contains("loaded"), "valid .md should be loaded");
4062 assert!(
4063 !rules.contains("should be ignored"),
4064 ".txt should be ignored"
4065 );
4066 }
4067
4068 #[test]
4069 fn rules_cap_truncates_excess_files() {
4070 let tmp = tempdir().expect("tempdir");
4071 let rules_dir = tmp.path().join(".codewhale/rules");
4072 fs::create_dir_all(&rules_dir).expect("mkdir rules");
4073
4074 // Create more files than the cap
4075 for i in 0..60 {
4076 fs::write(
4077 rules_dir.join(format!("rule_{i:04}.md")),
4078 format!("content {i}"),
4079 )
4080 .expect("write");
4081 }
4082
4083 let ctx = load_project_context(tmp.path());
4084 let rules = ctx.rules_block.as_ref().unwrap();
4085
4086 // The last file (by sorted name) should NOT be present
4087 assert!(
4088 !rules.contains("content 59"),
4089 "rule_0059 should be above cap"
4090 );
4091 // The first file should be present
4092 assert!(
4093 rules.contains("content 0"),
4094 "rule_0000 should be within cap"
4095 );
4096 // Count <project_rule> blocks
4097 let count = rules.matches("<project_rule source=").count();
4098 assert_eq!(
4099 count, MAX_RULES_FILES,
4100 "exactly {MAX_RULES_FILES} rules should be loaded"
4101 );
4102 }
4103
4104 #[cfg(unix)]
4105 #[test]
4106 fn rules_rejects_symlinked_files() {
4107 let workspace = tempdir().expect("workspace tempdir");
4108 let outside = tempdir().expect("outside tempdir");
4109 let rules_dir = workspace.path().join(".codewhale/rules");
4110 fs::create_dir_all(&rules_dir).expect("mkdir rules");
4111
4112 let outside_rule = outside.path().join("outside.md");
4113 fs::write(&outside_rule, "outside content").expect("write outside");
4114 std::os::unix::fs::symlink(&outside_rule, rules_dir.join("outside.md"))
4115 .expect("symlink rule");
4116
4117 let ctx = load_project_context(workspace.path());
4118
4119 // Symlinked rules must not be loaded
4120 assert!(
4121 ctx.rules_block.is_none()
4122 || !ctx
4123 .rules_block
4124 .as_ref()
4125 .unwrap()
4126 .contains("outside content"),
4127 "symlinked rules must not be loaded"
4128 );
4129 }
4130
4131 #[cfg(unix)]
4132 #[test]
4133 fn rules_rejects_symlinked_directory() {
4134 let workspace = tempdir().expect("workspace tempdir");
4135 let outside = tempdir().expect("outside tempdir");
4136 let outside_dir = outside.path().join("real_rules");
4137 fs::create_dir_all(&outside_dir).expect("mkdir outside dir");
4138 fs::write(outside_dir.join("secret.md"), "outside content").expect("write outside");
4139 fs::create_dir_all(workspace.path().join(".codewhale")).expect("mkdir codewhale");
4140
4141 // Symlink the directory itself, not individual files
4142 std::os::unix::fs::symlink(&outside_dir, workspace.path().join(".codewhale/rules"))
4143 .expect("symlink rules dir");
4144
4145 let ctx = load_project_context(workspace.path());
4146
4147 // Symlinked rules directory must be refused at the directory level
4148 assert!(
4149 ctx.rules_block.is_none()
4150 || !ctx
4151 .rules_block
4152 .as_ref()
4153 .unwrap()
4154 .contains("outside content"),
4155 "symlinked rules directory must be refused"
4156 );
4157 }
4158
4159 #[test]
4160 fn rules_from_both_dirs_are_loaded_together() {
4161 let tmp = tempdir().expect("tempdir");
4162 let codewhale_rules = tmp.path().join(".codewhale/rules");
4163 let claude_rules = tmp.path().join(".claude/rules");
4164 fs::create_dir_all(&codewhale_rules).expect("mkdir codewhale rules");
4165 fs::create_dir_all(&claude_rules).expect("mkdir claude rules");
4166 fs::write(codewhale_rules.join("cw.md"), "codewhale-rule").expect("write");
4167 fs::write(claude_rules.join("claude.md"), "claude-rule").expect("write");
4168
4169 let (imports, _) = ForeignInstructionImports::from_config(&["claude".to_string()]);
4170 let ctx = load_project_context_with_imports(tmp.path(), &imports);
4171 let rules = ctx.rules_block.as_ref().unwrap();
4172
4173 assert!(
4174 rules.contains("codewhale-rule"),
4175 ".codewhale/rules/ should be loaded"
4176 );
4177 assert!(
4178 rules.contains("claude-rule"),
4179 "an imported .claude/rules/ should be loaded"
4180 );
4181 // .codewhale/rules/ content should precede an imported foreign dir
4182 let pos_cw = rules.find("codewhale-rule").unwrap();
4183 let pos_claude = rules.find("claude-rule").unwrap();
4184 assert!(
4185 pos_cw < pos_claude,
4186 ".codewhale/rules/ should precede .claude/rules/"
4187 );
4188 }
4189
4190 #[test]
4191 fn instruction_sources_report_precedence_shadowing_and_ignored_files() {
4192 let tmp = tempdir().expect("tempdir");
4193 let root = tmp.path();
4194 fs::create_dir_all(root.join(".git")).expect("mkdir git");
4195 fs::write(root.join(".git").join("HEAD"), "ref: refs/heads/main\n").expect("head");
4196 fs::write(root.join("AGENTS.md"), "primary\n").expect("agents");
4197 fs::create_dir_all(root.join(".codewhale")).expect("mkdir codewhale");
4198 fs::write(
4199 root.join(".codewhale").join("instructions.md"),
4200 "secondary\n",
4201 )
4202 .expect("workspace instructions");
4203 fs::write(root.join("WHALE.md"), "deprecated\n").expect("whale");
4204 fs::create_dir_all(root.join(".codewhale").join("rules")).expect("mkdir rules");
4205 fs::write(
4206 root.join(".codewhale").join("rules").join("style.md"),
4207 "keep it small\n",
4208 )
4209 .expect("rule");
4210
4211 let home = tmp.path().join("home");
4212 fs::create_dir_all(&home).expect("mkdir home");
4213 let configured = vec![root.join("team").join("extra.md")];
4214 fs::create_dir_all(root.join("team")).expect("mkdir team");
4215 fs::write(root.join("team").join("extra.md"), "configured\n").expect("configured");
4216
4217 let sources = project_instruction_sources(root, Some(&home), &configured);
4218 let find = |path_suffix: &str| {
4219 sources
4220 .iter()
4221 .find(|source| source.path.ends_with(path_suffix))
4222 .unwrap_or_else(|| panic!("missing entry for {path_suffix}: {sources:?}"))
4223 };
4224
4225 let agents = find("AGENTS.md");
4226 assert_eq!(agents.kind, InstructionSourceKind::Project);
4227 assert_eq!(agents.status, InstructionSourceStatus::Loaded);
4228 assert_eq!(agents.bytes, Some(8));
4229
4230 // The lower-priority candidate in the same scope exists but is
4231 // shadowed, not loaded.
4232 let secondary = find(".codewhale/instructions.md");
4233 assert_eq!(secondary.status, InstructionSourceStatus::Shadowed);
4234
4235 let whale = find("WHALE.md");
4236 assert_eq!(whale.kind, InstructionSourceKind::Ignored);
4237 assert_eq!(whale.status, InstructionSourceStatus::Skipped);
4238 assert!(whale.warning.is_some());
4239
4240 let rule = find("style.md");
4241 assert_eq!(rule.kind, InstructionSourceKind::Rule);
4242 assert_eq!(rule.status, InstructionSourceStatus::Loaded);
4243
4244 let configured_entry = find("extra.md");
4245 assert_eq!(configured_entry.kind, InstructionSourceKind::Configured);
4246 assert_eq!(configured_entry.status, InstructionSourceStatus::Loaded);
4247
4248 // Unchecked-but-real candidates are enumerated so clients can render
4249 // the full precedence map.
4250 assert!(
4251 sources
4252 .iter()
4253 .any(|s| s.status == InstructionSourceStatus::Missing),
4254 "missing candidates must appear: {sources:?}"
4255 );
4256 // Global candidates under the (empty) home are reported as missing.
4257 assert!(
4258 sources
4259 .iter()
4260 .any(|s| s.kind == InstructionSourceKind::Global
4261 && s.status == InstructionSourceStatus::Missing),
4262 "global candidates must appear: {sources:?}"
4263 );
4264 }
4265
4266 #[test]
4267 fn instruction_sources_mark_unreadable_winner_as_skipped_not_loaded() {
4268 let tmp = tempdir().expect("tempdir");
4269 let root = tmp.path();
4270 fs::create_dir_all(root.join(".git")).expect("mkdir git");
4271 fs::write(root.join(".git").join("HEAD"), "ref: refs/heads/main\n").expect("head");
4272 // An empty AGENTS.md fails the load check, so the next candidate wins.
4273 fs::write(root.join("AGENTS.md"), " \n").expect("empty agents");
4274 fs::create_dir_all(root.join(".codewhale")).expect("mkdir codewhale");
4275 fs::write(root.join(".codewhale").join("instructions.md"), "wins\n")
4276 .expect("workspace instructions");
4277
4278 let sources = project_instruction_sources(root, None, &[]);
4279 let agents = sources
4280 .iter()
4281 .find(|s| s.path.ends_with("AGENTS.md"))
4282 .expect("agents entry");
4283 assert_eq!(agents.status, InstructionSourceStatus::Skipped);
4284 assert!(agents.warning.is_some(), "refusal must carry a warning");
4285
4286 let winner = sources
4287 .iter()
4288 .find(|s| s.path.ends_with(".codewhale/instructions.md"))
4289 .expect("instructions entry");
4290 assert_eq!(winner.status, InstructionSourceStatus::Loaded);
4291 }
4292 }
4293
4293 lines RUST