1use std::io::Read;
19use std::path::{Path, PathBuf};
20
21pub const DEFAULT_MAX_FILE_CHARS: usize = 6000;
23pub const DEFAULT_BUDGET_CHARS: usize = 12000;
25const MIN_CLIP: usize = 120;
28const MAX_WALK: usize = 64;
31const MAX_LAYER_BYTES: u64 = 1 << 20;
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub struct Budget {
40 pub max_file_chars: usize,
42 pub total_chars: usize,
44}
45
46impl Default for Budget {
47 fn default() -> Self {
48 Self {
49 max_file_chars: DEFAULT_MAX_FILE_CHARS,
50 total_chars: DEFAULT_BUDGET_CHARS,
51 }
52 }
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Layer {
58 pub name: String,
60 pub path: PathBuf,
61 pub body: String,
63 pub chars: usize,
65 pub original_chars: usize,
67}
68
69impl Layer {
70 pub fn truncated(&self) -> bool {
71 self.original_chars > self.chars
72 }
73}
74
75#[derive(Debug, Clone, Default, PartialEq, Eq)]
77pub struct Context {
78 pub instructions: Vec<Layer>,
81 pub user: Option<Layer>,
82 pub memory: Option<Layer>,
83 pub skills: Option<crate::skills::Index>,
86 pub notes: Vec<String>,
88 pub skill_notes: Vec<String>,
92 pub guidance: String,
96}
97
98impl Context {
99 fn with_guidance(mut self, cfg: &crate::config::Config) -> Self {
105 self.guidance = cfg.agent.prompt_blocks.guidance(&cfg.provider.model);
106 self
107 }
108
109 pub fn layers(&self) -> impl Iterator<Item = &Layer> {
111 self.instructions
112 .iter()
113 .chain(self.user.iter())
114 .chain(self.memory.iter())
115 }
116
117 pub fn total_chars(&self) -> usize {
118 self.layers().map(|l| l.chars).sum()
119 }
120
121 pub fn is_empty(&self) -> bool {
122 self.layers().next().is_none() && self.skills.is_none()
123 }
124
125 pub fn with_skills(mut self, report: &crate::skills::Report, budget: usize) -> Self {
127 let (index, notes) = crate::skills::index(report, budget);
128 self.skills = index;
129 self.skill_notes = notes;
130 self
131 }
132}
133
134pub struct Sources<'a> {
137 pub config_dir: Option<&'a Path>,
139 pub profile_dir: Option<&'a Path>,
141 pub workspace: &'a Path,
143 pub home: Option<&'a Path>,
145 pub user_file: &'a str,
147 pub memory_file: &'a str,
148}
149
150pub fn gather(sources: &Sources<'_>, budget: Budget) -> Context {
152 let mut ctx = Context::default();
153
154 if let Some(dir) = sources.config_dir {
155 if let Some(path) = context_file_in(dir) {
156 let name = layer_name(&path);
157 push_layer(
158 &mut ctx.instructions,
159 &name,
160 path,
161 None,
162 budget,
163 &mut ctx.notes,
164 );
165 }
166 }
167 let (project, root) = project_walk(sources.workspace, sources.home);
172 for path in project {
173 let name = layer_name(&path);
174 push_layer(
175 &mut ctx.instructions,
176 &name,
177 path,
178 Some(&root),
179 budget,
180 &mut ctx.notes,
181 );
182 }
183 if let Some(dir) = sources.profile_dir {
184 ctx.user = read_layer(
185 sources.user_file,
186 dir.join(sources.user_file),
187 None,
188 budget,
189 &mut ctx.notes,
190 );
191 ctx.memory = read_layer(
192 sources.memory_file,
193 dir.join(sources.memory_file),
194 None,
195 budget,
196 &mut ctx.notes,
197 )
198 .map(render_memory);
199 }
200 apply_total(&mut ctx, budget.total_chars);
201 ctx
202}
203
204pub fn project_files(workspace: &Path, home: Option<&Path>) -> Vec<PathBuf> {
211 project_walk(workspace, home).0
212}
213
214pub fn project_walk(workspace: &Path, home: Option<&Path>) -> (Vec<PathBuf>, PathBuf) {
219 let home = home.and_then(|h| std::fs::canonicalize(h).ok().or(Some(h.to_path_buf())));
220 let mut dir = std::fs::canonicalize(workspace).unwrap_or_else(|_| workspace.to_path_buf());
221 let mut found: Vec<PathBuf> = Vec::new();
222 for _ in 0..MAX_WALK {
223 if let Some(path) = agent_file_in(&dir) {
224 found.push(path);
225 }
226 if dir.join(".git").exists() {
228 break;
229 }
230 let Some(parent) = dir.parent() else { break };
231 if let Some(ref home) = home {
237 if !parent.starts_with(home) {
238 break;
239 }
240 }
241 dir = parent.to_path_buf();
242 }
243 found.reverse();
244 let top = std::fs::canonicalize(&dir).unwrap_or(dir);
248 (found, top)
249}
250
251fn agent_file_in(dir: &Path) -> Option<PathBuf> {
252 [
257 dir.join("AGENT.md"),
258 dir.join(".eclipse").join("AGENT.md"),
259 dir.join("AGENTS.md"),
260 dir.join(".eclipse").join("AGENTS.md"),
261 ]
262 .into_iter()
263 .find(|candidate| candidate.is_file())
264}
265
266fn context_file_in(dir: &Path) -> Option<PathBuf> {
269 ["AGENT.md", "AGENTS.md"]
270 .iter()
271 .map(|name| dir.join(*name))
272 .find(|path| path.is_file())
273}
274
275fn layer_name(path: &Path) -> String {
278 path.file_name()
279 .map(|n| n.to_string_lossy().into_owned())
280 .unwrap_or_else(|| "AGENT.md".to_string())
281}
282
283fn render_memory(layer: Layer) -> Layer {
287 let entries = crate::memory::parse(&layer.body);
288 let body = entries
289 .iter()
290 .map(|entry| {
291 let mut lines = entry.lines();
292 let mut out = format!("- {}", lines.next().unwrap_or("").trim());
293 for line in lines {
294 out.push_str("\n ");
295 out.push_str(line.trim());
296 }
297 out
298 })
299 .collect::<Vec<_>>()
300 .join("\n");
301 Layer {
302 chars: body.chars().count(),
303 original_chars: layer.original_chars,
304 body,
305 ..layer
306 }
307}
308
309fn push_layer(
310 into: &mut Vec<Layer>,
311 name: &str,
312 path: PathBuf,
313 boundary: Option<&Path>,
314 budget: Budget,
315 notes: &mut Vec<String>,
316) {
317 if let Some(layer) = read_layer(name, path, boundary, budget, notes) {
318 into.push(layer);
319 }
320}
321
322fn read_layer(
337 name: &str,
338 path: PathBuf,
339 boundary: Option<&Path>,
340 budget: Budget,
341 notes: &mut Vec<String>,
342) -> Option<Layer> {
343 let shown = path.display().to_string();
344 match std::fs::metadata(&path) {
347 Ok(meta) if meta.is_file() => {}
348 Ok(_) => {
349 notes.push(format!("{name} at {shown} is not a regular file; not read"));
350 return None;
351 }
352 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None,
353 Err(e) => {
354 notes.push(format!("{name} at {shown} could not be read: {e}"));
355 return None;
356 }
357 }
358 let path = std::fs::canonicalize(&path).unwrap_or(path);
360 if let Some(root) = boundary {
361 if !path.starts_with(root) {
362 notes.push(format!(
363 "{name} at {shown} points outside the project ({}); not read",
364 path.display()
365 ));
366 return None;
367 }
368 }
369 let raw = read_capped(&path, name, notes)?;
370 let original = raw.chars().count();
371 if raw.trim().is_empty() {
372 return None; }
374 let body = clip(&raw, budget.max_file_chars);
375 let chars = body.chars().count();
376 Some(Layer {
377 name: name.to_string(),
378 path,
379 body,
380 chars,
381 original_chars: original,
382 })
383}
384
385fn read_capped(path: &Path, name: &str, notes: &mut Vec<String>) -> Option<String> {
392 let file = std::fs::File::open(path).ok()?;
393 let mut bytes = Vec::new();
394 file.take(MAX_LAYER_BYTES + 1)
395 .read_to_end(&mut bytes)
396 .ok()?;
397 let cut = bytes.len() as u64 > MAX_LAYER_BYTES;
398 if cut {
399 bytes.truncate(MAX_LAYER_BYTES as usize);
400 }
401 let text = match String::from_utf8(bytes) {
402 Ok(text) => text,
403 Err(e) => {
404 if !cut || e.utf8_error().error_len().is_some() {
405 return None;
406 }
407 let valid = e.utf8_error().valid_up_to();
408 let bytes = e.into_bytes();
409 String::from_utf8_lossy(&bytes[..valid]).into_owned()
410 }
411 };
412 if cut {
413 notes.push(format!(
414 "{name} is larger than {} KB and was read only to that point",
415 MAX_LAYER_BYTES / 1024
416 ));
417 }
418 Some(text)
419}
420
421fn clip(text: &str, max: usize) -> String {
425 let total = text.chars().count();
426 if total <= max || max == 0 {
427 return text.to_string();
428 }
429 let full = |removed: usize| format!("\n\n[… truncated: {removed} chars …]\n\n");
430 let tight = format!("[…{total}c…]");
433 let mut room = max.saturating_sub(full(total).chars().count());
434 if room < 12 {
435 return if tight.chars().count() <= max {
436 tight
437 } else {
438 tight.chars().take(max).collect()
439 };
440 }
441 loop {
444 let head_budget = room / 2;
445 let tail_budget = room - head_budget;
446 let removed = total.saturating_sub(head_budget + tail_budget);
447 let marker = full(removed);
448 let fits = head_budget + tail_budget + marker.chars().count();
449 if fits <= max {
450 let head: String = text.chars().take(head_budget).collect();
451 let tail: String = text
452 .chars()
453 .rev()
454 .take(tail_budget)
455 .collect::<Vec<_>>()
456 .into_iter()
457 .rev()
458 .collect();
459 return format!("{head}{marker}{tail}");
460 }
461 let next = max.saturating_sub(marker.chars().count() + 1);
462 if next >= room {
463 return tight;
464 }
465 room = next;
466 }
467}
468
469fn apply_total(ctx: &mut Context, total: usize) {
477 if total == 0 || ctx.total_chars() <= total {
478 return;
479 }
480 let mut notes = Vec::new();
481 while ctx.total_chars() > total && !ctx.instructions.is_empty() {
482 let layer = ctx.instructions.remove(0);
483 notes.push(dropped(&layer, total));
484 }
485 if ctx.total_chars() > total {
486 if let Some(layer) = ctx.memory.take() {
487 notes.push(dropped(&layer, total));
488 }
489 }
490 if ctx.total_chars() > total {
491 if let Some(mut layer) = ctx.user.take() {
492 let left = total.saturating_sub(ctx.total_chars());
493 if left >= MIN_CLIP {
494 let body = clip(&layer.body, left);
495 notes.push(format!(
496 "clipped {} to {left} chars to fit the {total} char budget",
497 layer.path.display()
498 ));
499 layer.chars = body.chars().count();
500 layer.body = body;
501 ctx.user = Some(layer);
502 } else {
503 notes.push(dropped(&layer, total));
504 }
505 }
506 }
507 ctx.notes.extend(notes);
508}
509
510fn dropped(layer: &Layer, total: usize) -> String {
511 format!(
512 "dropped {} ({} chars): over the {total} char budget",
513 layer.path.display(),
514 layer.chars
515 )
516}
517
518pub fn for_config(
522 cfg: &crate::config::Config,
523 env: crate::config::EnvFn,
524 plugins: &crate::plugins::Plugins,
525) -> Context {
526 for_config_with(cfg, env, plugins, None)
527}
528
529pub fn for_config_with(
534 cfg: &crate::config::Config,
535 env: crate::config::EnvFn,
536 plugins: &crate::plugins::Plugins,
537 only: Option<&[String]>,
538) -> Context {
539 let workspace = cfg.workspace_root(env);
540 let ctx = gather_for(cfg, env);
541 let report = crate::skills::discover_only(
542 &crate::skills::roots_for(cfg, env, plugins, &workspace),
543 only,
544 );
545 ctx.with_skills(&report, cfg.skills.index_budget_chars)
546}
547
548fn gather_for(cfg: &crate::config::Config, env: crate::config::EnvFn) -> Context {
552 let workspace = cfg.workspace_root(env);
553 let config_root = cfg.memory_dir(env);
556 let profile_dir = config_root.clone();
557 let home = cfg.home(env);
558 let sources = Sources {
559 config_dir: config_root.as_deref(),
560 profile_dir: profile_dir.as_deref(),
561 workspace: &workspace,
562 home: home.as_deref(),
563 user_file: &cfg.user.file,
564 memory_file: &cfg.user.memory_file,
565 };
566 gather(
567 &sources,
568 Budget {
569 max_file_chars: cfg.agent.context_file_max_chars,
570 total_chars: cfg.agent.context_files_budget_chars,
571 },
572 )
573 .with_guidance(cfg)
574}
575
576#[derive(Debug, Clone, Copy, PartialEq, Eq)]
579pub enum Which {
580 Agent,
582 User,
584 Memory,
586}
587
588impl Which {
589 pub fn id(self) -> &'static str {
593 match self {
594 Which::Agent => "agent",
595 Which::User => "user",
596 Which::Memory => "memory",
597 }
598 }
599
600 pub fn from_id(id: &str) -> Option<Self> {
601 match id {
602 "agent" => Some(Which::Agent),
603 "user" => Some(Which::User),
604 "memory" => Some(Which::Memory),
605 _ => None,
606 }
607 }
608}
609
610#[derive(Debug, Clone, PartialEq, Eq)]
613pub struct Editable {
614 pub which: Which,
615 pub file: String,
617 pub path: PathBuf,
620 pub exists: bool,
621 pub text: String,
624 pub chars: usize,
626 pub kept: usize,
628 pub max_chars: usize,
630 pub own_budget: Option<usize>,
633 pub total: usize,
635 pub total_budget: usize,
636 pub position: Option<usize>,
638 pub others: usize,
640}
641
642impl Editable {
643 pub fn truncated(&self) -> bool {
644 self.kept < self.chars
645 }
646}
647
648pub fn editable(cfg: &crate::config::Config, env: crate::config::EnvFn) -> Vec<Editable> {
656 let ctx = gather_for(cfg, env);
657 let total = ctx.total_chars();
658 let total_budget = cfg.agent.context_files_budget_chars;
659 let max_chars = cfg.agent.context_file_max_chars;
660 let dir = cfg.memory_dir(env);
661
662 let layers: Vec<&Layer> = ctx.layers().collect();
663 let position_of = |path: &Path| layers.iter().position(|l| l.path == path).map(|i| i + 1);
664
665 let workspace = cfg.workspace_root(env);
666 let project = project_files(&workspace, cfg.home(env).as_deref());
667
668 let mut rows = Vec::new();
669
670 let agent = project
674 .last()
675 .cloned()
676 .or_else(|| Some(dir.as_ref()?.join("AGENT.md")));
677 if let Some(path) = agent {
678 let layer = layers.iter().find(|l| l.path == canonical_or(&path));
679 let agents = layers
683 .iter()
684 .filter(|l| l.name.starts_with("AGENT"))
685 .count();
686 let others = agents.saturating_sub(usize::from(layer.is_some()));
687 rows.push(row_from(
688 Which::Agent,
689 path,
690 layer.copied(),
691 max_chars,
692 None,
693 total,
694 total_budget,
695 position_of,
696 others,
697 ));
698 }
699 if let Some(dir) = dir.as_deref() {
700 for (which, file, own_budget) in [
701 (Which::User, cfg.user.file.clone(), None),
702 (
703 Which::Memory,
704 cfg.user.memory_file.clone(),
705 Some(cfg.user.memory_budget_chars),
706 ),
707 ] {
708 let path = dir.join(&file);
709 let layer = layers.iter().find(|l| l.path == canonical_or(&path));
710 rows.push(row_from(
711 which,
712 path,
713 layer.copied(),
714 max_chars,
715 own_budget,
716 total,
717 total_budget,
718 position_of,
719 0,
720 ));
721 }
722 }
723 rows
724}
725
726#[allow(clippy::too_many_arguments)]
727fn row_from(
728 which: Which,
729 path: PathBuf,
730 layer: Option<&Layer>,
731 max_chars: usize,
732 own_budget: Option<usize>,
733 total: usize,
734 total_budget: usize,
735 position_of: impl Fn(&Path) -> Option<usize>,
736 others: usize,
737) -> Editable {
738 let canonical = canonical_or(&path);
739 let text = std::fs::read_to_string(&canonical).unwrap_or_default();
740 let chars = text.chars().count();
741 let kept = layer.map_or(chars, |l| l.chars);
742 Editable {
743 which,
744 position: position_of(&canonical),
745 file: path
746 .file_name()
747 .map(|n| n.to_string_lossy().into_owned())
748 .unwrap_or_else(|| format!("{}.md", which.id())),
749 exists: canonical.is_file(),
750 chars,
751 kept,
752 max_chars,
753 own_budget,
754 total,
755 total_budget,
756 others,
757 path: canonical,
758 text,
759 }
760}
761
762fn canonical_or(path: &Path) -> PathBuf {
763 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
764}
765
766pub fn write_file(
777 cfg: &crate::config::Config,
778 env: crate::config::EnvFn,
779 which: Which,
780 text: &str,
781) -> crate::error::Result<Editable> {
782 let Some(row) = editable(cfg, env).into_iter().find(|r| r.which == which) else {
783 return Err(crate::error::Error::Config(format!(
784 "this configuration has no {} file to write",
785 which.id()
786 )));
787 };
788 match which {
789 Which::Memory => {
790 let memory = crate::memory::Memory::new(&row.path, cfg.user.memory_budget_chars);
791 if let crate::memory::Outcome::Full {
792 chars,
793 budget,
794 entries,
795 } = memory.replace(crate::memory::parse(text))?
796 {
797 return Err(crate::error::Error::Config(format!(
798 "{} would be {chars} chars and its budget is {budget}; it holds {} entr{} now — \
799 remove or shorten one here instead",
800 row.file,
801 entries.len(),
802 if entries.len() == 1 { "y" } else { "ies" }
803 )));
804 }
805 }
806 Which::Agent | Which::User => {
807 crate::atomic::write_file_atomically(&row.path, text)
808 .map_err(|e| crate::error::Error::io(&row.path, e))?;
809 }
810 }
811 let after = editable(cfg, env);
812 after.into_iter().find(|r| r.which == which).ok_or_else(|| {
813 crate::error::Error::Config("the file vanished while it was being written".into())
814 })
815}
816
817pub fn assemble(base: &str, ctx: &Context, fragments: &[String]) -> String {
823 let mut parts: Vec<String> = Vec::new();
824 let base = base.trim();
825 if !base.is_empty() {
826 parts.push(base.to_string());
827 }
828 let guidance = ctx.guidance.trim();
832 if !guidance.is_empty() {
833 parts.push(guidance.to_string());
834 }
835 for layer in &ctx.instructions {
836 parts.push(labelled(layer));
837 }
838 for fragment in fragments {
839 let fragment = fragment.trim();
840 if !fragment.is_empty() {
841 parts.push(fragment.to_string());
842 }
843 }
844 if let Some(user) = &ctx.user {
845 parts.push(labelled(user));
846 }
847 if let Some(memory) = &ctx.memory {
848 parts.push(labelled(memory));
849 }
850 if let Some(skills) = &ctx.skills {
851 parts.push(format!("## Skills\n\n{}", skills.body));
854 }
855 parts.join("\n\n")
856}
857
858fn labelled(layer: &Layer) -> String {
859 format!(
860 "## {} ({})\n\n{}",
861 layer.name,
862 layer.path.display(),
863 layer.body.trim_end()
864 )
865}
866
867#[cfg(test)]
868mod tests {
869 use super::*;
870
871 fn write(path: &Path, body: &str) {
872 if let Some(parent) = path.parent() {
873 std::fs::create_dir_all(parent).unwrap();
874 }
875 std::fs::write(path, body).unwrap();
876 }
877
878 fn three(
880 tmp: &tempfile::TempDir,
881 ) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) {
882 let config = tmp.path().join("config");
883 let profile = tmp.path().join("profile");
884 let workspace = tmp.path().join("work");
885 std::fs::create_dir_all(&workspace).unwrap();
886 (config, profile, workspace)
887 }
888
889 fn sources<'a>(config: &'a Path, profile: &'a Path, workspace: &'a Path) -> Sources<'a> {
890 Sources {
891 config_dir: Some(config),
892 profile_dir: Some(profile),
893 workspace,
894 home: None,
895 user_file: "USER.md",
896 memory_file: "MEMORY.md",
897 }
898 }
899
900 fn cfg_in(home: &Path, workspace: &Path) -> crate::config::Config {
903 let mut cfg = crate::config::Config::default();
904 cfg.tools.workspace_root = Some(workspace.to_path_buf());
905 cfg.profile = None;
906 let _ = home;
907 cfg
908 }
909
910 fn home_env(home: &Path) -> impl Fn(&str) -> Option<String> + '_ {
913 move |key: &str| match key {
914 "HOME" => Some(home.display().to_string()),
915 _ => None,
916 }
917 }
918
919 #[test]
922 fn the_standing_blocks_reach_the_assembled_prompt_and_off_removes_them() {
923 use crate::prompt_blocks::Choice;
924
925 let plugins = crate::plugins::Plugins::default();
926 let mut cfg = crate::config::Config::default();
927 cfg.provider.model = "gpt-oss:120b".into();
928 let env: crate::config::EnvFn = &|_: &str| None;
930
931 let on = assemble("you are eclipse", &for_config(&cfg, env, &plugins), &[]);
932 assert!(
933 on.contains("you are eclipse"),
934 "the configured sentence survives: {on}"
935 );
936 assert!(
937 on.contains("## task-completion") && on.contains("## execution-guidance"),
938 "the gated blocks are in the prompt: {on}"
939 );
940
941 cfg.agent.prompt_blocks = Choice::Off;
942 let off = assemble("you are eclipse", &for_config(&cfg, env, &plugins), &[]);
943 assert_eq!(
944 off.trim(),
945 "you are eclipse",
946 "off leaves the sentence and nothing else"
947 );
948 }
949
950 #[test]
951 fn the_three_files_are_found_with_their_budgets_and_the_missing_ones_are_predicted() {
952 let tmp = tempfile::tempdir().unwrap();
953 let home = tmp.path();
954 let workspace = home.join("work");
955 std::fs::create_dir_all(&workspace).unwrap();
956 let memory = home.join(".eclipse/memory");
957 write(&memory.join("USER.md"), "USER FACT: one line");
958 write(&memory.join("MEMORY.md"), "first fact\n§\nsecond fact");
959
960 let cfg = cfg_in(home, &workspace);
961 let env = home_env(home);
962 let rows = editable(&cfg, &env);
963 assert_eq!(rows.len(), 3, "{rows:#?}");
964 assert_eq!(
965 rows.iter().map(|r| r.which.id()).collect::<Vec<_>>(),
966 vec!["agent", "user", "memory"]
967 );
968
969 let agent = &rows[0];
970 assert!(!agent.exists);
973 assert_eq!(
974 agent.others, 0,
975 "the one file this row would create is the only one"
976 );
977 assert_eq!(agent.path, memory.join("AGENT.md"));
978 assert_eq!(agent.text, "");
979 assert_eq!(agent.position, None);
980 assert_eq!(agent.max_chars, DEFAULT_MAX_FILE_CHARS);
981 assert!(
982 agent.own_budget.is_none(),
983 "prose files have no budget of their own"
984 );
985
986 let user = &rows[1];
987 assert!(user.exists);
988 assert_eq!(user.chars, "USER FACT: one line".chars().count());
989 assert_eq!(user.kept, user.chars, "nothing is clipped");
990 assert!(!user.truncated());
991
992 let mem = &rows[2];
993 assert_eq!(mem.file, "MEMORY.md");
994 assert_eq!(mem.chars, "first fact\n§\nsecond fact".chars().count());
995 assert!(mem.text.contains('§'));
997 assert_eq!(mem.own_budget, Some(crate::memory::DEFAULT_BUDGET_CHARS));
998 assert_eq!(user.position, Some(1));
1000 assert_eq!(mem.position, Some(2));
1001 }
1002
1003 #[test]
1004 fn the_nearest_agent_file_is_the_one_to_edit_and_the_wider_ones_are_counted() {
1005 let tmp = tempfile::tempdir().unwrap();
1006 let home = tmp.path();
1007 let repo = home.join("repo");
1008 let leaf = repo.join("crates/app");
1009 std::fs::create_dir_all(repo.join(".git")).unwrap();
1010 std::fs::create_dir_all(&leaf).unwrap();
1011 write(&repo.join("AGENT.md"), "REPO RULE");
1012 write(&leaf.join("AGENT.md"), "LEAF RULE");
1013 write(&home.join(".eclipse/memory/AGENT.md"), "GLOBAL RULE");
1014
1015 let cfg = cfg_in(home, &leaf);
1016 let env = home_env(home);
1017 let agent = editable(&cfg, &env)
1018 .into_iter()
1019 .find(|r| r.which == Which::Agent)
1020 .unwrap();
1021 assert_eq!(
1023 agent.path,
1024 std::fs::canonicalize(leaf.join("AGENT.md")).unwrap()
1025 );
1026 assert_eq!(agent.text, "LEAF RULE");
1027 assert_eq!(agent.others, 2);
1029 assert_eq!(agent.position, Some(3), "global, repo, leaf");
1030 }
1031
1032 #[test]
1033 fn a_file_past_the_per_file_ceiling_is_reported_as_clipped() {
1034 let tmp = tempfile::tempdir().unwrap();
1035 let home = tmp.path();
1036 let workspace = home.join("work");
1037 std::fs::create_dir_all(&workspace).unwrap();
1038 let memory = home.join(".eclipse/memory");
1039 write(&memory.join("USER.md"), &"x".repeat(200));
1040
1041 let mut cfg = cfg_in(home, &workspace);
1042 cfg.agent.context_file_max_chars = 100;
1043 let env = home_env(home);
1044 let user = editable(&cfg, &env)
1045 .into_iter()
1046 .find(|r| r.which == Which::User)
1047 .unwrap();
1048 assert_eq!(user.chars, 200);
1049 assert!(
1050 user.kept < user.chars,
1051 "the prompt keeps less than the file"
1052 );
1053 assert!(user.truncated());
1054 assert_eq!(user.max_chars, 100);
1056 }
1057
1058 #[test]
1059 fn a_save_creates_the_file_it_promised_and_leaves_no_temp_behind() {
1060 let tmp = tempfile::tempdir().unwrap();
1061 let home = tmp.path();
1062 let workspace = home.join("work");
1063 std::fs::create_dir_all(&workspace).unwrap();
1064 let cfg = cfg_in(home, &workspace);
1065 let env = home_env(home);
1066
1067 let row = write_file(&cfg, &env, Which::Agent, "RULE: one\n").unwrap();
1068 assert!(
1069 row.exists,
1070 "the row it answers with is the file it just created"
1071 );
1072 assert_eq!(row.path, home.join(".eclipse/memory/AGENT.md"));
1073 assert_eq!(std::fs::read_to_string(&row.path).unwrap(), "RULE: one\n");
1074 let leftovers: Vec<_> = std::fs::read_dir(home.join(".eclipse/memory"))
1076 .unwrap()
1077 .filter_map(|e| e.ok())
1078 .map(|e| e.file_name().to_string_lossy().into_owned())
1079 .filter(|n| n.contains("tmp"))
1080 .collect();
1081 assert!(leftovers.is_empty(), "{leftovers:?}");
1082
1083 let row = write_file(&cfg, &env, Which::Agent, "RULE: two\n").unwrap();
1085 assert_eq!(row.chars, "RULE: two\n".chars().count());
1086 assert_eq!(std::fs::read_to_string(&row.path).unwrap(), "RULE: two\n");
1087
1088 #[cfg(unix)]
1089 {
1090 use std::os::unix::fs::PermissionsExt;
1091 let mode = std::fs::metadata(&row.path).unwrap().permissions().mode() & 0o777;
1092 assert_eq!(mode, 0o600, "a file the page created is not world-readable");
1093 }
1094 }
1095
1096 #[test]
1097 fn a_memory_save_goes_through_the_memory_writer_and_is_refused_past_its_budget() {
1098 let tmp = tempfile::tempdir().unwrap();
1099 let home = tmp.path();
1100 let workspace = home.join("work");
1101 std::fs::create_dir_all(&workspace).unwrap();
1102 let cfg = cfg_in(home, &workspace);
1103 let env = home_env(home);
1104
1105 let row = write_file(&cfg, &env, Which::Memory, "fact one\n§\nfact two\n").unwrap();
1107 let entries = crate::memory::parse(&std::fs::read_to_string(&row.path).unwrap());
1108 assert_eq!(entries, vec!["fact one", "fact two"], "{entries:?}");
1109 let memory = crate::memory::Memory::new(&row.path, cfg.user.memory_budget_chars);
1111 assert_eq!(memory.read().unwrap().len(), 2);
1112
1113 let mut small = cfg_in(home, &workspace);
1114 small.user.memory_budget_chars = 20;
1115 let err = write_file(&small, &env, Which::Memory, &"y".repeat(200)).unwrap_err();
1116 let said = err.to_string();
1117 assert!(said.contains("budget"), "{said}");
1118 assert!(said.contains("remove or shorten"), "{said}");
1119 assert_eq!(memory.read().unwrap().len(), 2);
1121 }
1122
1123 #[test]
1127 fn the_plural_agents_md_is_read_when_the_singular_is_absent() {
1128 let tmp = tempfile::tempdir().unwrap();
1129 let (config, profile, workspace) = three(&tmp);
1130 write(&workspace.join("AGENTS.md"), "plural rules\n");
1131
1132 let ctx = gather(&sources(&config, &profile, &workspace), Budget::default());
1133 let instructions = ctx
1134 .instructions
1135 .iter()
1136 .map(|l| (l.name.as_str(), l.body.as_str()))
1137 .collect::<Vec<_>>();
1138 assert!(
1139 instructions
1140 .iter()
1141 .any(|(name, body)| *name == "AGENTS.md" && body.contains("plural rules")),
1142 "the alias is read and reported under its own name: {instructions:?}"
1143 );
1144 }
1145
1146 #[test]
1149 fn the_singular_wins_over_the_alias_in_the_same_directory() {
1150 let tmp = tempfile::tempdir().unwrap();
1151 let (config, profile, workspace) = three(&tmp);
1152 write(&workspace.join("AGENT.md"), "singular rules\n");
1153 write(&workspace.join("AGENTS.md"), "plural rules\n");
1154
1155 let ctx = gather(&sources(&config, &profile, &workspace), Budget::default());
1156 let names = ctx
1157 .instructions
1158 .iter()
1159 .map(|l| l.name.clone())
1160 .collect::<Vec<_>>();
1161 let bodies = ctx
1162 .instructions
1163 .iter()
1164 .map(|l| l.body.clone())
1165 .collect::<Vec<_>>();
1166 assert_eq!(
1167 names.iter().filter(|n| n.ends_with(".md")).count(),
1168 names.len()
1169 );
1170 assert!(
1171 !bodies.iter().any(|b| b.contains("plural rules")),
1172 "one file per directory, and it is the singular: {bodies:?}"
1173 );
1174 }
1175
1176 #[test]
1179 fn the_dotted_singular_wins_over_a_plain_alias() {
1180 let tmp = tempfile::tempdir().unwrap();
1181 let (config, profile, workspace) = three(&tmp);
1182 write(
1183 &workspace.join(".eclipse").join("AGENT.md"),
1184 "dotted rules\n",
1185 );
1186 write(&workspace.join("AGENTS.md"), "plural rules\n");
1187
1188 let ctx = gather(&sources(&config, &profile, &workspace), Budget::default());
1189 let bodies = ctx
1190 .instructions
1191 .iter()
1192 .map(|l| l.body.clone())
1193 .collect::<Vec<_>>();
1194 assert!(
1195 bodies.iter().any(|b| b.contains("dotted rules")),
1196 "{bodies:?}"
1197 );
1198 assert!(
1199 !bodies.iter().any(|b| b.contains("plural rules")),
1200 "{bodies:?}"
1201 );
1202 }
1203
1204 #[test]
1206 fn the_config_directory_accepts_the_alias() {
1207 let tmp = tempfile::tempdir().unwrap();
1208 let (config, profile, workspace) = three(&tmp);
1209 write(&config.join("AGENTS.md"), "install-wide rules\n");
1210
1211 let ctx = gather(&sources(&config, &profile, &workspace), Budget::default());
1212 let bodies = ctx
1213 .instructions
1214 .iter()
1215 .map(|l| l.body.clone())
1216 .collect::<Vec<_>>();
1217 assert!(
1218 bodies.iter().any(|b| b.contains("install-wide rules")),
1219 "{bodies:?}"
1220 );
1221 }
1222
1223 #[test]
1224 fn a_blank_or_empty_file_contributes_no_section() {
1225 let tmp = tempfile::tempdir().unwrap();
1226 let profile = tmp.path().join("profile");
1227 std::fs::create_dir_all(&profile).unwrap();
1228 std::fs::write(profile.join("MEMORY.md"), "").unwrap();
1230 std::fs::write(profile.join("USER.md"), "\n \n\t\n").unwrap();
1232 let workspace = profile.clone();
1233 let sources = Sources {
1234 config_dir: Some(&profile),
1235 profile_dir: Some(&profile),
1236 workspace: &workspace,
1237 home: None,
1238 user_file: "USER.md",
1239 memory_file: "MEMORY.md",
1240 };
1241 let ctx = gather(
1242 &sources,
1243 Budget {
1244 max_file_chars: 6000,
1245 total_chars: 12000,
1246 },
1247 );
1248 assert!(
1249 ctx.user.is_none(),
1250 "a whitespace-only USER.md is not a layer"
1251 );
1252 assert!(ctx.memory.is_none(), "an empty MEMORY.md is not a layer");
1253 assert!(ctx.is_empty(), "nothing to inject: {ctx:?}");
1254 }
1255
1256 #[test]
1257 fn a_project_file_is_found_from_a_subdirectory_up_to_the_repository_root() {
1258 let tmp = tempfile::tempdir().unwrap();
1259 let root = tmp.path();
1260 write(&root.join(".git/HEAD"), "ref: refs/heads/main");
1261 write(&root.join("AGENT.md"), "repo rules");
1262 write(&root.join("sub/deeper/AGENT.md"), "leaf rules");
1263 let workspace = root.join("sub/deeper");
1264
1265 let found = project_files(&workspace, None);
1266 let names: Vec<_> = found
1267 .iter()
1268 .map(|p| p.strip_prefix(root).unwrap().to_string_lossy().to_string())
1269 .collect();
1270 assert_eq!(
1271 names,
1272 ["AGENT.md", "sub/deeper/AGENT.md"],
1273 "outermost first, so the nearest file has the last word"
1274 );
1275 }
1276
1277 #[test]
1278 fn walking_up_stops_at_the_home_boundary_instead_of_reaching_root() {
1279 let tmp = tempfile::tempdir().unwrap();
1280 let home = tmp.path().join("home");
1281 let deep = home.join("work/proj");
1282 std::fs::create_dir_all(&deep).unwrap();
1283 write(&home.join("AGENT.md"), "home rules");
1284 write(&deep.join("AGENT.md"), "project rules");
1285
1286 let found = project_files(&deep, Some(&home));
1287 assert_eq!(found.len(), 2, "{found:?}");
1288 write(&tmp.path().join("AGENT.md"), "above home");
1290 let found = project_files(&deep, Some(&home));
1291 assert_eq!(found.len(), 2, "{found:?}");
1292 assert!(found.iter().all(|p| p.starts_with(&home)));
1293 let elsewhere = tmp.path().join("elsewhere/a/b/proj");
1297 std::fs::create_dir_all(&elsewhere).unwrap();
1298 write(
1299 &tmp.path().join("elsewhere/AGENT.md"),
1300 "an unrelated project",
1301 );
1302 write(
1303 &tmp.path().join("elsewhere/a/AGENT.md"),
1304 "another unrelated project",
1305 );
1306 write(&elsewhere.join("AGENT.md"), "project rules");
1307 assert_eq!(
1308 project_files(&elsewhere, Some(&home)),
1309 [elsewhere.join("AGENT.md")],
1310 "the workspace's own file, and nothing from the trees above it"
1311 );
1312 }
1313
1314 #[test]
1315 fn a_dot_eclipse_file_is_used_when_there_is_no_agent_md() {
1316 let tmp = tempfile::tempdir().unwrap();
1317 let root = tmp.path();
1318 write(&root.join(".git/HEAD"), "ref: refs/heads/main");
1319 write(&root.join(".eclipse/AGENT.md"), "hidden rules");
1320 let found = project_files(root, None);
1321 assert_eq!(found, [root.join(".eclipse/AGENT.md")]);
1322 }
1323
1324 #[test]
1325 fn a_plain_agent_md_wins_over_the_hidden_one() {
1326 let tmp = tempfile::tempdir().unwrap();
1327 let root = tmp.path();
1328 write(&root.join(".git/HEAD"), "ref: refs/heads/main");
1329 write(&root.join(".eclipse/AGENT.md"), "hidden rules");
1330 write(&root.join("AGENT.md"), "visible rules");
1331 assert_eq!(project_files(root, None), [root.join("AGENT.md")]);
1332 }
1333
1334 #[test]
1335 fn every_file_kind_lands_in_its_layer_and_in_injection_order() {
1336 let tmp = tempfile::tempdir().unwrap();
1337 let config = tmp.path().join("config");
1338 let profile = config.join("profiles/work");
1339 let repo = tmp.path().join("repo");
1340 write(&repo.join(".git/HEAD"), "ref: refs/heads/main");
1341 write(&config.join("AGENT.md"), "global rules");
1342 write(&repo.join("AGENT.md"), "repo rules");
1343 write(&profile.join("USER.md"), "I am Max, be direct");
1344 write(&profile.join("MEMORY.md"), "the fleet is two servers");
1345 let workspace = repo.join("crates");
1346
1347 let ctx = gather(&sources(&config, &profile, &workspace), Budget::default());
1348 assert_eq!(ctx.instructions.len(), 2);
1349 assert!(
1350 ctx.instructions[0].path.starts_with(&config),
1351 "global first"
1352 );
1353 assert!(ctx.instructions[1].path.starts_with(&repo), "then project");
1354 assert_eq!(ctx.user.as_ref().unwrap().body, "I am Max, be direct");
1355 assert_eq!(
1358 ctx.memory.as_ref().unwrap().body,
1359 "- the fleet is two servers"
1360 );
1361
1362 let prompt = assemble("You are Eclipse.", &ctx, &["plugin says hi".into()]);
1363 let order: Vec<&str> = [
1364 "You are Eclipse.",
1365 "global rules",
1366 "repo rules",
1367 "plugin says hi",
1368 "I am Max, be direct",
1369 "the fleet is two servers",
1370 ]
1371 .to_vec();
1372 let mut at = 0;
1373 for needle in order {
1374 let found = prompt[at..]
1375 .find(needle)
1376 .unwrap_or_else(|| panic!("{needle:?} missing or out of order in:\n{prompt}"));
1377 at += found;
1378 }
1379 assert!(prompt.contains("## AGENT.md ("), "{prompt}");
1381 assert!(prompt.contains("## USER.md ("), "{prompt}");
1382 assert!(prompt.contains("## MEMORY.md ("), "{prompt}");
1383 }
1384
1385 #[test]
1386 fn a_long_file_keeps_its_head_and_its_tail_and_says_what_went() {
1387 let tmp = tempfile::tempdir().unwrap();
1388 let config = tmp.path().join("config");
1389 let profile = config.join("profiles/default");
1390 let workspace = tmp.path().join("ws");
1391 std::fs::create_dir_all(&workspace).unwrap();
1392 let body = format!("HEAD{}{}TAIL", "x".repeat(500), "y".repeat(500));
1393 write(&profile.join("USER.md"), &body);
1394
1395 let budget = Budget {
1396 max_file_chars: 200,
1397 total_chars: 10_000,
1398 };
1399 let ctx = gather(&sources(&config, &profile, &workspace), budget);
1400 let user = ctx.user.unwrap();
1401 assert!(user.truncated());
1402 assert_eq!(user.original_chars, body.chars().count());
1403 assert!(user.body.starts_with("HEAD"), "{}", user.body);
1404 assert!(user.body.ends_with("TAIL"), "{}", user.body);
1405 assert!(
1406 user.body.contains("[… truncated:") && user.body.contains("chars …]"),
1407 "the cut is visible: {}",
1408 user.body
1409 );
1410 assert!(
1411 user.chars <= 200,
1412 "the cap includes the marker: {} chars",
1413 user.chars
1414 );
1415 }
1416
1417 #[test]
1418 fn the_cap_is_a_hard_cap_marker_included() {
1419 for max in [60usize, 120, 200, 1000] {
1420 let text = "x".repeat(5000);
1421 let out = clip(&text, max);
1422 assert!(
1423 out.chars().count() <= max,
1424 "clip({max}) produced {} chars",
1425 out.chars().count()
1426 );
1427 assert!(out.contains("[… truncated:"), "{out}");
1428 }
1429 assert_eq!(clip("short", 100), "short");
1431 }
1432
1433 #[test]
1434 fn truncation_never_splits_a_character() {
1435 let text = "é".repeat(100);
1436 let clipped = clip(&text, 80);
1437 assert!(clipped.starts_with("éé"), "{clipped}");
1438 assert!(clipped.ends_with('é'), "{clipped}");
1439 assert!(clipped.chars().count() <= 80);
1440 assert!(clipped.is_char_boundary(clipped.len()));
1441
1442 let cramped = clip(&text, 21);
1447 assert!(cramped.chars().count() <= 21, "{cramped}");
1448 assert!(cramped.contains("100"), "{cramped}");
1449 assert!(!cramped.is_empty() && cramped.is_char_boundary(cramped.len()));
1450 }
1451
1452 #[test]
1453 fn over_the_total_the_broadest_file_goes_first_and_the_drop_is_named() {
1454 let tmp = tempfile::tempdir().unwrap();
1455 let config = tmp.path().join("config");
1456 let profile = config.join("profiles/default");
1457 let repo = tmp.path().join("repo");
1458 write(&repo.join(".git/HEAD"), "ref: refs/heads/main");
1459 write(&config.join("AGENT.md"), &"g".repeat(400));
1460 write(&repo.join("AGENT.md"), &"r".repeat(400));
1461 write(&profile.join("USER.md"), "user");
1462 write(&profile.join("MEMORY.md"), "memory");
1463
1464 let budget = Budget {
1465 max_file_chars: 6000,
1466 total_chars: 900,
1467 };
1468 let ctx = gather(&sources(&config, &profile, &repo), budget);
1469 assert_eq!(ctx.instructions.len(), 2);
1471 assert!(ctx.notes.is_empty(), "{:?}", ctx.notes);
1472
1473 let budget = Budget {
1474 max_file_chars: 6000,
1475 total_chars: 500,
1476 };
1477 let ctx = gather(&sources(&config, &profile, &repo), budget);
1478 assert_eq!(ctx.instructions.len(), 1, "the global file went first");
1479 assert!(ctx.instructions[0].path.starts_with(&repo));
1480 assert!(ctx.user.is_some() && ctx.memory.is_some());
1481 assert!(
1482 ctx.notes
1483 .iter()
1484 .any(|n| n.contains("dropped") && n.contains("chars")),
1485 "{:?}",
1486 ctx.notes
1487 );
1488 }
1489
1490 #[test]
1491 fn a_missing_config_directory_is_not_an_error() {
1492 let workspace = tempfile::tempdir().unwrap();
1493 let ctx = gather(
1494 &Sources {
1495 config_dir: Some(Path::new("/nonexistent/eclipse")),
1496 profile_dir: Some(Path::new("/nonexistent/eclipse/profiles/default")),
1497 workspace: workspace.path(),
1498 home: None,
1499 user_file: "USER.md",
1500 memory_file: "MEMORY.md",
1501 },
1502 Budget::default(),
1503 );
1504 assert!(ctx.is_empty());
1505 assert_eq!(assemble("base", &ctx, &[]), "base");
1506 }
1507
1508 #[test]
1509 fn the_fragments_sit_between_the_instruction_files_and_the_user_model() {
1510 let ctx = Context {
1511 instructions: vec![Layer {
1512 name: "AGENT.md".into(),
1513 path: PathBuf::from("/r/AGENT.md"),
1514 body: "rules".into(),
1515 chars: 5,
1516 original_chars: 5,
1517 }],
1518 user: Some(Layer {
1519 name: "USER.md".into(),
1520 path: PathBuf::from("/p/USER.md"),
1521 body: "who".into(),
1522 chars: 3,
1523 original_chars: 3,
1524 }),
1525 memory: None,
1526 skills: None,
1527 notes: Vec::new(),
1528 skill_notes: Vec::new(),
1529 guidance: String::new(),
1530 };
1531 let prompt = assemble("base", &ctx, &["frag".into(), " ".into()]);
1532 let prompt = prompt.replace("\n", " ");
1533 let compact = prompt.split_whitespace().collect::<Vec<_>>().join(" ");
1534 assert!(
1535 compact.ends_with("rules frag ## USER.md (/p/USER.md) who"),
1536 "{compact}"
1537 );
1538 assert_eq!(ctx.total_chars(), 8);
1539 }
1540
1541 fn skill(dir: &Path, name: &str, description: &str) {
1542 write(
1543 &dir.join(name).join("SKILL.md"),
1544 &format!("---\nname: {name}\ndescription: {description}\n---\nDo {name}.\n"),
1545 );
1546 }
1547
1548 fn env_for(home: &Path) -> impl Fn(&str) -> Option<String> {
1549 let home = home.display().to_string();
1550 move |key: &str| (key == "HOME").then(|| home.clone())
1551 }
1552
1553 #[test]
1554 fn the_skills_index_is_the_last_labelled_layer_after_memory() {
1555 let tmp = tempfile::tempdir().unwrap();
1556 let (config, profile, workspace) = (
1557 tmp.path().join("c"),
1558 tmp.path().join("p"),
1559 tmp.path().join("w"),
1560 );
1561 write(&config.join("AGENT.md"), "RULES");
1562 write(&profile.join("USER.md"), "WHO");
1563 write(&profile.join("MEMORY.md"), "a fact");
1564 skill(&config.join("skills"), "backup", "back things up");
1565 let report = crate::skills::discover(&[crate::skills::Root {
1566 source: crate::skills::Source::Shared,
1567 dir: config.join("skills"),
1568 }]);
1569 let ctx = gather(&sources(&config, &profile, &workspace), Budget::default())
1570 .with_skills(&report, 4000);
1571
1572 let prompt = assemble("base", &ctx, &[]);
1573 let at = |needle: &str| {
1574 prompt
1575 .find(needle)
1576 .unwrap_or_else(|| panic!("{needle}: {prompt}"))
1577 };
1578 assert!(at("a fact") < at("## Skills"), "after MEMORY.md: {prompt}");
1579 assert!(prompt.contains("- backup: back things up"), "{prompt}");
1580 assert!(
1581 !prompt.contains("Do backup."),
1582 "the body is loaded on demand: {prompt}"
1583 );
1584 assert!(prompt.trim_end().ends_with("back things up"), "{prompt}");
1585 assert!(!ctx.is_empty());
1586 assert_eq!(
1587 ctx.total_chars(),
1588 "RULES".len() + "WHO".len() + "- a fact".len()
1589 );
1590 }
1591
1592 #[test]
1593 fn the_config_reaches_the_shared_profile_and_workspace_skills_and_the_budget() {
1594 let tmp = tempfile::tempdir().unwrap();
1595 let home = tmp.path();
1596 let config = home.join(".eclipse");
1597 let workspace = home.join("ws");
1598 skill(&config.join("skills"), "backup", "the shared one");
1599 skill(&config.join("skills"), "other", "shared only");
1600 skill(
1601 &config.join("profiles/work/skills"),
1602 "backup",
1603 "the profile one",
1604 );
1605 skill(&workspace.join(".eclipse/skills"), "deploy", "this project");
1606
1607 let mut cfg = crate::config::Config {
1608 profile: Some("work".into()),
1609 ..Default::default()
1610 };
1611 cfg.tools.workspace_root = Some(workspace.clone());
1612 let env = env_for(home);
1613 let plugins = crate::plugins::Plugins::default();
1614
1615 let ctx = for_config(&cfg, &env, &plugins);
1616 let index = ctx.skills.as_ref().unwrap();
1617 assert!(index.body.contains("the profile one"), "{}", index.body);
1618 assert!(
1619 !index.body.contains("the shared one"),
1620 "the profile shadows it"
1621 );
1622 assert!(index.body.contains("- deploy: this project"));
1623 assert!(index.body.contains("- other: shared only"));
1624 assert!(ctx.skill_notes.is_empty(), "{:?}", ctx.skill_notes);
1625
1626 cfg.skills.index_budget_chars = index.chars - 10;
1627 let ctx = for_config(&cfg, &env, &plugins);
1628 assert_eq!(ctx.skills.as_ref().unwrap().names.len(), 2);
1629 assert!(
1630 ctx.skill_notes
1631 .iter()
1632 .any(|n| n.contains("left out 1 of 3")),
1633 "{:?}",
1634 ctx.skill_notes
1635 );
1636 }
1637
1638 fn under_home<'a>(
1642 config: &'a Path,
1643 profile: &'a Path,
1644 workspace: &'a Path,
1645 home: &'a Path,
1646 ) -> Sources<'a> {
1647 Sources {
1648 config_dir: Some(config),
1649 profile_dir: Some(profile),
1650 workspace,
1651 home: Some(home),
1652 user_file: "USER.md",
1653 memory_file: "MEMORY.md",
1654 }
1655 }
1656
1657 #[test]
1660 fn a_project_file_that_points_outside_the_tree_is_not_read() {
1661 let tmp = tempfile::tempdir().unwrap();
1662 let home = tmp.path().join("home");
1663 let workspace = home.join("work");
1664 std::fs::create_dir_all(&workspace).unwrap();
1665 let config = tmp.path().join("config");
1666 let profile = tmp.path().join("profile");
1667 let secret = tmp.path().join("id_rsa");
1669 write(&secret, "-----BEGIN OPENSSH PRIVATE KEY-----\n");
1670 std::os::unix::fs::symlink(&secret, workspace.join("AGENTS.md")).unwrap();
1671
1672 let ctx = gather(
1673 &under_home(&config, &profile, &workspace, &home),
1674 Budget::default(),
1675 );
1676 assert!(
1677 ctx.instructions.is_empty(),
1678 "nothing from the link: {:?}",
1679 ctx.instructions
1680 );
1681 assert!(
1682 ctx.notes
1683 .iter()
1684 .any(|n| n.contains("points outside the project")),
1685 "{:?}",
1686 ctx.notes
1687 );
1688 }
1689
1690 #[test]
1693 fn a_project_file_that_points_inside_the_tree_is_still_read() {
1694 let tmp = tempfile::tempdir().unwrap();
1695 let (config, profile, workspace) = three(&tmp);
1696 write(
1697 &workspace.join("docs/conventions.md"),
1698 "run make, never cargo test\n",
1699 );
1700 std::os::unix::fs::symlink(
1701 workspace.join("docs/conventions.md"),
1702 workspace.join("AGENTS.md"),
1703 )
1704 .unwrap();
1705
1706 let ctx = gather(
1707 &under_home(&config, &profile, &workspace, tmp.path()),
1708 Budget::default(),
1709 );
1710 assert_eq!(ctx.instructions.len(), 1, "{:?}", ctx.notes);
1711 assert!(ctx.instructions[0].body.contains("run make"));
1712 assert_eq!(
1713 ctx.instructions[0].path,
1714 std::fs::canonicalize(workspace.join("docs/conventions.md")).unwrap(),
1715 "the label names the file that was read"
1716 );
1717 }
1718
1719 #[test]
1722 fn the_operators_own_agent_file_may_still_be_a_symlink() {
1723 let tmp = tempfile::tempdir().unwrap();
1724 let (config, profile, workspace) = three(&tmp);
1725 let shared = tmp.path().join("dotfiles/AGENT.md");
1726 write(&shared, "my rules, kept outside any project\n");
1727 std::fs::create_dir_all(&config).unwrap();
1728 std::os::unix::fs::symlink(&shared, config.join("AGENT.md")).unwrap();
1729
1730 let ctx = gather(
1731 &under_home(&config, &profile, &workspace, tmp.path()),
1732 Budget::default(),
1733 );
1734 assert_eq!(ctx.instructions.len(), 1, "{:?}", ctx.notes);
1735 assert!(ctx.instructions[0].body.contains("my rules"));
1736 }
1737
1738 #[test]
1741 fn a_context_file_that_is_not_a_regular_file_is_refused() {
1742 let tmp = tempfile::tempdir().unwrap();
1743 let (config, profile, workspace) = three(&tmp);
1744 std::fs::create_dir_all(&profile).unwrap();
1745 let fifo = profile.join("USER.md");
1746 let made = std::process::Command::new("mkfifo").arg(&fifo).status();
1747 assert!(
1748 matches!(made, Ok(s) if s.success()),
1749 "mkfifo is how this test makes the case: {made:?}"
1750 );
1751
1752 let ctx = gather(
1753 &under_home(&config, &profile, &workspace, tmp.path()),
1754 Budget::default(),
1755 );
1756 assert!(ctx.user.is_none(), "no section, and no hang");
1757 assert!(
1758 ctx.notes
1759 .iter()
1760 .any(|n| n.contains("is not a regular file")),
1761 "{:?}",
1762 ctx.notes
1763 );
1764 }
1765
1766 #[test]
1769 fn an_enormous_context_file_is_read_only_to_the_cap() {
1770 let tmp = tempfile::tempdir().unwrap();
1771 let (config, profile, workspace) = three(&tmp);
1772 std::fs::create_dir_all(&profile).unwrap();
1773 let body = "a".repeat(2 * 1024 * 1024);
1775 std::fs::write(profile.join("USER.md"), &body).unwrap();
1776
1777 let mut ctx = gather(
1778 &under_home(&config, &profile, &workspace, tmp.path()),
1779 Budget::default(),
1780 );
1781 let layer = ctx.user.take().expect("the head of it is still read");
1782 assert!(layer.truncated(), "the injected body is clipped");
1783 assert_eq!(
1784 layer.original_chars,
1785 (MAX_LAYER_BYTES) as usize,
1786 "read exactly to the cap, not to the end of the file"
1787 );
1788 assert!(
1789 ctx.notes
1790 .iter()
1791 .any(|n| n.contains("read only to that point")),
1792 "{:?}",
1793 ctx.notes
1794 );
1795 }
1796}