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, boundary) = project_walk(&workspace, cfg.home(env).as_deref());
673 let project: Vec<PathBuf> = project
674 .into_iter()
675 .filter(|path| canonical_or(path).starts_with(&boundary))
676 .collect();
677
678 let mut rows = Vec::new();
679
680 let agent = project
684 .last()
685 .cloned()
686 .or_else(|| Some(dir.as_ref()?.join("AGENT.md")));
687 if let Some(path) = agent {
688 let layer = layers.iter().find(|l| l.path == canonical_or(&path));
689 let agents = layers
693 .iter()
694 .filter(|l| l.name.starts_with("AGENT"))
695 .count();
696 let others = agents.saturating_sub(usize::from(layer.is_some()));
697 rows.push(row_from(
698 Which::Agent,
699 path,
700 layer.copied(),
701 max_chars,
702 None,
703 total,
704 total_budget,
705 position_of,
706 others,
707 ));
708 }
709 if let Some(dir) = dir.as_deref() {
710 for (which, file, own_budget) in [
711 (Which::User, cfg.user.file.clone(), None),
712 (
713 Which::Memory,
714 cfg.user.memory_file.clone(),
715 Some(cfg.user.memory_budget_chars),
716 ),
717 ] {
718 let path = dir.join(&file);
719 let layer = layers.iter().find(|l| l.path == canonical_or(&path));
720 rows.push(row_from(
721 which,
722 path,
723 layer.copied(),
724 max_chars,
725 own_budget,
726 total,
727 total_budget,
728 position_of,
729 0,
730 ));
731 }
732 }
733 rows
734}
735
736#[allow(clippy::too_many_arguments)]
737fn row_from(
738 which: Which,
739 path: PathBuf,
740 layer: Option<&Layer>,
741 max_chars: usize,
742 own_budget: Option<usize>,
743 total: usize,
744 total_budget: usize,
745 position_of: impl Fn(&Path) -> Option<usize>,
746 others: usize,
747) -> Editable {
748 let canonical = canonical_or(&path);
749 let text = std::fs::read_to_string(&canonical).unwrap_or_default();
750 let chars = text.chars().count();
751 let kept = layer.map_or(chars, |l| l.chars);
752 Editable {
753 which,
754 position: position_of(&canonical),
755 file: path
756 .file_name()
757 .map(|n| n.to_string_lossy().into_owned())
758 .unwrap_or_else(|| format!("{}.md", which.id())),
759 exists: canonical.is_file(),
760 chars,
761 kept,
762 max_chars,
763 own_budget,
764 total,
765 total_budget,
766 others,
767 path: canonical,
768 text,
769 }
770}
771
772fn canonical_or(path: &Path) -> PathBuf {
773 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
774}
775
776pub fn write_file(
787 cfg: &crate::config::Config,
788 env: crate::config::EnvFn,
789 which: Which,
790 text: &str,
791) -> crate::error::Result<Editable> {
792 let Some(row) = editable(cfg, env).into_iter().find(|r| r.which == which) else {
793 return Err(crate::error::Error::Config(format!(
794 "this configuration has no {} file to write",
795 which.id()
796 )));
797 };
798 match which {
799 Which::Memory => {
800 let memory = crate::memory::Memory::new(&row.path, cfg.user.memory_budget_chars);
801 if let crate::memory::Outcome::Full {
802 chars,
803 budget,
804 entries,
805 } = memory.replace(crate::memory::parse(text))?
806 {
807 return Err(crate::error::Error::Config(format!(
808 "{} would be {chars} chars and its budget is {budget}; it holds {} entr{} now — \
809 remove or shorten one here instead",
810 row.file,
811 entries.len(),
812 if entries.len() == 1 { "y" } else { "ies" }
813 )));
814 }
815 }
816 Which::Agent | Which::User => {
817 crate::atomic::write_file_atomically(&row.path, text)
818 .map_err(|e| crate::error::Error::io(&row.path, e))?;
819 }
820 }
821 let after = editable(cfg, env);
822 after.into_iter().find(|r| r.which == which).ok_or_else(|| {
823 crate::error::Error::Config("the file vanished while it was being written".into())
824 })
825}
826
827pub fn assemble(base: &str, ctx: &Context, fragments: &[String]) -> String {
833 let mut parts: Vec<String> = Vec::new();
834 let base = base.trim();
835 if !base.is_empty() {
836 parts.push(base.to_string());
837 }
838 let guidance = ctx.guidance.trim();
842 if !guidance.is_empty() {
843 parts.push(guidance.to_string());
844 }
845 for layer in &ctx.instructions {
846 parts.push(labelled(layer));
847 }
848 for fragment in fragments {
849 let fragment = fragment.trim();
850 if !fragment.is_empty() {
851 parts.push(fragment.to_string());
852 }
853 }
854 if let Some(user) = &ctx.user {
855 parts.push(labelled(user));
856 }
857 if let Some(memory) = &ctx.memory {
858 parts.push(labelled(memory));
859 }
860 if let Some(skills) = &ctx.skills {
861 parts.push(format!("## Skills\n\n{}", skills.body));
864 }
865 parts.join("\n\n")
866}
867
868fn labelled(layer: &Layer) -> String {
869 format!(
870 "## {} ({})\n\n{}",
871 layer.name,
872 layer.path.display(),
873 layer.body.trim_end()
874 )
875}
876
877#[cfg(test)]
878mod tests {
879 use super::*;
880
881 fn write(path: &Path, body: &str) {
882 if let Some(parent) = path.parent() {
883 std::fs::create_dir_all(parent).unwrap();
884 }
885 std::fs::write(path, body).unwrap();
886 }
887
888 fn three(
890 tmp: &tempfile::TempDir,
891 ) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) {
892 let config = tmp.path().join("config");
893 let profile = tmp.path().join("profile");
894 let workspace = tmp.path().join("work");
895 std::fs::create_dir_all(&workspace).unwrap();
896 (config, profile, workspace)
897 }
898
899 fn sources<'a>(config: &'a Path, profile: &'a Path, workspace: &'a Path) -> Sources<'a> {
900 Sources {
901 config_dir: Some(config),
902 profile_dir: Some(profile),
903 workspace,
904 home: None,
905 user_file: "USER.md",
906 memory_file: "MEMORY.md",
907 }
908 }
909
910 fn cfg_in(home: &Path, workspace: &Path) -> crate::config::Config {
913 let mut cfg = crate::config::Config::default();
914 cfg.tools.workspace_root = Some(workspace.to_path_buf());
915 cfg.profile = None;
916 let _ = home;
917 cfg
918 }
919
920 fn home_env(home: &Path) -> impl Fn(&str) -> Option<String> + '_ {
923 move |key: &str| match key {
924 "HOME" => Some(home.display().to_string()),
925 _ => None,
926 }
927 }
928
929 #[test]
932 fn the_standing_blocks_reach_the_assembled_prompt_and_off_removes_them() {
933 use crate::prompt_blocks::Choice;
934
935 let plugins = crate::plugins::Plugins::default();
936 let mut cfg = crate::config::Config::default();
937 cfg.provider.model = "gpt-oss:120b".into();
938 let env: crate::config::EnvFn = &|_: &str| None;
940
941 let on = assemble("you are eclipse", &for_config(&cfg, env, &plugins), &[]);
942 assert!(
943 on.contains("you are eclipse"),
944 "the configured sentence survives: {on}"
945 );
946 assert!(
947 on.contains("## task-completion") && on.contains("## execution-guidance"),
948 "the gated blocks are in the prompt: {on}"
949 );
950
951 cfg.agent.prompt_blocks = Choice::Off;
952 let off = assemble("you are eclipse", &for_config(&cfg, env, &plugins), &[]);
953 assert_eq!(
954 off.trim(),
955 "you are eclipse",
956 "off leaves the sentence and nothing else"
957 );
958 }
959
960 #[test]
961 fn the_three_files_are_found_with_their_budgets_and_the_missing_ones_are_predicted() {
962 let tmp = tempfile::tempdir().unwrap();
963 let home = tmp.path();
964 let workspace = home.join("work");
965 std::fs::create_dir_all(&workspace).unwrap();
966 let memory = home.join(".eclipse/memory");
967 write(&memory.join("USER.md"), "USER FACT: one line");
968 write(&memory.join("MEMORY.md"), "first fact\n§\nsecond fact");
969
970 let cfg = cfg_in(home, &workspace);
971 let env = home_env(home);
972 let rows = editable(&cfg, &env);
973 assert_eq!(rows.len(), 3, "{rows:#?}");
974 assert_eq!(
975 rows.iter().map(|r| r.which.id()).collect::<Vec<_>>(),
976 vec!["agent", "user", "memory"]
977 );
978
979 let agent = &rows[0];
980 assert!(!agent.exists);
983 assert_eq!(
984 agent.others, 0,
985 "the one file this row would create is the only one"
986 );
987 assert_eq!(agent.path, memory.join("AGENT.md"));
988 assert_eq!(agent.text, "");
989 assert_eq!(agent.position, None);
990 assert_eq!(agent.max_chars, DEFAULT_MAX_FILE_CHARS);
991 assert!(
992 agent.own_budget.is_none(),
993 "prose files have no budget of their own"
994 );
995
996 let user = &rows[1];
997 assert!(user.exists);
998 assert_eq!(user.chars, "USER FACT: one line".chars().count());
999 assert_eq!(user.kept, user.chars, "nothing is clipped");
1000 assert!(!user.truncated());
1001
1002 let mem = &rows[2];
1003 assert_eq!(mem.file, "MEMORY.md");
1004 assert_eq!(mem.chars, "first fact\n§\nsecond fact".chars().count());
1005 assert!(mem.text.contains('§'));
1007 assert_eq!(mem.own_budget, Some(crate::memory::DEFAULT_BUDGET_CHARS));
1008 assert_eq!(user.position, Some(1));
1010 assert_eq!(mem.position, Some(2));
1011 }
1012
1013 #[test]
1014 fn the_nearest_agent_file_is_the_one_to_edit_and_the_wider_ones_are_counted() {
1015 let tmp = tempfile::tempdir().unwrap();
1016 let home = tmp.path();
1017 let repo = home.join("repo");
1018 let leaf = repo.join("crates/app");
1019 std::fs::create_dir_all(repo.join(".git")).unwrap();
1020 std::fs::create_dir_all(&leaf).unwrap();
1021 write(&repo.join("AGENT.md"), "REPO RULE");
1022 write(&leaf.join("AGENT.md"), "LEAF RULE");
1023 write(&home.join(".eclipse/memory/AGENT.md"), "GLOBAL RULE");
1024
1025 let cfg = cfg_in(home, &leaf);
1026 let env = home_env(home);
1027 let agent = editable(&cfg, &env)
1028 .into_iter()
1029 .find(|r| r.which == Which::Agent)
1030 .unwrap();
1031 assert_eq!(
1033 agent.path,
1034 std::fs::canonicalize(leaf.join("AGENT.md")).unwrap()
1035 );
1036 assert_eq!(agent.text, "LEAF RULE");
1037 assert_eq!(agent.others, 2);
1039 assert_eq!(agent.position, Some(3), "global, repo, leaf");
1040 }
1041
1042 #[test]
1046 fn a_project_agent_file_that_points_outside_the_tree_is_not_offered_for_editing() {
1047 let tmp = tempfile::tempdir().unwrap();
1048 let home = tmp.path().join("home");
1049 let workspace = home.join("work");
1050 std::fs::create_dir_all(&workspace).unwrap();
1051 let secret = tmp.path().join("id_rsa");
1052 write(&secret, "-----BEGIN OPENSSH PRIVATE KEY-----\n");
1053 std::os::unix::fs::symlink(&secret, workspace.join("AGENT.md")).unwrap();
1054
1055 let cfg = cfg_in(&home, &workspace);
1056 let env = home_env(&home);
1057 let agent = editable(&cfg, &env)
1058 .into_iter()
1059 .find(|r| r.which == Which::Agent)
1060 .expect("the row still exists: it promises the file a save would create");
1061 assert!(
1062 !agent.text.contains("PRIVATE KEY"),
1063 "the key is not served: {:?}",
1064 agent.text
1065 );
1066 assert_eq!(agent.path, home.join(".eclipse/memory/AGENT.md"));
1069 assert!(!agent.exists);
1070
1071 write_file(&cfg, &env, Which::Agent, "my rules\n").unwrap();
1073 assert_eq!(
1074 std::fs::read_to_string(&secret).unwrap(),
1075 "-----BEGIN OPENSSH PRIVATE KEY-----\n",
1076 "the key was not written through"
1077 );
1078 assert_eq!(
1079 std::fs::read_to_string(home.join(".eclipse/memory/AGENT.md")).unwrap(),
1080 "my rules\n"
1081 );
1082 }
1083
1084 #[test]
1087 fn a_project_agent_file_that_points_inside_the_tree_is_still_offered() {
1088 let tmp = tempfile::tempdir().unwrap();
1089 let home = tmp.path().join("home");
1090 let workspace = home.join("work");
1091 std::fs::create_dir_all(&workspace).unwrap();
1092 write(&workspace.join("docs/conventions.md"), "run make\n");
1093 std::os::unix::fs::symlink(
1094 workspace.join("docs/conventions.md"),
1095 workspace.join("AGENT.md"),
1096 )
1097 .unwrap();
1098
1099 let cfg = cfg_in(&home, &workspace);
1100 let env = home_env(&home);
1101 let agent = editable(&cfg, &env)
1102 .into_iter()
1103 .find(|r| r.which == Which::Agent)
1104 .unwrap();
1105 assert_eq!(agent.text, "run make\n");
1106 assert_eq!(
1107 agent.path,
1108 std::fs::canonicalize(workspace.join("docs/conventions.md")).unwrap()
1109 );
1110 }
1111
1112 #[test]
1113 fn a_file_past_the_per_file_ceiling_is_reported_as_clipped() {
1114 let tmp = tempfile::tempdir().unwrap();
1115 let home = tmp.path();
1116 let workspace = home.join("work");
1117 std::fs::create_dir_all(&workspace).unwrap();
1118 let memory = home.join(".eclipse/memory");
1119 write(&memory.join("USER.md"), &"x".repeat(200));
1120
1121 let mut cfg = cfg_in(home, &workspace);
1122 cfg.agent.context_file_max_chars = 100;
1123 let env = home_env(home);
1124 let user = editable(&cfg, &env)
1125 .into_iter()
1126 .find(|r| r.which == Which::User)
1127 .unwrap();
1128 assert_eq!(user.chars, 200);
1129 assert!(
1130 user.kept < user.chars,
1131 "the prompt keeps less than the file"
1132 );
1133 assert!(user.truncated());
1134 assert_eq!(user.max_chars, 100);
1136 }
1137
1138 #[test]
1139 fn a_save_creates_the_file_it_promised_and_leaves_no_temp_behind() {
1140 let tmp = tempfile::tempdir().unwrap();
1141 let home = tmp.path();
1142 let workspace = home.join("work");
1143 std::fs::create_dir_all(&workspace).unwrap();
1144 let cfg = cfg_in(home, &workspace);
1145 let env = home_env(home);
1146
1147 let row = write_file(&cfg, &env, Which::Agent, "RULE: one\n").unwrap();
1148 assert!(
1149 row.exists,
1150 "the row it answers with is the file it just created"
1151 );
1152 assert_eq!(row.path, home.join(".eclipse/memory/AGENT.md"));
1153 assert_eq!(std::fs::read_to_string(&row.path).unwrap(), "RULE: one\n");
1154 let leftovers: Vec<_> = std::fs::read_dir(home.join(".eclipse/memory"))
1156 .unwrap()
1157 .filter_map(|e| e.ok())
1158 .map(|e| e.file_name().to_string_lossy().into_owned())
1159 .filter(|n| n.contains("tmp"))
1160 .collect();
1161 assert!(leftovers.is_empty(), "{leftovers:?}");
1162
1163 let row = write_file(&cfg, &env, Which::Agent, "RULE: two\n").unwrap();
1165 assert_eq!(row.chars, "RULE: two\n".chars().count());
1166 assert_eq!(std::fs::read_to_string(&row.path).unwrap(), "RULE: two\n");
1167
1168 #[cfg(unix)]
1169 {
1170 use std::os::unix::fs::PermissionsExt;
1171 let mode = std::fs::metadata(&row.path).unwrap().permissions().mode() & 0o777;
1172 assert_eq!(mode, 0o600, "a file the page created is not world-readable");
1173 }
1174 }
1175
1176 #[test]
1177 fn a_memory_save_goes_through_the_memory_writer_and_is_refused_past_its_budget() {
1178 let tmp = tempfile::tempdir().unwrap();
1179 let home = tmp.path();
1180 let workspace = home.join("work");
1181 std::fs::create_dir_all(&workspace).unwrap();
1182 let cfg = cfg_in(home, &workspace);
1183 let env = home_env(home);
1184
1185 let row = write_file(&cfg, &env, Which::Memory, "fact one\n§\nfact two\n").unwrap();
1187 let entries = crate::memory::parse(&std::fs::read_to_string(&row.path).unwrap());
1188 assert_eq!(entries, vec!["fact one", "fact two"], "{entries:?}");
1189 let memory = crate::memory::Memory::new(&row.path, cfg.user.memory_budget_chars);
1191 assert_eq!(memory.read().unwrap().len(), 2);
1192
1193 let mut small = cfg_in(home, &workspace);
1194 small.user.memory_budget_chars = 20;
1195 let err = write_file(&small, &env, Which::Memory, &"y".repeat(200)).unwrap_err();
1196 let said = err.to_string();
1197 assert!(said.contains("budget"), "{said}");
1198 assert!(said.contains("remove or shorten"), "{said}");
1199 assert_eq!(memory.read().unwrap().len(), 2);
1201 }
1202
1203 #[test]
1207 fn the_plural_agents_md_is_read_when_the_singular_is_absent() {
1208 let tmp = tempfile::tempdir().unwrap();
1209 let (config, profile, workspace) = three(&tmp);
1210 write(&workspace.join("AGENTS.md"), "plural rules\n");
1211
1212 let ctx = gather(&sources(&config, &profile, &workspace), Budget::default());
1213 let instructions = ctx
1214 .instructions
1215 .iter()
1216 .map(|l| (l.name.as_str(), l.body.as_str()))
1217 .collect::<Vec<_>>();
1218 assert!(
1219 instructions
1220 .iter()
1221 .any(|(name, body)| *name == "AGENTS.md" && body.contains("plural rules")),
1222 "the alias is read and reported under its own name: {instructions:?}"
1223 );
1224 }
1225
1226 #[test]
1229 fn the_singular_wins_over_the_alias_in_the_same_directory() {
1230 let tmp = tempfile::tempdir().unwrap();
1231 let (config, profile, workspace) = three(&tmp);
1232 write(&workspace.join("AGENT.md"), "singular rules\n");
1233 write(&workspace.join("AGENTS.md"), "plural rules\n");
1234
1235 let ctx = gather(&sources(&config, &profile, &workspace), Budget::default());
1236 let names = ctx
1237 .instructions
1238 .iter()
1239 .map(|l| l.name.clone())
1240 .collect::<Vec<_>>();
1241 let bodies = ctx
1242 .instructions
1243 .iter()
1244 .map(|l| l.body.clone())
1245 .collect::<Vec<_>>();
1246 assert_eq!(
1247 names.iter().filter(|n| n.ends_with(".md")).count(),
1248 names.len()
1249 );
1250 assert!(
1251 !bodies.iter().any(|b| b.contains("plural rules")),
1252 "one file per directory, and it is the singular: {bodies:?}"
1253 );
1254 }
1255
1256 #[test]
1259 fn the_dotted_singular_wins_over_a_plain_alias() {
1260 let tmp = tempfile::tempdir().unwrap();
1261 let (config, profile, workspace) = three(&tmp);
1262 write(
1263 &workspace.join(".eclipse").join("AGENT.md"),
1264 "dotted rules\n",
1265 );
1266 write(&workspace.join("AGENTS.md"), "plural rules\n");
1267
1268 let ctx = gather(&sources(&config, &profile, &workspace), Budget::default());
1269 let bodies = ctx
1270 .instructions
1271 .iter()
1272 .map(|l| l.body.clone())
1273 .collect::<Vec<_>>();
1274 assert!(
1275 bodies.iter().any(|b| b.contains("dotted rules")),
1276 "{bodies:?}"
1277 );
1278 assert!(
1279 !bodies.iter().any(|b| b.contains("plural rules")),
1280 "{bodies:?}"
1281 );
1282 }
1283
1284 #[test]
1286 fn the_config_directory_accepts_the_alias() {
1287 let tmp = tempfile::tempdir().unwrap();
1288 let (config, profile, workspace) = three(&tmp);
1289 write(&config.join("AGENTS.md"), "install-wide rules\n");
1290
1291 let ctx = gather(&sources(&config, &profile, &workspace), Budget::default());
1292 let bodies = ctx
1293 .instructions
1294 .iter()
1295 .map(|l| l.body.clone())
1296 .collect::<Vec<_>>();
1297 assert!(
1298 bodies.iter().any(|b| b.contains("install-wide rules")),
1299 "{bodies:?}"
1300 );
1301 }
1302
1303 #[test]
1304 fn a_blank_or_empty_file_contributes_no_section() {
1305 let tmp = tempfile::tempdir().unwrap();
1306 let profile = tmp.path().join("profile");
1307 std::fs::create_dir_all(&profile).unwrap();
1308 std::fs::write(profile.join("MEMORY.md"), "").unwrap();
1310 std::fs::write(profile.join("USER.md"), "\n \n\t\n").unwrap();
1312 let workspace = profile.clone();
1313 let sources = Sources {
1314 config_dir: Some(&profile),
1315 profile_dir: Some(&profile),
1316 workspace: &workspace,
1317 home: None,
1318 user_file: "USER.md",
1319 memory_file: "MEMORY.md",
1320 };
1321 let ctx = gather(
1322 &sources,
1323 Budget {
1324 max_file_chars: 6000,
1325 total_chars: 12000,
1326 },
1327 );
1328 assert!(
1329 ctx.user.is_none(),
1330 "a whitespace-only USER.md is not a layer"
1331 );
1332 assert!(ctx.memory.is_none(), "an empty MEMORY.md is not a layer");
1333 assert!(ctx.is_empty(), "nothing to inject: {ctx:?}");
1334 }
1335
1336 #[test]
1337 fn a_project_file_is_found_from_a_subdirectory_up_to_the_repository_root() {
1338 let tmp = tempfile::tempdir().unwrap();
1339 let root = tmp.path();
1340 write(&root.join(".git/HEAD"), "ref: refs/heads/main");
1341 write(&root.join("AGENT.md"), "repo rules");
1342 write(&root.join("sub/deeper/AGENT.md"), "leaf rules");
1343 let workspace = root.join("sub/deeper");
1344
1345 let found = project_files(&workspace, None);
1346 let names: Vec<_> = found
1347 .iter()
1348 .map(|p| p.strip_prefix(root).unwrap().to_string_lossy().to_string())
1349 .collect();
1350 assert_eq!(
1351 names,
1352 ["AGENT.md", "sub/deeper/AGENT.md"],
1353 "outermost first, so the nearest file has the last word"
1354 );
1355 }
1356
1357 #[test]
1358 fn walking_up_stops_at_the_home_boundary_instead_of_reaching_root() {
1359 let tmp = tempfile::tempdir().unwrap();
1360 let home = tmp.path().join("home");
1361 let deep = home.join("work/proj");
1362 std::fs::create_dir_all(&deep).unwrap();
1363 write(&home.join("AGENT.md"), "home rules");
1364 write(&deep.join("AGENT.md"), "project rules");
1365
1366 let found = project_files(&deep, Some(&home));
1367 assert_eq!(found.len(), 2, "{found:?}");
1368 write(&tmp.path().join("AGENT.md"), "above home");
1370 let found = project_files(&deep, Some(&home));
1371 assert_eq!(found.len(), 2, "{found:?}");
1372 assert!(found.iter().all(|p| p.starts_with(&home)));
1373 let elsewhere = tmp.path().join("elsewhere/a/b/proj");
1377 std::fs::create_dir_all(&elsewhere).unwrap();
1378 write(
1379 &tmp.path().join("elsewhere/AGENT.md"),
1380 "an unrelated project",
1381 );
1382 write(
1383 &tmp.path().join("elsewhere/a/AGENT.md"),
1384 "another unrelated project",
1385 );
1386 write(&elsewhere.join("AGENT.md"), "project rules");
1387 assert_eq!(
1388 project_files(&elsewhere, Some(&home)),
1389 [elsewhere.join("AGENT.md")],
1390 "the workspace's own file, and nothing from the trees above it"
1391 );
1392 }
1393
1394 #[test]
1395 fn a_dot_eclipse_file_is_used_when_there_is_no_agent_md() {
1396 let tmp = tempfile::tempdir().unwrap();
1397 let root = tmp.path();
1398 write(&root.join(".git/HEAD"), "ref: refs/heads/main");
1399 write(&root.join(".eclipse/AGENT.md"), "hidden rules");
1400 let found = project_files(root, None);
1401 assert_eq!(found, [root.join(".eclipse/AGENT.md")]);
1402 }
1403
1404 #[test]
1405 fn a_plain_agent_md_wins_over_the_hidden_one() {
1406 let tmp = tempfile::tempdir().unwrap();
1407 let root = tmp.path();
1408 write(&root.join(".git/HEAD"), "ref: refs/heads/main");
1409 write(&root.join(".eclipse/AGENT.md"), "hidden rules");
1410 write(&root.join("AGENT.md"), "visible rules");
1411 assert_eq!(project_files(root, None), [root.join("AGENT.md")]);
1412 }
1413
1414 #[test]
1415 fn every_file_kind_lands_in_its_layer_and_in_injection_order() {
1416 let tmp = tempfile::tempdir().unwrap();
1417 let config = tmp.path().join("config");
1418 let profile = config.join("profiles/work");
1419 let repo = tmp.path().join("repo");
1420 write(&repo.join(".git/HEAD"), "ref: refs/heads/main");
1421 write(&config.join("AGENT.md"), "global rules");
1422 write(&repo.join("AGENT.md"), "repo rules");
1423 write(&profile.join("USER.md"), "I am Max, be direct");
1424 write(&profile.join("MEMORY.md"), "the fleet is two servers");
1425 let workspace = repo.join("crates");
1426
1427 let ctx = gather(&sources(&config, &profile, &workspace), Budget::default());
1428 assert_eq!(ctx.instructions.len(), 2);
1429 assert!(
1430 ctx.instructions[0].path.starts_with(&config),
1431 "global first"
1432 );
1433 assert!(ctx.instructions[1].path.starts_with(&repo), "then project");
1434 assert_eq!(ctx.user.as_ref().unwrap().body, "I am Max, be direct");
1435 assert_eq!(
1438 ctx.memory.as_ref().unwrap().body,
1439 "- the fleet is two servers"
1440 );
1441
1442 let prompt = assemble("You are Eclipse.", &ctx, &["plugin says hi".into()]);
1443 let order: Vec<&str> = [
1444 "You are Eclipse.",
1445 "global rules",
1446 "repo rules",
1447 "plugin says hi",
1448 "I am Max, be direct",
1449 "the fleet is two servers",
1450 ]
1451 .to_vec();
1452 let mut at = 0;
1453 for needle in order {
1454 let found = prompt[at..]
1455 .find(needle)
1456 .unwrap_or_else(|| panic!("{needle:?} missing or out of order in:\n{prompt}"));
1457 at += found;
1458 }
1459 assert!(prompt.contains("## AGENT.md ("), "{prompt}");
1461 assert!(prompt.contains("## USER.md ("), "{prompt}");
1462 assert!(prompt.contains("## MEMORY.md ("), "{prompt}");
1463 }
1464
1465 #[test]
1466 fn a_long_file_keeps_its_head_and_its_tail_and_says_what_went() {
1467 let tmp = tempfile::tempdir().unwrap();
1468 let config = tmp.path().join("config");
1469 let profile = config.join("profiles/default");
1470 let workspace = tmp.path().join("ws");
1471 std::fs::create_dir_all(&workspace).unwrap();
1472 let body = format!("HEAD{}{}TAIL", "x".repeat(500), "y".repeat(500));
1473 write(&profile.join("USER.md"), &body);
1474
1475 let budget = Budget {
1476 max_file_chars: 200,
1477 total_chars: 10_000,
1478 };
1479 let ctx = gather(&sources(&config, &profile, &workspace), budget);
1480 let user = ctx.user.unwrap();
1481 assert!(user.truncated());
1482 assert_eq!(user.original_chars, body.chars().count());
1483 assert!(user.body.starts_with("HEAD"), "{}", user.body);
1484 assert!(user.body.ends_with("TAIL"), "{}", user.body);
1485 assert!(
1486 user.body.contains("[… truncated:") && user.body.contains("chars …]"),
1487 "the cut is visible: {}",
1488 user.body
1489 );
1490 assert!(
1491 user.chars <= 200,
1492 "the cap includes the marker: {} chars",
1493 user.chars
1494 );
1495 }
1496
1497 #[test]
1498 fn the_cap_is_a_hard_cap_marker_included() {
1499 for max in [60usize, 120, 200, 1000] {
1500 let text = "x".repeat(5000);
1501 let out = clip(&text, max);
1502 assert!(
1503 out.chars().count() <= max,
1504 "clip({max}) produced {} chars",
1505 out.chars().count()
1506 );
1507 assert!(out.contains("[… truncated:"), "{out}");
1508 }
1509 assert_eq!(clip("short", 100), "short");
1511 }
1512
1513 #[test]
1514 fn truncation_never_splits_a_character() {
1515 let text = "é".repeat(100);
1516 let clipped = clip(&text, 80);
1517 assert!(clipped.starts_with("éé"), "{clipped}");
1518 assert!(clipped.ends_with('é'), "{clipped}");
1519 assert!(clipped.chars().count() <= 80);
1520 assert!(clipped.is_char_boundary(clipped.len()));
1521
1522 let cramped = clip(&text, 21);
1527 assert!(cramped.chars().count() <= 21, "{cramped}");
1528 assert!(cramped.contains("100"), "{cramped}");
1529 assert!(!cramped.is_empty() && cramped.is_char_boundary(cramped.len()));
1530 }
1531
1532 #[test]
1533 fn over_the_total_the_broadest_file_goes_first_and_the_drop_is_named() {
1534 let tmp = tempfile::tempdir().unwrap();
1535 let config = tmp.path().join("config");
1536 let profile = config.join("profiles/default");
1537 let repo = tmp.path().join("repo");
1538 write(&repo.join(".git/HEAD"), "ref: refs/heads/main");
1539 write(&config.join("AGENT.md"), &"g".repeat(400));
1540 write(&repo.join("AGENT.md"), &"r".repeat(400));
1541 write(&profile.join("USER.md"), "user");
1542 write(&profile.join("MEMORY.md"), "memory");
1543
1544 let budget = Budget {
1545 max_file_chars: 6000,
1546 total_chars: 900,
1547 };
1548 let ctx = gather(&sources(&config, &profile, &repo), budget);
1549 assert_eq!(ctx.instructions.len(), 2);
1551 assert!(ctx.notes.is_empty(), "{:?}", ctx.notes);
1552
1553 let budget = Budget {
1554 max_file_chars: 6000,
1555 total_chars: 500,
1556 };
1557 let ctx = gather(&sources(&config, &profile, &repo), budget);
1558 assert_eq!(ctx.instructions.len(), 1, "the global file went first");
1559 assert!(ctx.instructions[0].path.starts_with(&repo));
1560 assert!(ctx.user.is_some() && ctx.memory.is_some());
1561 assert!(
1562 ctx.notes
1563 .iter()
1564 .any(|n| n.contains("dropped") && n.contains("chars")),
1565 "{:?}",
1566 ctx.notes
1567 );
1568 }
1569
1570 #[test]
1571 fn a_missing_config_directory_is_not_an_error() {
1572 let workspace = tempfile::tempdir().unwrap();
1573 let ctx = gather(
1574 &Sources {
1575 config_dir: Some(Path::new("/nonexistent/eclipse")),
1576 profile_dir: Some(Path::new("/nonexistent/eclipse/profiles/default")),
1577 workspace: workspace.path(),
1578 home: None,
1579 user_file: "USER.md",
1580 memory_file: "MEMORY.md",
1581 },
1582 Budget::default(),
1583 );
1584 assert!(ctx.is_empty());
1585 assert_eq!(assemble("base", &ctx, &[]), "base");
1586 }
1587
1588 #[test]
1589 fn the_fragments_sit_between_the_instruction_files_and_the_user_model() {
1590 let ctx = Context {
1591 instructions: vec![Layer {
1592 name: "AGENT.md".into(),
1593 path: PathBuf::from("/r/AGENT.md"),
1594 body: "rules".into(),
1595 chars: 5,
1596 original_chars: 5,
1597 }],
1598 user: Some(Layer {
1599 name: "USER.md".into(),
1600 path: PathBuf::from("/p/USER.md"),
1601 body: "who".into(),
1602 chars: 3,
1603 original_chars: 3,
1604 }),
1605 memory: None,
1606 skills: None,
1607 notes: Vec::new(),
1608 skill_notes: Vec::new(),
1609 guidance: String::new(),
1610 };
1611 let prompt = assemble("base", &ctx, &["frag".into(), " ".into()]);
1612 let prompt = prompt.replace("\n", " ");
1613 let compact = prompt.split_whitespace().collect::<Vec<_>>().join(" ");
1614 assert!(
1615 compact.ends_with("rules frag ## USER.md (/p/USER.md) who"),
1616 "{compact}"
1617 );
1618 assert_eq!(ctx.total_chars(), 8);
1619 }
1620
1621 fn skill(dir: &Path, name: &str, description: &str) {
1622 write(
1623 &dir.join(name).join("SKILL.md"),
1624 &format!("---\nname: {name}\ndescription: {description}\n---\nDo {name}.\n"),
1625 );
1626 }
1627
1628 fn env_for(home: &Path) -> impl Fn(&str) -> Option<String> {
1629 let home = home.display().to_string();
1630 move |key: &str| (key == "HOME").then(|| home.clone())
1631 }
1632
1633 #[test]
1634 fn the_skills_index_is_the_last_labelled_layer_after_memory() {
1635 let tmp = tempfile::tempdir().unwrap();
1636 let (config, profile, workspace) = (
1637 tmp.path().join("c"),
1638 tmp.path().join("p"),
1639 tmp.path().join("w"),
1640 );
1641 write(&config.join("AGENT.md"), "RULES");
1642 write(&profile.join("USER.md"), "WHO");
1643 write(&profile.join("MEMORY.md"), "a fact");
1644 skill(&config.join("skills"), "backup", "back things up");
1645 let report = crate::skills::discover(&[crate::skills::Root {
1646 source: crate::skills::Source::Shared,
1647 dir: config.join("skills"),
1648 }]);
1649 let ctx = gather(&sources(&config, &profile, &workspace), Budget::default())
1650 .with_skills(&report, 4000);
1651
1652 let prompt = assemble("base", &ctx, &[]);
1653 let at = |needle: &str| {
1654 prompt
1655 .find(needle)
1656 .unwrap_or_else(|| panic!("{needle}: {prompt}"))
1657 };
1658 assert!(at("a fact") < at("## Skills"), "after MEMORY.md: {prompt}");
1659 assert!(prompt.contains("- backup: back things up"), "{prompt}");
1660 assert!(
1661 !prompt.contains("Do backup."),
1662 "the body is loaded on demand: {prompt}"
1663 );
1664 assert!(prompt.trim_end().ends_with("back things up"), "{prompt}");
1665 assert!(!ctx.is_empty());
1666 assert_eq!(
1667 ctx.total_chars(),
1668 "RULES".len() + "WHO".len() + "- a fact".len()
1669 );
1670 }
1671
1672 #[test]
1673 fn the_config_reaches_the_shared_profile_and_workspace_skills_and_the_budget() {
1674 let tmp = tempfile::tempdir().unwrap();
1675 let home = tmp.path();
1676 let config = home.join(".eclipse");
1677 let workspace = home.join("ws");
1678 skill(&config.join("skills"), "backup", "the shared one");
1679 skill(&config.join("skills"), "other", "shared only");
1680 skill(
1681 &config.join("profiles/work/skills"),
1682 "backup",
1683 "the profile one",
1684 );
1685 skill(&workspace.join(".eclipse/skills"), "deploy", "this project");
1686
1687 let mut cfg = crate::config::Config {
1688 profile: Some("work".into()),
1689 ..Default::default()
1690 };
1691 cfg.tools.workspace_root = Some(workspace.clone());
1692 let env = env_for(home);
1693 let plugins = crate::plugins::Plugins::default();
1694
1695 let ctx = for_config(&cfg, &env, &plugins);
1696 let index = ctx.skills.as_ref().unwrap();
1697 assert!(index.body.contains("the profile one"), "{}", index.body);
1698 assert!(
1699 !index.body.contains("the shared one"),
1700 "the profile shadows it"
1701 );
1702 assert!(index.body.contains("- deploy: this project"));
1703 assert!(index.body.contains("- other: shared only"));
1704 assert!(ctx.skill_notes.is_empty(), "{:?}", ctx.skill_notes);
1705
1706 cfg.skills.index_budget_chars = index.chars - 10;
1707 let ctx = for_config(&cfg, &env, &plugins);
1708 assert_eq!(ctx.skills.as_ref().unwrap().names.len(), 2);
1709 assert!(
1710 ctx.skill_notes
1711 .iter()
1712 .any(|n| n.contains("left out 1 of 3")),
1713 "{:?}",
1714 ctx.skill_notes
1715 );
1716 }
1717
1718 fn under_home<'a>(
1722 config: &'a Path,
1723 profile: &'a Path,
1724 workspace: &'a Path,
1725 home: &'a Path,
1726 ) -> Sources<'a> {
1727 Sources {
1728 config_dir: Some(config),
1729 profile_dir: Some(profile),
1730 workspace,
1731 home: Some(home),
1732 user_file: "USER.md",
1733 memory_file: "MEMORY.md",
1734 }
1735 }
1736
1737 #[test]
1740 fn a_project_file_that_points_outside_the_tree_is_not_read() {
1741 let tmp = tempfile::tempdir().unwrap();
1742 let home = tmp.path().join("home");
1743 let workspace = home.join("work");
1744 std::fs::create_dir_all(&workspace).unwrap();
1745 let config = tmp.path().join("config");
1746 let profile = tmp.path().join("profile");
1747 let secret = tmp.path().join("id_rsa");
1749 write(&secret, "-----BEGIN OPENSSH PRIVATE KEY-----\n");
1750 std::os::unix::fs::symlink(&secret, workspace.join("AGENTS.md")).unwrap();
1751
1752 let ctx = gather(
1753 &under_home(&config, &profile, &workspace, &home),
1754 Budget::default(),
1755 );
1756 assert!(
1757 ctx.instructions.is_empty(),
1758 "nothing from the link: {:?}",
1759 ctx.instructions
1760 );
1761 assert!(
1762 ctx.notes
1763 .iter()
1764 .any(|n| n.contains("points outside the project")),
1765 "{:?}",
1766 ctx.notes
1767 );
1768 }
1769
1770 #[test]
1773 fn a_project_file_that_points_inside_the_tree_is_still_read() {
1774 let tmp = tempfile::tempdir().unwrap();
1775 let (config, profile, workspace) = three(&tmp);
1776 write(
1777 &workspace.join("docs/conventions.md"),
1778 "run make, never cargo test\n",
1779 );
1780 std::os::unix::fs::symlink(
1781 workspace.join("docs/conventions.md"),
1782 workspace.join("AGENTS.md"),
1783 )
1784 .unwrap();
1785
1786 let ctx = gather(
1787 &under_home(&config, &profile, &workspace, tmp.path()),
1788 Budget::default(),
1789 );
1790 assert_eq!(ctx.instructions.len(), 1, "{:?}", ctx.notes);
1791 assert!(ctx.instructions[0].body.contains("run make"));
1792 assert_eq!(
1793 ctx.instructions[0].path,
1794 std::fs::canonicalize(workspace.join("docs/conventions.md")).unwrap(),
1795 "the label names the file that was read"
1796 );
1797 }
1798
1799 #[test]
1802 fn the_operators_own_agent_file_may_still_be_a_symlink() {
1803 let tmp = tempfile::tempdir().unwrap();
1804 let (config, profile, workspace) = three(&tmp);
1805 let shared = tmp.path().join("dotfiles/AGENT.md");
1806 write(&shared, "my rules, kept outside any project\n");
1807 std::fs::create_dir_all(&config).unwrap();
1808 std::os::unix::fs::symlink(&shared, config.join("AGENT.md")).unwrap();
1809
1810 let ctx = gather(
1811 &under_home(&config, &profile, &workspace, tmp.path()),
1812 Budget::default(),
1813 );
1814 assert_eq!(ctx.instructions.len(), 1, "{:?}", ctx.notes);
1815 assert!(ctx.instructions[0].body.contains("my rules"));
1816 }
1817
1818 #[test]
1821 fn a_context_file_that_is_not_a_regular_file_is_refused() {
1822 let tmp = tempfile::tempdir().unwrap();
1823 let (config, profile, workspace) = three(&tmp);
1824 std::fs::create_dir_all(&profile).unwrap();
1825 let fifo = profile.join("USER.md");
1826 let made = std::process::Command::new("mkfifo").arg(&fifo).status();
1827 assert!(
1828 matches!(made, Ok(s) if s.success()),
1829 "mkfifo is how this test makes the case: {made:?}"
1830 );
1831
1832 let ctx = gather(
1833 &under_home(&config, &profile, &workspace, tmp.path()),
1834 Budget::default(),
1835 );
1836 assert!(ctx.user.is_none(), "no section, and no hang");
1837 assert!(
1838 ctx.notes
1839 .iter()
1840 .any(|n| n.contains("is not a regular file")),
1841 "{:?}",
1842 ctx.notes
1843 );
1844 }
1845
1846 #[test]
1849 fn an_enormous_context_file_is_read_only_to_the_cap() {
1850 let tmp = tempfile::tempdir().unwrap();
1851 let (config, profile, workspace) = three(&tmp);
1852 std::fs::create_dir_all(&profile).unwrap();
1853 let body = "a".repeat(2 * 1024 * 1024);
1855 std::fs::write(profile.join("USER.md"), &body).unwrap();
1856
1857 let mut ctx = gather(
1858 &under_home(&config, &profile, &workspace, tmp.path()),
1859 Budget::default(),
1860 );
1861 let layer = ctx.user.take().expect("the head of it is still read");
1862 assert!(layer.truncated(), "the injected body is clipped");
1863 assert_eq!(
1864 layer.original_chars,
1865 (MAX_LAYER_BYTES) as usize,
1866 "read exactly to the cap, not to the end of the file"
1867 );
1868 assert!(
1869 ctx.notes
1870 .iter()
1871 .any(|n| n.contains("read only to that point")),
1872 "{:?}",
1873 ctx.notes
1874 );
1875 }
1876}