返回 CodeWhale
fragments.rs
根目录 / crates / core / src / fragments.rs
1 //! Bounded context-fragment system with hard caps (issue #5264).
2 //!
3 //! Every context injection goes through a typed fragment with a
4 //! `matches_text` recognizer, collected in one `crates/core` module.
5 //! Hard caps: per-fragment byte cap, 10K-token ceiling, injected-item count.
6 //! Project-instruction import (#3978, #4079) is a typed fragment.
7
8 use std::collections::hash_map::DefaultHasher;
9 use std::hash::{Hash, Hasher};
10 use std::path::{Path, PathBuf};
11
12 // Caps
13 pub const MAX_FRAGMENT_TOKENS: usize = 10_000;
14 pub const MAX_FRAGMENT_BYTES: usize = MAX_FRAGMENT_TOKENS * 4; // 40_000
15 pub const DEFAULT_FRAGMENT_MAX_BYTES: usize = 4 * 1024;
16 pub const MAX_FRAGMENTS_PER_CONTEXT: usize = 16;
17 pub const INSTRUCTIONS_FILE_MAX_BYTES: usize = 100 * 1024;
18 pub const MAX_INSTRUCTION_FILES: usize = 32;
19
20 /// Stable fragment identities. Markers are public contract.
21 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
22 pub enum FragmentId {
23 Workspace,
24 Permissions,
25 Route,
26 AgentTopology,
27 SkillsTools,
28 SessionRelay,
29 ProjectInstructions,
30 Constitution,
31 }
32
33 impl FragmentId {
34 #[must_use]
35 pub fn as_str(self) -> &'static str {
36 match self {
37 Self::Workspace => "workspace",
38 Self::Permissions => "permissions",
39 Self::Route => "route",
40 Self::AgentTopology => "agent_topology",
41 Self::SkillsTools => "skills_tools",
42 Self::SessionRelay => "session_relay",
43 Self::ProjectInstructions => "project_instructions",
44 Self::Constitution => "constitution",
45 }
46 }
47 #[must_use]
48 pub fn marker(self) -> &'static str {
49 match self {
50 Self::Workspace => "<!-- cw:ctx:workspace -->",
51 Self::Permissions => "<!-- cw:ctx:permissions -->",
52 Self::Route => "<!-- cw:ctx:route -->",
53 Self::AgentTopology => "<!-- cw:ctx:agent_topology -->",
54 Self::SkillsTools => "<!-- cw:ctx:skills_tools -->",
55 Self::SessionRelay => "<!-- cw:ctx:session_relay -->",
56 Self::ProjectInstructions => "<!-- cw:ctx:project_instructions -->",
57 Self::Constitution => "<!-- cw:ctx:constitution -->",
58 }
59 }
60 #[must_use]
61 pub fn role(self) -> FragmentRole {
62 match self {
63 Self::Workspace => FragmentRole::Workspace,
64 Self::Permissions => FragmentRole::Permissions,
65 Self::Route => FragmentRole::Route,
66 Self::AgentTopology => FragmentRole::AgentTopology,
67 Self::SkillsTools => FragmentRole::SkillsTools,
68 Self::SessionRelay => FragmentRole::SessionRelay,
69 Self::ProjectInstructions => FragmentRole::ProjectInstructions,
70 Self::Constitution => FragmentRole::Constitution,
71 }
72 }
73 #[must_use]
74 pub fn all() -> &'static [FragmentId] {
75 &[
76 Self::Workspace,
77 Self::Permissions,
78 Self::Route,
79 Self::AgentTopology,
80 Self::SkillsTools,
81 Self::SessionRelay,
82 Self::ProjectInstructions,
83 Self::Constitution,
84 ]
85 }
86 }
87
88 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
89 pub enum FragmentRole {
90 Workspace,
91 Permissions,
92 Route,
93 AgentTopology,
94 SkillsTools,
95 SessionRelay,
96 ProjectInstructions,
97 Constitution,
98 }
99
100 impl FragmentRole {
101 #[must_use]
102 pub fn as_str(self) -> &'static str {
103 match self {
104 Self::Workspace => "workspace",
105 Self::Permissions => "permissions",
106 Self::Route => "route",
107 Self::AgentTopology => "agent_topology",
108 Self::SkillsTools => "skills_tools",
109 Self::SessionRelay => "session_relay",
110 Self::ProjectInstructions => "project_instructions",
111 Self::Constitution => "constitution",
112 }
113 }
114 }
115
116 #[must_use]
117 pub fn estimate_tokens(text: &str) -> usize {
118 text.len().div_ceil(4)
119 }
120
121 /// Typed fragment trait with `matches_text` recognizer.
122 pub trait ContextFragment {
123 fn fragment_id(&self) -> FragmentId;
124 fn marker(&self) -> &'static str;
125 fn content(&self) -> &str;
126 fn matches_text(&self, haystack: &str) -> bool {
127 haystack.contains(self.marker())
128 }
129 fn tokens_est(&self) -> usize {
130 estimate_tokens(self.content())
131 }
132 fn max_bytes(&self) -> usize;
133 fn is_within_token_ceiling(&self) -> bool {
134 self.tokens_est() <= MAX_FRAGMENT_TOKENS
135 }
136 fn is_within_byte_ceiling(&self) -> bool {
137 self.content().len() <= MAX_FRAGMENT_BYTES
138 }
139 }
140
141 #[derive(Debug, Clone, PartialEq, Eq)]
142 pub struct BoundedFragment {
143 pub id: FragmentId,
144 pub role: FragmentRole,
145 pub marker: &'static str,
146 pub max_bytes: usize,
147 pub content: String,
148 pub content_hash: u64,
149 }
150
151 impl BoundedFragment {
152 #[must_use]
153 pub fn new(id: FragmentId, raw: impl Into<String>) -> Self {
154 Self::with_max_bytes(id, raw, DEFAULT_FRAGMENT_MAX_BYTES)
155 }
156 #[must_use]
157 pub fn with_max_bytes(id: FragmentId, raw: impl Into<String>, max_bytes: usize) -> Self {
158 let clamped_max = max_bytes.min(MAX_FRAGMENT_BYTES);
159 let mut content = enforce_byte_cap(raw.into(), clamped_max);
160 if estimate_tokens(&content) > MAX_FRAGMENT_TOKENS {
161 content = enforce_byte_cap(content, MAX_FRAGMENT_BYTES);
162 }
163 let content_hash = hash_content(&content);
164 Self {
165 id,
166 role: id.role(),
167 marker: id.marker(),
168 max_bytes: clamped_max,
169 content,
170 content_hash,
171 }
172 }
173 #[must_use]
174 pub fn project_instructions(raw: impl Into<String>) -> Self {
175 Self::with_max_bytes(FragmentId::ProjectInstructions, raw, MAX_FRAGMENT_BYTES)
176 }
177 #[must_use]
178 pub fn constitution(raw: impl Into<String>) -> Self {
179 Self::with_max_bytes(FragmentId::Constitution, raw, MAX_FRAGMENT_BYTES)
180 }
181 #[must_use]
182 pub fn render_marked(&self) -> String {
183 format!("{}\n{}", self.marker, self.content.trim_end())
184 }
185 }
186
187 impl ContextFragment for BoundedFragment {
188 fn fragment_id(&self) -> FragmentId {
189 self.id
190 }
191 fn marker(&self) -> &'static str {
192 self.marker
193 }
194 fn content(&self) -> &str {
195 &self.content
196 }
197 fn max_bytes(&self) -> usize {
198 self.max_bytes
199 }
200 }
201
202 #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
203 pub enum FragmentCapError {
204 #[error("fragment {id:?} exceeds 10K-token ceiling: {tokens} tokens ({bytes} bytes)")]
205 TokenCeiling {
206 id: FragmentId,
207 tokens: usize,
208 bytes: usize,
209 },
210 #[error("fragment {id:?} exceeds byte ceiling: {bytes} > {max} bytes")]
211 ByteCeiling {
212 id: FragmentId,
213 bytes: usize,
214 max: usize,
215 },
216 #[error("context has too many fragments: {count} > {max}")]
217 TooManyFragments { count: usize, max: usize },
218 }
219
220 pub fn validate_fragment(fragment: &BoundedFragment) -> Result<(), FragmentCapError> {
221 if fragment.content.len() > MAX_FRAGMENT_BYTES {
222 return Err(FragmentCapError::ByteCeiling {
223 id: fragment.id,
224 bytes: fragment.content.len(),
225 max: MAX_FRAGMENT_BYTES,
226 });
227 }
228 let tokens = estimate_tokens(&fragment.content);
229 if tokens > MAX_FRAGMENT_TOKENS {
230 return Err(FragmentCapError::TokenCeiling {
231 id: fragment.id,
232 bytes: fragment.content.len(),
233 tokens,
234 });
235 }
236 Ok(())
237 }
238
239 pub fn validate_fragment_set(fragments: &[BoundedFragment]) -> Result<(), FragmentCapError> {
240 if fragments.len() > MAX_FRAGMENTS_PER_CONTEXT {
241 return Err(FragmentCapError::TooManyFragments {
242 count: fragments.len(),
243 max: MAX_FRAGMENTS_PER_CONTEXT,
244 });
245 }
246 for f in fragments {
247 validate_fragment(f)?;
248 }
249 Ok(())
250 }
251
252 // Project-instruction import (#3978)
253 pub const PROJECT_INSTRUCTION_CANDIDATES: &[&str] = &[
254 "AGENTS.md",
255 ".agents/AGENTS.md",
256 "CLAUDE.md",
257 ".claude/instructions.md",
258 ".codewhale/instructions.md",
259 ".deepseek/instructions.md",
260 ".cursorrules",
261 ".cursor/rules",
262 ".clinerules",
263 ".windsurf/rules",
264 ".gemini",
265 ".github/copilot-instructions.md",
266 ".github/muse-instructions.md",
267 ];
268
269 /// Workspace instruction formats not already owned by Codewhale's canonical
270 /// project-context loader. The TUI uses this subset to avoid injecting
271 /// `AGENTS.md` / `CLAUDE.md` / `instructions.md` twice while still importing
272 /// additional agent rule formats through the typed fragment boundary.
273 pub const ADDITIONAL_PROJECT_INSTRUCTION_CANDIDATES: &[&str] = &[
274 ".agents/AGENTS.md",
275 ".cursorrules",
276 ".cursor/rules",
277 ".clinerules",
278 ".windsurf/rules",
279 ".gemini",
280 ".github/copilot-instructions.md",
281 ".github/muse-instructions.md",
282 ];
283
284 fn is_symlink(p: &Path) -> bool {
285 std::fs::symlink_metadata(p)
286 .map(|m| m.file_type().is_symlink())
287 .unwrap_or(false)
288 }
289 pub fn read_project_instruction_file(file: std::fs::File) -> Option<String> {
290 let meta = file.metadata().ok()?;
291 if !meta.is_file() {
292 return None;
293 }
294 use std::io::Read as _;
295 let mut buf = Vec::new();
296 file.take(INSTRUCTIONS_FILE_MAX_BYTES as u64 + 1)
297 .read_to_end(&mut buf)
298 .ok()?;
299 let observed_len = buf.len() as u64;
300 if meta.len().max(observed_len) > INSTRUCTIONS_FILE_MAX_BYTES as u64 {
301 buf.truncate(INSTRUCTIONS_FILE_MAX_BYTES);
302 let mut text = String::from_utf8_lossy(&buf).into_owned();
303 let mut end = INSTRUCTIONS_FILE_MAX_BYTES.min(text.len());
304 while end > 0 && !text.is_char_boundary(end) {
305 end -= 1;
306 }
307 text.truncate(end);
308 let omitted = meta
309 .len()
310 .max(observed_len)
311 .saturating_sub(INSTRUCTIONS_FILE_MAX_BYTES as u64);
312 text.push_str(&format!("\n[…truncated: {omitted} bytes omitted]"));
313 return Some(text);
314 }
315 let raw = String::from_utf8(buf).ok()?;
316 let trimmed = raw.trim();
317 if trimmed.is_empty() {
318 None
319 } else {
320 Some(trimmed.to_string())
321 }
322 }
323 fn collect_candidate_files(workspace: &Path, candidates: &[&str]) -> Vec<PathBuf> {
324 let mut files = Vec::new();
325 for candidate in candidates {
326 let path = workspace.join(candidate);
327 // `is_dir()` follows symlinks, so a symlinked `.cursor/rules` pointing
328 // outside the workspace used to be traversed: every file behind it is a
329 // real file, so the per-entry symlink checks below all passed and the
330 // escape succeeded. `project_context.rs` already refuses symlinked
331 // rules directories for exactly this reason; the two loaders now agree.
332 if path.is_dir() && !is_symlink(&path) {
333 let mut dir_files = Vec::new();
334 if let Ok(entries) = std::fs::read_dir(&path) {
335 for e in entries.flatten() {
336 let p = e.path();
337 if p.is_file() && p.extension().is_some_and(|e| e == "md") && !is_symlink(&p) {
338 dir_files.push(p);
339 }
340 }
341 }
342 if let Ok(entries) = std::fs::read_dir(&path) {
343 for e in entries.flatten() {
344 let p = e.path();
345 if p.is_dir()
346 && !is_symlink(&p)
347 && let Ok(sub) = std::fs::read_dir(&p)
348 {
349 for se in sub.flatten() {
350 let sp = se.path();
351 if sp.is_file()
352 && sp.extension().is_some_and(|e| e == "md")
353 && !is_symlink(&sp)
354 {
355 dir_files.push(sp);
356 }
357 }
358 }
359 }
360 }
361 dir_files.sort();
362 let remaining = MAX_INSTRUCTION_FILES.saturating_sub(files.len());
363 dir_files.truncate(remaining);
364 files.extend(dir_files);
365 } else if path.is_file() && !is_symlink(&path) {
366 files.push(path);
367 }
368 if files.len() >= MAX_INSTRUCTION_FILES {
369 break;
370 }
371 }
372 files.truncate(MAX_INSTRUCTION_FILES);
373 files.sort();
374 files.dedup();
375 files
376 }
377
378 /// Enumerate the safe, bounded file paths selected for a caller-provided set
379 /// of project-instruction candidates.
380 ///
381 /// This is the same traversal used by
382 /// [`load_selected_project_instruction_fragment`]. Callers that cache the
383 /// loader's result can fingerprint these paths without maintaining a second,
384 /// subtly different directory walk. Content validation still happens in the
385 /// loader: an empty, unreadable, or non-UTF-8 file may be selected here and
386 /// then contribute no fragment.
387 #[must_use]
388 pub fn selected_project_instruction_candidate_files(
389 workspace: &Path,
390 candidates: &[&str],
391 ) -> Vec<PathBuf> {
392 collect_candidate_files(workspace, candidates)
393 }
394
395 fn load_project_instruction_fragment_from_candidates(
396 workspace: &Path,
397 candidates: &[&str],
398 mut opener: impl FnMut(&Path) -> std::io::Result<std::fs::File>,
399 ) -> Option<BoundedFragment> {
400 let files = collect_candidate_files(workspace, candidates);
401 if files.is_empty() {
402 return None;
403 }
404 let mut sections = Vec::new();
405 for path in files {
406 if let Some(content) = opener(&path).ok().and_then(read_project_instruction_file) {
407 let rel = path
408 .strip_prefix(workspace)
409 .unwrap_or(&path)
410 .display()
411 .to_string();
412 sections.push(format!(
413 "<project_instructions source=\"{rel}\">\n{content}\n</project_instructions>"
414 ));
415 }
416 }
417 if sections.is_empty() {
418 return None;
419 }
420 let merged = sections.join("\n\n");
421 let fragment = BoundedFragment::project_instructions(merged);
422 debug_assert!(validate_fragment(&fragment).is_ok());
423 Some(fragment)
424 }
425
426 pub fn load_project_instruction_fragment(workspace: &Path) -> Option<BoundedFragment> {
427 load_project_instruction_fragment_from_candidates(
428 workspace,
429 PROJECT_INSTRUCTION_CANDIDATES,
430 |path| std::fs::File::open(path),
431 )
432 }
433
434 /// Load only instruction formats that the canonical TUI project-context path
435 /// does not already render. This prevents duplicate authority while retaining
436 /// the broader compatibility import added by the bounded fragment system.
437 ///
438 /// Prefer [`load_selected_project_instruction_fragment`]: importing every
439 /// foreign format unconditionally makes another tool's instruction file
440 /// standing authority here without anyone asking for it.
441 pub fn load_additional_project_instruction_fragment(workspace: &Path) -> Option<BoundedFragment> {
442 load_project_instruction_fragment_from_candidates(
443 workspace,
444 ADDITIONAL_PROJECT_INSTRUCTION_CANDIDATES,
445 |path| std::fs::File::open(path),
446 )
447 }
448
449 /// Load exactly the instruction candidates the caller names.
450 ///
451 /// The caller owns the opt-in decision; an empty list imports nothing and
452 /// yields `None` rather than silently falling back to the full candidate set.
453 pub fn load_selected_project_instruction_fragment(
454 workspace: &Path,
455 candidates: &[&str],
456 ) -> Option<BoundedFragment> {
457 load_selected_project_instruction_fragment_with_reader(workspace, candidates, |path| {
458 std::fs::File::open(path)
459 })
460 }
461
462 pub fn load_selected_project_instruction_fragment_with_reader(
463 workspace: &Path,
464 candidates: &[&str],
465 opener: impl FnMut(&Path) -> std::io::Result<std::fs::File>,
466 ) -> Option<BoundedFragment> {
467 if candidates.is_empty() {
468 return None;
469 }
470 load_project_instruction_fragment_from_candidates(workspace, candidates, opener)
471 }
472
473 pub fn project_instructions_from_sources(
474 sources: impl IntoIterator<Item = (String, String)>,
475 ) -> Option<BoundedFragment> {
476 let mut sections = Vec::new();
477 for (name, content) in sources {
478 let trimmed = content.trim();
479 if trimmed.is_empty() {
480 continue;
481 }
482 let body = if trimmed.len() > INSTRUCTIONS_FILE_MAX_BYTES {
483 let mut end = INSTRUCTIONS_FILE_MAX_BYTES;
484 while end > 0 && !trimmed.is_char_boundary(end) {
485 end -= 1;
486 }
487 let omitted = trimmed.len() - end;
488 format!("{}\n[…truncated: {omitted} bytes omitted]", &trimmed[..end])
489 } else {
490 trimmed.to_string()
491 };
492 sections.push(format!(
493 "<project_instructions source=\"{name}\">\n{body}\n</project_instructions>"
494 ));
495 if sections.len() >= MAX_INSTRUCTION_FILES {
496 break;
497 }
498 }
499 if sections.is_empty() {
500 return None;
501 }
502 Some(BoundedFragment::project_instructions(sections.join("\n\n")))
503 }
504
505 #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
506 pub struct FragmentBudgetSnapshot {
507 pub fragment_ids: Vec<String>,
508 pub fragment_markers: Vec<String>,
509 pub max_fragment_bytes: usize,
510 pub max_fragment_tokens: usize,
511 pub default_fragment_max_bytes: usize,
512 pub max_fragments_per_context: usize,
513 pub instructions_file_max_bytes: usize,
514 pub max_instruction_files: usize,
515 pub project_instruction_candidates: Vec<String>,
516 }
517
518 #[must_use]
519 pub fn fragment_budget_snapshot() -> FragmentBudgetSnapshot {
520 FragmentBudgetSnapshot {
521 fragment_ids: FragmentId::all()
522 .iter()
523 .map(|id| id.as_str().to_string())
524 .collect(),
525 fragment_markers: FragmentId::all()
526 .iter()
527 .map(|id| id.marker().to_string())
528 .collect(),
529 max_fragment_bytes: MAX_FRAGMENT_BYTES,
530 max_fragment_tokens: MAX_FRAGMENT_TOKENS,
531 default_fragment_max_bytes: DEFAULT_FRAGMENT_MAX_BYTES,
532 max_fragments_per_context: MAX_FRAGMENTS_PER_CONTEXT,
533 instructions_file_max_bytes: INSTRUCTIONS_FILE_MAX_BYTES,
534 max_instruction_files: MAX_INSTRUCTION_FILES,
535 project_instruction_candidates: PROJECT_INSTRUCTION_CANDIDATES
536 .iter()
537 .map(|s| s.to_string())
538 .collect(),
539 }
540 }
541
542 fn hash_content(content: &str) -> u64 {
543 let mut hasher = DefaultHasher::new();
544 content.hash(&mut hasher);
545 hasher.finish()
546 }
547 fn enforce_byte_cap(raw: String, max_bytes: usize) -> String {
548 if max_bytes == 0 {
549 return String::new();
550 }
551 if raw.len() <= max_bytes {
552 return raw;
553 }
554 let omitted = raw.len().saturating_sub(max_bytes);
555 let marker = format!("\n[…truncated: {omitted} bytes omitted]");
556 if marker.len() >= max_bytes {
557 return marker.chars().take(max_bytes).collect();
558 }
559 let keep = max_bytes.saturating_sub(marker.len());
560 let mut end = keep;
561 while end > 0 && !raw.is_char_boundary(end) {
562 end -= 1;
563 }
564 let mut out = raw[..end].to_string();
565 out.push_str(&marker);
566 out
567 }
568
569 #[cfg(test)]
570 mod tests {
571 use super::*;
572 use std::fs;
573 use tempfile::tempdir;
574
575 #[test]
576 fn fragment_has_matches_text_recognizer() {
577 let fragment = BoundedFragment::new(FragmentId::Workspace, "repo: /tmp/demo");
578 let rendered = fragment.render_marked();
579 assert!(fragment.matches_text(&rendered));
580 assert!(!fragment.matches_text("no marker here"));
581 assert_eq!(FragmentId::Workspace.marker(), "<!-- cw:ctx:workspace -->");
582 assert_eq!(
583 FragmentId::ProjectInstructions.marker(),
584 "<!-- cw:ctx:project_instructions -->"
585 );
586 assert_eq!(
587 FragmentId::Constitution.marker(),
588 "<!-- cw:ctx:constitution -->"
589 );
590 }
591 #[test]
592 fn all_fragment_types_go_through_bounded_module() {
593 for id in FragmentId::all() {
594 let fragment = BoundedFragment::new(*id, "hello");
595 assert_eq!(fragment.marker, id.marker());
596 assert_eq!(fragment.id, *id);
597 validate_fragment(&fragment).expect("small fragment must pass caps");
598 assert!(fragment.is_within_token_ceiling());
599 assert!(fragment.is_within_byte_ceiling());
600 }
601 }
602 #[test]
603 fn per_fragment_byte_cap_truncates_with_marker() {
604 let oversized = "x".repeat(DEFAULT_FRAGMENT_MAX_BYTES + 64);
605 let fragment = BoundedFragment::new(FragmentId::AgentTopology, oversized);
606 assert!(fragment.content.len() <= DEFAULT_FRAGMENT_MAX_BYTES);
607 assert!(fragment.content.contains("[…truncated:"));
608 validate_fragment(&fragment).expect("truncated fragment must pass caps");
609 }
610 #[test]
611 fn ten_k_token_ceiling_is_enforced() {
612 let huge = "a".repeat(MAX_FRAGMENT_BYTES + 1_000);
613 let fragment = BoundedFragment::project_instructions(huge);
614 assert!(fragment.content.len() <= MAX_FRAGMENT_BYTES);
615 assert!(estimate_tokens(&fragment.content) <= MAX_FRAGMENT_TOKENS);
616 validate_fragment(&fragment).expect("capped fragment must satisfy token ceiling");
617 let also_huge = "b".repeat(MAX_FRAGMENT_BYTES + 5000);
618 let fragment = BoundedFragment::with_max_bytes(FragmentId::Workspace, also_huge, 100_000);
619 assert!(fragment.max_bytes <= MAX_FRAGMENT_BYTES);
620 assert!(fragment.content.len() <= MAX_FRAGMENT_BYTES);
621 assert!(fragment.is_within_token_ceiling());
622 }
623 #[test]
624 fn injected_item_count_cap_is_enforced() {
625 let fragments: Vec<BoundedFragment> = (0..MAX_FRAGMENTS_PER_CONTEXT)
626 .map(|i| BoundedFragment::new(FragmentId::Workspace, format!("item {i}")))
627 .collect();
628 validate_fragment_set(&fragments).expect("exactly MAX_FRAGMENTS must pass");
629 let mut too_many = fragments.clone();
630 too_many.push(BoundedFragment::new(FragmentId::Route, "one too many"));
631 let err = validate_fragment_set(&too_many).expect_err("one over cap must fail");
632 assert!(matches!(err, FragmentCapError::TooManyFragments { .. }));
633 }
634 #[test]
635 #[cfg(unix)]
636 fn symlinked_candidate_directory_cannot_escape_the_workspace() {
637 // `Path::is_dir()` follows symlinks, so a symlinked candidate dir used
638 // to be traversed: every file behind it is a real file, so the
639 // per-entry symlink checks passed and content outside the workspace was
640 // imported as project instruction authority.
641 let outside = tempdir().expect("outside");
642 fs::write(outside.path().join("leaked.md"), "SECRET-OUTSIDE-WORKSPACE")
643 .expect("write outside");
644
645 let dir = tempdir().expect("workspace");
646 let ws = dir.path();
647 fs::create_dir_all(ws.join(".cursor")).expect("mkdir .cursor");
648 std::os::unix::fs::symlink(outside.path(), ws.join(".cursor").join("rules"))
649 .expect("symlink rules dir");
650
651 let fragment = load_selected_project_instruction_fragment(ws, &[".cursor/rules"]);
652 assert!(
653 fragment.is_none(),
654 "a symlinked candidate directory must not be traversed: {fragment:?}"
655 );
656 }
657
658 #[test]
659 fn selected_candidates_import_nothing_when_the_list_is_empty() {
660 let dir = tempdir().expect("tempdir");
661 let ws = dir.path();
662 fs::write(ws.join(".cursorrules"), "cursor: always use tabs").expect("write cursor");
663 assert!(
664 load_selected_project_instruction_fragment(ws, &[]).is_none(),
665 "an empty opt-in list must import nothing, not fall back to every format"
666 );
667 assert!(
668 load_selected_project_instruction_fragment(ws, &[".cursorrules"]).is_some(),
669 "an explicitly named candidate is still imported"
670 );
671 }
672
673 #[test]
674 fn project_instruction_import_is_a_typed_fragment() {
675 let dir = tempdir().expect("tempdir");
676 let ws = dir.path();
677 fs::write(ws.join(".cursorrules"), "cursor: always use tabs").expect("write cursor");
678 fs::write(ws.join(".clinerules"), "cline: prefer functional style").expect("write cline");
679 fs::create_dir_all(ws.join(".windsurf").join("rules")).expect("mkdir windsurf");
680 fs::write(
681 ws.join(".windsurf").join("rules").join("extra.md"),
682 "# windsurf extra",
683 )
684 .expect("write windsurf");
685 fs::create_dir_all(ws.join(".github")).expect("mkdir github");
686 fs::write(
687 ws.join(".github").join("copilot-instructions.md"),
688 "# copilot says hello",
689 )
690 .expect("write copilot");
691 let fragment =
692 load_project_instruction_fragment(ws).expect("must find imported instructions");
693 assert_eq!(fragment.id, FragmentId::ProjectInstructions);
694 assert!(fragment.matches_text(&fragment.render_marked()));
695 assert!(
696 fragment.content.contains(".cursorrules") || fragment.content.contains(".clinerules")
697 );
698 validate_fragment(&fragment).expect("project-instructions fragment must satisfy caps");
699 let from_sources = project_instructions_from_sources(vec![
700 ("AGENTS.md".to_string(), "# AGENTS\nbe helpful".to_string()),
701 (
702 ".cursorrules".to_string(),
703 "cursor: do the thing".to_string(),
704 ),
705 ])
706 .expect("sources");
707 assert_eq!(from_sources.id, FragmentId::ProjectInstructions);
708 assert!(from_sources.content.contains("AGENTS.md"));
709 assert!(from_sources.content.contains(".cursorrules"));
710 validate_fragment(&from_sources).expect("explicit sources must also satisfy caps");
711 }
712 #[test]
713 fn additional_project_instruction_import_does_not_duplicate_canonical_authority() {
714 let dir = tempdir().expect("tempdir");
715 let ws = dir.path();
716 fs::write(ws.join("AGENTS.md"), "canonical authority marker").expect("write agents");
717
718 assert!(
719 load_additional_project_instruction_fragment(ws).is_none(),
720 "AGENTS.md is already owned by the canonical project-context loader"
721 );
722
723 fs::write(ws.join(".cursorrules"), "additional cursor marker").expect("write cursor rules");
724 let additional = load_additional_project_instruction_fragment(ws)
725 .expect("additional rules must produce a typed fragment");
726 assert!(additional.content.contains("additional cursor marker"));
727 assert!(!additional.content.contains("canonical authority marker"));
728
729 let complete = load_project_instruction_fragment(ws)
730 .expect("complete importer must retain every supported source");
731 assert!(complete.content.contains("canonical authority marker"));
732 assert!(complete.content.contains("additional cursor marker"));
733 }
734 #[test]
735 fn fragment_budget_snapshot_is_stable() {
736 let snap = fragment_budget_snapshot();
737 assert_eq!(snap.max_fragment_tokens, 10_000);
738 assert_eq!(snap.max_fragment_bytes, 40_000);
739 assert_eq!(snap.max_fragments_per_context, 16);
740 assert_eq!(snap.default_fragment_max_bytes, 4 * 1024);
741 assert!(
742 snap.fragment_ids
743 .contains(&"project_instructions".to_string())
744 );
745 assert!(snap.fragment_ids.contains(&"constitution".to_string()));
746 assert!(
747 snap.project_instruction_candidates
748 .contains(&".cursorrules".to_string())
749 );
750 assert!(
751 snap.project_instruction_candidates
752 .contains(&".github/copilot-instructions.md".to_string())
753 );
754 assert!(
755 snap.fragment_markers
756 .contains(&"<!-- cw:ctx:project_instructions -->".to_string())
757 );
758 }
759 }
760
760 lines RUST