use std::io::Read;
use std::path::{Path, PathBuf};
pub const DEFAULT_MAX_FILE_CHARS: usize = 6000;
pub const DEFAULT_BUDGET_CHARS: usize = 12000;
const MIN_CLIP: usize = 120;
const MAX_WALK: usize = 64;
const MAX_LAYER_BYTES: u64 = 1 << 20;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Budget {
pub max_file_chars: usize,
pub total_chars: usize,
}
impl Default for Budget {
fn default() -> Self {
Self {
max_file_chars: DEFAULT_MAX_FILE_CHARS,
total_chars: DEFAULT_BUDGET_CHARS,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Layer {
pub name: String,
pub path: PathBuf,
pub body: String,
pub chars: usize,
pub original_chars: usize,
}
impl Layer {
pub fn truncated(&self) -> bool {
self.original_chars > self.chars
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Context {
pub instructions: Vec<Layer>,
pub user: Option<Layer>,
pub memory: Option<Layer>,
pub skills: Option<crate::skills::Index>,
pub notes: Vec<String>,
pub skill_notes: Vec<String>,
pub guidance: String,
}
impl Context {
fn with_guidance(mut self, cfg: &crate::config::Config) -> Self {
self.guidance = cfg.agent.prompt_blocks.guidance(&cfg.provider.model);
self
}
pub fn layers(&self) -> impl Iterator<Item = &Layer> {
self.instructions
.iter()
.chain(self.user.iter())
.chain(self.memory.iter())
}
pub fn total_chars(&self) -> usize {
self.layers().map(|l| l.chars).sum()
}
pub fn is_empty(&self) -> bool {
self.layers().next().is_none() && self.skills.is_none()
}
pub fn with_skills(mut self, report: &crate::skills::Report, budget: usize) -> Self {
let (index, notes) = crate::skills::index(report, budget);
self.skills = index;
self.skill_notes = notes;
self
}
}
pub struct Sources<'a> {
pub config_dir: Option<&'a Path>,
pub profile_dir: Option<&'a Path>,
pub workspace: &'a Path,
pub home: Option<&'a Path>,
pub user_file: &'a str,
pub memory_file: &'a str,
}
pub fn gather(sources: &Sources<'_>, budget: Budget) -> Context {
let mut ctx = Context::default();
if let Some(dir) = sources.config_dir {
if let Some(path) = context_file_in(dir) {
let name = layer_name(&path);
push_layer(
&mut ctx.instructions,
&name,
path,
None,
budget,
&mut ctx.notes,
);
}
}
let (project, root) = project_walk(sources.workspace, sources.home);
for path in project {
let name = layer_name(&path);
push_layer(
&mut ctx.instructions,
&name,
path,
Some(&root),
budget,
&mut ctx.notes,
);
}
if let Some(dir) = sources.profile_dir {
ctx.user = read_layer(
sources.user_file,
dir.join(sources.user_file),
None,
budget,
&mut ctx.notes,
);
ctx.memory = read_layer(
sources.memory_file,
dir.join(sources.memory_file),
None,
budget,
&mut ctx.notes,
)
.map(render_memory);
}
apply_total(&mut ctx, budget.total_chars);
ctx
}
pub fn project_files(workspace: &Path, home: Option<&Path>) -> Vec<PathBuf> {
project_walk(workspace, home).0
}
pub fn project_walk(workspace: &Path, home: Option<&Path>) -> (Vec<PathBuf>, PathBuf) {
let home = home.and_then(|h| std::fs::canonicalize(h).ok().or(Some(h.to_path_buf())));
let mut dir = std::fs::canonicalize(workspace).unwrap_or_else(|_| workspace.to_path_buf());
let mut found: Vec<PathBuf> = Vec::new();
for _ in 0..MAX_WALK {
if let Some(path) = agent_file_in(&dir) {
found.push(path);
}
if dir.join(".git").exists() {
break;
}
let Some(parent) = dir.parent() else { break };
if let Some(ref home) = home {
if !parent.starts_with(home) {
break;
}
}
dir = parent.to_path_buf();
}
found.reverse();
let top = std::fs::canonicalize(&dir).unwrap_or(dir);
(found, top)
}
fn agent_file_in(dir: &Path) -> Option<PathBuf> {
[
dir.join("AGENT.md"),
dir.join(".eclipse").join("AGENT.md"),
dir.join("AGENTS.md"),
dir.join(".eclipse").join("AGENTS.md"),
]
.into_iter()
.find(|candidate| candidate.is_file())
}
fn context_file_in(dir: &Path) -> Option<PathBuf> {
["AGENT.md", "AGENTS.md"]
.iter()
.map(|name| dir.join(*name))
.find(|path| path.is_file())
}
fn layer_name(path: &Path) -> String {
path.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "AGENT.md".to_string())
}
fn render_memory(layer: Layer) -> Layer {
let entries = crate::memory::parse(&layer.body);
let body = entries
.iter()
.map(|entry| {
let mut lines = entry.lines();
let mut out = format!("- {}", lines.next().unwrap_or("").trim());
for line in lines {
out.push_str("\n ");
out.push_str(line.trim());
}
out
})
.collect::<Vec<_>>()
.join("\n");
Layer {
chars: body.chars().count(),
original_chars: layer.original_chars,
body,
..layer
}
}
fn push_layer(
into: &mut Vec<Layer>,
name: &str,
path: PathBuf,
boundary: Option<&Path>,
budget: Budget,
notes: &mut Vec<String>,
) {
if let Some(layer) = read_layer(name, path, boundary, budget, notes) {
into.push(layer);
}
}
fn read_layer(
name: &str,
path: PathBuf,
boundary: Option<&Path>,
budget: Budget,
notes: &mut Vec<String>,
) -> Option<Layer> {
let shown = path.display().to_string();
match std::fs::metadata(&path) {
Ok(meta) if meta.is_file() => {}
Ok(_) => {
notes.push(format!("{name} at {shown} is not a regular file; not read"));
return None;
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None,
Err(e) => {
notes.push(format!("{name} at {shown} could not be read: {e}"));
return None;
}
}
let path = std::fs::canonicalize(&path).unwrap_or(path);
if let Some(root) = boundary {
if !path.starts_with(root) {
notes.push(format!(
"{name} at {shown} points outside the project ({}); not read",
path.display()
));
return None;
}
}
let raw = read_capped(&path, name, notes)?;
let original = raw.chars().count();
if raw.trim().is_empty() {
return None; }
let body = clip(&raw, budget.max_file_chars);
let chars = body.chars().count();
Some(Layer {
name: name.to_string(),
path,
body,
chars,
original_chars: original,
})
}
fn read_capped(path: &Path, name: &str, notes: &mut Vec<String>) -> Option<String> {
let file = std::fs::File::open(path).ok()?;
let mut bytes = Vec::new();
file.take(MAX_LAYER_BYTES + 1)
.read_to_end(&mut bytes)
.ok()?;
let cut = bytes.len() as u64 > MAX_LAYER_BYTES;
if cut {
bytes.truncate(MAX_LAYER_BYTES as usize);
}
let text = match String::from_utf8(bytes) {
Ok(text) => text,
Err(e) => {
if !cut || e.utf8_error().error_len().is_some() {
return None;
}
let valid = e.utf8_error().valid_up_to();
let bytes = e.into_bytes();
String::from_utf8_lossy(&bytes[..valid]).into_owned()
}
};
if cut {
notes.push(format!(
"{name} is larger than {} KB and was read only to that point",
MAX_LAYER_BYTES / 1024
));
}
Some(text)
}
fn clip(text: &str, max: usize) -> String {
let total = text.chars().count();
if total <= max || max == 0 {
return text.to_string();
}
let full = |removed: usize| format!("\n\n[… truncated: {removed} chars …]\n\n");
let tight = format!("[…{total}c…]");
let mut room = max.saturating_sub(full(total).chars().count());
if room < 12 {
return if tight.chars().count() <= max {
tight
} else {
tight.chars().take(max).collect()
};
}
loop {
let head_budget = room / 2;
let tail_budget = room - head_budget;
let removed = total.saturating_sub(head_budget + tail_budget);
let marker = full(removed);
let fits = head_budget + tail_budget + marker.chars().count();
if fits <= max {
let head: String = text.chars().take(head_budget).collect();
let tail: String = text
.chars()
.rev()
.take(tail_budget)
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect();
return format!("{head}{marker}{tail}");
}
let next = max.saturating_sub(marker.chars().count() + 1);
if next >= room {
return tight;
}
room = next;
}
}
fn apply_total(ctx: &mut Context, total: usize) {
if total == 0 || ctx.total_chars() <= total {
return;
}
let mut notes = Vec::new();
while ctx.total_chars() > total && !ctx.instructions.is_empty() {
let layer = ctx.instructions.remove(0);
notes.push(dropped(&layer, total));
}
if ctx.total_chars() > total {
if let Some(layer) = ctx.memory.take() {
notes.push(dropped(&layer, total));
}
}
if ctx.total_chars() > total {
if let Some(mut layer) = ctx.user.take() {
let left = total.saturating_sub(ctx.total_chars());
if left >= MIN_CLIP {
let body = clip(&layer.body, left);
notes.push(format!(
"clipped {} to {left} chars to fit the {total} char budget",
layer.path.display()
));
layer.chars = body.chars().count();
layer.body = body;
ctx.user = Some(layer);
} else {
notes.push(dropped(&layer, total));
}
}
}
ctx.notes.extend(notes);
}
fn dropped(layer: &Layer, total: usize) -> String {
format!(
"dropped {} ({} chars): over the {total} char budget",
layer.path.display(),
layer.chars
)
}
pub fn for_config(
cfg: &crate::config::Config,
env: crate::config::EnvFn,
plugins: &crate::plugins::Plugins,
) -> Context {
for_config_with(cfg, env, plugins, None)
}
pub fn for_config_with(
cfg: &crate::config::Config,
env: crate::config::EnvFn,
plugins: &crate::plugins::Plugins,
only: Option<&[String]>,
) -> Context {
let workspace = cfg.workspace_root(env);
let ctx = gather_for(cfg, env);
let report = crate::skills::discover_only(
&crate::skills::roots_for(cfg, env, plugins, &workspace),
only,
);
ctx.with_skills(&report, cfg.skills.index_budget_chars)
}
fn gather_for(cfg: &crate::config::Config, env: crate::config::EnvFn) -> Context {
let workspace = cfg.workspace_root(env);
let config_root = cfg.memory_dir(env);
let profile_dir = config_root.clone();
let home = cfg.home(env);
let sources = Sources {
config_dir: config_root.as_deref(),
profile_dir: profile_dir.as_deref(),
workspace: &workspace,
home: home.as_deref(),
user_file: &cfg.user.file,
memory_file: &cfg.user.memory_file,
};
gather(
&sources,
Budget {
max_file_chars: cfg.agent.context_file_max_chars,
total_chars: cfg.agent.context_files_budget_chars,
},
)
.with_guidance(cfg)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Which {
Agent,
User,
Memory,
}
impl Which {
pub fn id(self) -> &'static str {
match self {
Which::Agent => "agent",
Which::User => "user",
Which::Memory => "memory",
}
}
pub fn from_id(id: &str) -> Option<Self> {
match id {
"agent" => Some(Which::Agent),
"user" => Some(Which::User),
"memory" => Some(Which::Memory),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Editable {
pub which: Which,
pub file: String,
pub path: PathBuf,
pub exists: bool,
pub text: String,
pub chars: usize,
pub kept: usize,
pub max_chars: usize,
pub own_budget: Option<usize>,
pub total: usize,
pub total_budget: usize,
pub position: Option<usize>,
pub others: usize,
}
impl Editable {
pub fn truncated(&self) -> bool {
self.kept < self.chars
}
}
pub fn editable(cfg: &crate::config::Config, env: crate::config::EnvFn) -> Vec<Editable> {
let ctx = gather_for(cfg, env);
let total = ctx.total_chars();
let total_budget = cfg.agent.context_files_budget_chars;
let max_chars = cfg.agent.context_file_max_chars;
let dir = cfg.memory_dir(env);
let layers: Vec<&Layer> = ctx.layers().collect();
let position_of = |path: &Path| layers.iter().position(|l| l.path == path).map(|i| i + 1);
let workspace = cfg.workspace_root(env);
let (project, boundary) = project_walk(&workspace, cfg.home(env).as_deref());
let project: Vec<PathBuf> = project
.into_iter()
.filter(|path| canonical_or(path).starts_with(&boundary))
.collect();
let mut rows = Vec::new();
let agent = project
.last()
.cloned()
.or_else(|| Some(dir.as_ref()?.join("AGENT.md")));
if let Some(path) = agent {
let layer = layers.iter().find(|l| l.path == canonical_or(&path));
let agents = layers
.iter()
.filter(|l| l.name.starts_with("AGENT"))
.count();
let others = agents.saturating_sub(usize::from(layer.is_some()));
rows.push(row_from(
Which::Agent,
path,
layer.copied(),
max_chars,
None,
total,
total_budget,
position_of,
others,
));
}
if let Some(dir) = dir.as_deref() {
for (which, file, own_budget) in [
(Which::User, cfg.user.file.clone(), None),
(
Which::Memory,
cfg.user.memory_file.clone(),
Some(cfg.user.memory_budget_chars),
),
] {
let path = dir.join(&file);
let layer = layers.iter().find(|l| l.path == canonical_or(&path));
rows.push(row_from(
which,
path,
layer.copied(),
max_chars,
own_budget,
total,
total_budget,
position_of,
0,
));
}
}
rows
}
#[allow(clippy::too_many_arguments)]
fn row_from(
which: Which,
path: PathBuf,
layer: Option<&Layer>,
max_chars: usize,
own_budget: Option<usize>,
total: usize,
total_budget: usize,
position_of: impl Fn(&Path) -> Option<usize>,
others: usize,
) -> Editable {
let canonical = canonical_or(&path);
let text = std::fs::read_to_string(&canonical).unwrap_or_default();
let chars = text.chars().count();
let kept = layer.map_or(chars, |l| l.chars);
Editable {
which,
position: position_of(&canonical),
file: path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| format!("{}.md", which.id())),
exists: canonical.is_file(),
chars,
kept,
max_chars,
own_budget,
total,
total_budget,
others,
path: canonical,
text,
}
}
fn canonical_or(path: &Path) -> PathBuf {
std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}
pub fn write_file(
cfg: &crate::config::Config,
env: crate::config::EnvFn,
which: Which,
text: &str,
) -> crate::error::Result<Editable> {
let Some(row) = editable(cfg, env).into_iter().find(|r| r.which == which) else {
return Err(crate::error::Error::Config(format!(
"this configuration has no {} file to write",
which.id()
)));
};
match which {
Which::Memory => {
let memory = crate::memory::Memory::new(&row.path, cfg.user.memory_budget_chars);
if let crate::memory::Outcome::Full {
chars,
budget,
entries,
} = memory.replace(crate::memory::parse(text))?
{
return Err(crate::error::Error::Config(format!(
"{} would be {chars} chars and its budget is {budget}; it holds {} entr{} now — \
remove or shorten one here instead",
row.file,
entries.len(),
if entries.len() == 1 { "y" } else { "ies" }
)));
}
}
Which::Agent | Which::User => {
crate::atomic::write_file_atomically(&row.path, text)
.map_err(|e| crate::error::Error::io(&row.path, e))?;
}
}
let after = editable(cfg, env);
after.into_iter().find(|r| r.which == which).ok_or_else(|| {
crate::error::Error::Config("the file vanished while it was being written".into())
})
}
pub fn assemble(base: &str, ctx: &Context, fragments: &[String]) -> String {
let mut parts: Vec<String> = Vec::new();
let base = base.trim();
if !base.is_empty() {
parts.push(base.to_string());
}
let guidance = ctx.guidance.trim();
if !guidance.is_empty() {
parts.push(guidance.to_string());
}
for layer in &ctx.instructions {
parts.push(labelled(layer));
}
for fragment in fragments {
let fragment = fragment.trim();
if !fragment.is_empty() {
parts.push(fragment.to_string());
}
}
if let Some(user) = &ctx.user {
parts.push(labelled(user));
}
if let Some(memory) = &ctx.memory {
parts.push(labelled(memory));
}
if let Some(skills) = &ctx.skills {
parts.push(format!("## Skills\n\n{}", skills.body));
}
parts.join("\n\n")
}
fn labelled(layer: &Layer) -> String {
format!(
"## {} ({})\n\n{}",
layer.name,
layer.path.display(),
layer.body.trim_end()
)
}
#[cfg(test)]
mod tests {
use super::*;
fn write(path: &Path, body: &str) {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).unwrap();
}
std::fs::write(path, body).unwrap();
}
fn three(
tmp: &tempfile::TempDir,
) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) {
let config = tmp.path().join("config");
let profile = tmp.path().join("profile");
let workspace = tmp.path().join("work");
std::fs::create_dir_all(&workspace).unwrap();
(config, profile, workspace)
}
fn sources<'a>(config: &'a Path, profile: &'a Path, workspace: &'a Path) -> Sources<'a> {
Sources {
config_dir: Some(config),
profile_dir: Some(profile),
workspace,
home: None,
user_file: "USER.md",
memory_file: "MEMORY.md",
}
}
fn cfg_in(home: &Path, workspace: &Path) -> crate::config::Config {
let mut cfg = crate::config::Config::default();
cfg.tools.workspace_root = Some(workspace.to_path_buf());
cfg.profile = None;
let _ = home;
cfg
}
fn home_env(home: &Path) -> impl Fn(&str) -> Option<String> + '_ {
move |key: &str| match key {
"HOME" => Some(home.display().to_string()),
_ => None,
}
}
#[test]
fn the_standing_blocks_reach_the_assembled_prompt_and_off_removes_them() {
use crate::prompt_blocks::Choice;
let plugins = crate::plugins::Plugins::default();
let mut cfg = crate::config::Config::default();
cfg.provider.model = "gpt-oss:120b".into();
let env: crate::config::EnvFn = &|_: &str| None;
let on = assemble("you are eclipse", &for_config(&cfg, env, &plugins), &[]);
assert!(
on.contains("you are eclipse"),
"the configured sentence survives: {on}"
);
assert!(
on.contains("## task-completion") && on.contains("## execution-guidance"),
"the gated blocks are in the prompt: {on}"
);
cfg.agent.prompt_blocks = Choice::Off;
let off = assemble("you are eclipse", &for_config(&cfg, env, &plugins), &[]);
assert_eq!(
off.trim(),
"you are eclipse",
"off leaves the sentence and nothing else"
);
}
#[test]
fn the_three_files_are_found_with_their_budgets_and_the_missing_ones_are_predicted() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path();
let workspace = home.join("work");
std::fs::create_dir_all(&workspace).unwrap();
let memory = home.join(".eclipse/memory");
write(&memory.join("USER.md"), "USER FACT: one line");
write(&memory.join("MEMORY.md"), "first fact\n§\nsecond fact");
let cfg = cfg_in(home, &workspace);
let env = home_env(home);
let rows = editable(&cfg, &env);
assert_eq!(rows.len(), 3, "{rows:#?}");
assert_eq!(
rows.iter().map(|r| r.which.id()).collect::<Vec<_>>(),
vec!["agent", "user", "memory"]
);
let agent = &rows[0];
assert!(!agent.exists);
assert_eq!(
agent.others, 0,
"the one file this row would create is the only one"
);
assert_eq!(agent.path, memory.join("AGENT.md"));
assert_eq!(agent.text, "");
assert_eq!(agent.position, None);
assert_eq!(agent.max_chars, DEFAULT_MAX_FILE_CHARS);
assert!(
agent.own_budget.is_none(),
"prose files have no budget of their own"
);
let user = &rows[1];
assert!(user.exists);
assert_eq!(user.chars, "USER FACT: one line".chars().count());
assert_eq!(user.kept, user.chars, "nothing is clipped");
assert!(!user.truncated());
let mem = &rows[2];
assert_eq!(mem.file, "MEMORY.md");
assert_eq!(mem.chars, "first fact\n§\nsecond fact".chars().count());
assert!(mem.text.contains('§'));
assert_eq!(mem.own_budget, Some(crate::memory::DEFAULT_BUDGET_CHARS));
assert_eq!(user.position, Some(1));
assert_eq!(mem.position, Some(2));
}
#[test]
fn the_nearest_agent_file_is_the_one_to_edit_and_the_wider_ones_are_counted() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path();
let repo = home.join("repo");
let leaf = repo.join("crates/app");
std::fs::create_dir_all(repo.join(".git")).unwrap();
std::fs::create_dir_all(&leaf).unwrap();
write(&repo.join("AGENT.md"), "REPO RULE");
write(&leaf.join("AGENT.md"), "LEAF RULE");
write(&home.join(".eclipse/memory/AGENT.md"), "GLOBAL RULE");
let cfg = cfg_in(home, &leaf);
let env = home_env(home);
let agent = editable(&cfg, &env)
.into_iter()
.find(|r| r.which == Which::Agent)
.unwrap();
assert_eq!(
agent.path,
std::fs::canonicalize(leaf.join("AGENT.md")).unwrap()
);
assert_eq!(agent.text, "LEAF RULE");
assert_eq!(agent.others, 2);
assert_eq!(agent.position, Some(3), "global, repo, leaf");
}
#[test]
fn a_project_agent_file_that_points_outside_the_tree_is_not_offered_for_editing() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
let workspace = home.join("work");
std::fs::create_dir_all(&workspace).unwrap();
let secret = tmp.path().join("id_rsa");
write(&secret, "-----BEGIN OPENSSH PRIVATE KEY-----\n");
std::os::unix::fs::symlink(&secret, workspace.join("AGENT.md")).unwrap();
let cfg = cfg_in(&home, &workspace);
let env = home_env(&home);
let agent = editable(&cfg, &env)
.into_iter()
.find(|r| r.which == Which::Agent)
.expect("the row still exists: it promises the file a save would create");
assert!(
!agent.text.contains("PRIVATE KEY"),
"the key is not served: {:?}",
agent.text
);
assert_eq!(agent.path, home.join(".eclipse/memory/AGENT.md"));
assert!(!agent.exists);
write_file(&cfg, &env, Which::Agent, "my rules\n").unwrap();
assert_eq!(
std::fs::read_to_string(&secret).unwrap(),
"-----BEGIN OPENSSH PRIVATE KEY-----\n",
"the key was not written through"
);
assert_eq!(
std::fs::read_to_string(home.join(".eclipse/memory/AGENT.md")).unwrap(),
"my rules\n"
);
}
#[test]
fn a_project_agent_file_that_points_inside_the_tree_is_still_offered() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
let workspace = home.join("work");
std::fs::create_dir_all(&workspace).unwrap();
write(&workspace.join("docs/conventions.md"), "run make\n");
std::os::unix::fs::symlink(
workspace.join("docs/conventions.md"),
workspace.join("AGENT.md"),
)
.unwrap();
let cfg = cfg_in(&home, &workspace);
let env = home_env(&home);
let agent = editable(&cfg, &env)
.into_iter()
.find(|r| r.which == Which::Agent)
.unwrap();
assert_eq!(agent.text, "run make\n");
assert_eq!(
agent.path,
std::fs::canonicalize(workspace.join("docs/conventions.md")).unwrap()
);
}
#[test]
fn a_file_past_the_per_file_ceiling_is_reported_as_clipped() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path();
let workspace = home.join("work");
std::fs::create_dir_all(&workspace).unwrap();
let memory = home.join(".eclipse/memory");
write(&memory.join("USER.md"), &"x".repeat(200));
let mut cfg = cfg_in(home, &workspace);
cfg.agent.context_file_max_chars = 100;
let env = home_env(home);
let user = editable(&cfg, &env)
.into_iter()
.find(|r| r.which == Which::User)
.unwrap();
assert_eq!(user.chars, 200);
assert!(
user.kept < user.chars,
"the prompt keeps less than the file"
);
assert!(user.truncated());
assert_eq!(user.max_chars, 100);
}
#[test]
fn a_save_creates_the_file_it_promised_and_leaves_no_temp_behind() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path();
let workspace = home.join("work");
std::fs::create_dir_all(&workspace).unwrap();
let cfg = cfg_in(home, &workspace);
let env = home_env(home);
let row = write_file(&cfg, &env, Which::Agent, "RULE: one\n").unwrap();
assert!(
row.exists,
"the row it answers with is the file it just created"
);
assert_eq!(row.path, home.join(".eclipse/memory/AGENT.md"));
assert_eq!(std::fs::read_to_string(&row.path).unwrap(), "RULE: one\n");
let leftovers: Vec<_> = std::fs::read_dir(home.join(".eclipse/memory"))
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.contains("tmp"))
.collect();
assert!(leftovers.is_empty(), "{leftovers:?}");
let row = write_file(&cfg, &env, Which::Agent, "RULE: two\n").unwrap();
assert_eq!(row.chars, "RULE: two\n".chars().count());
assert_eq!(std::fs::read_to_string(&row.path).unwrap(), "RULE: two\n");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(&row.path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600, "a file the page created is not world-readable");
}
}
#[test]
fn a_memory_save_goes_through_the_memory_writer_and_is_refused_past_its_budget() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path();
let workspace = home.join("work");
std::fs::create_dir_all(&workspace).unwrap();
let cfg = cfg_in(home, &workspace);
let env = home_env(home);
let row = write_file(&cfg, &env, Which::Memory, "fact one\n§\nfact two\n").unwrap();
let entries = crate::memory::parse(&std::fs::read_to_string(&row.path).unwrap());
assert_eq!(entries, vec!["fact one", "fact two"], "{entries:?}");
let memory = crate::memory::Memory::new(&row.path, cfg.user.memory_budget_chars);
assert_eq!(memory.read().unwrap().len(), 2);
let mut small = cfg_in(home, &workspace);
small.user.memory_budget_chars = 20;
let err = write_file(&small, &env, Which::Memory, &"y".repeat(200)).unwrap_err();
let said = err.to_string();
assert!(said.contains("budget"), "{said}");
assert!(said.contains("remove or shorten"), "{said}");
assert_eq!(memory.read().unwrap().len(), 2);
}
#[test]
fn the_plural_agents_md_is_read_when_the_singular_is_absent() {
let tmp = tempfile::tempdir().unwrap();
let (config, profile, workspace) = three(&tmp);
write(&workspace.join("AGENTS.md"), "plural rules\n");
let ctx = gather(&sources(&config, &profile, &workspace), Budget::default());
let instructions = ctx
.instructions
.iter()
.map(|l| (l.name.as_str(), l.body.as_str()))
.collect::<Vec<_>>();
assert!(
instructions
.iter()
.any(|(name, body)| *name == "AGENTS.md" && body.contains("plural rules")),
"the alias is read and reported under its own name: {instructions:?}"
);
}
#[test]
fn the_singular_wins_over_the_alias_in_the_same_directory() {
let tmp = tempfile::tempdir().unwrap();
let (config, profile, workspace) = three(&tmp);
write(&workspace.join("AGENT.md"), "singular rules\n");
write(&workspace.join("AGENTS.md"), "plural rules\n");
let ctx = gather(&sources(&config, &profile, &workspace), Budget::default());
let names = ctx
.instructions
.iter()
.map(|l| l.name.clone())
.collect::<Vec<_>>();
let bodies = ctx
.instructions
.iter()
.map(|l| l.body.clone())
.collect::<Vec<_>>();
assert_eq!(
names.iter().filter(|n| n.ends_with(".md")).count(),
names.len()
);
assert!(
!bodies.iter().any(|b| b.contains("plural rules")),
"one file per directory, and it is the singular: {bodies:?}"
);
}
#[test]
fn the_dotted_singular_wins_over_a_plain_alias() {
let tmp = tempfile::tempdir().unwrap();
let (config, profile, workspace) = three(&tmp);
write(
&workspace.join(".eclipse").join("AGENT.md"),
"dotted rules\n",
);
write(&workspace.join("AGENTS.md"), "plural rules\n");
let ctx = gather(&sources(&config, &profile, &workspace), Budget::default());
let bodies = ctx
.instructions
.iter()
.map(|l| l.body.clone())
.collect::<Vec<_>>();
assert!(
bodies.iter().any(|b| b.contains("dotted rules")),
"{bodies:?}"
);
assert!(
!bodies.iter().any(|b| b.contains("plural rules")),
"{bodies:?}"
);
}
#[test]
fn the_config_directory_accepts_the_alias() {
let tmp = tempfile::tempdir().unwrap();
let (config, profile, workspace) = three(&tmp);
write(&config.join("AGENTS.md"), "install-wide rules\n");
let ctx = gather(&sources(&config, &profile, &workspace), Budget::default());
let bodies = ctx
.instructions
.iter()
.map(|l| l.body.clone())
.collect::<Vec<_>>();
assert!(
bodies.iter().any(|b| b.contains("install-wide rules")),
"{bodies:?}"
);
}
#[test]
fn a_blank_or_empty_file_contributes_no_section() {
let tmp = tempfile::tempdir().unwrap();
let profile = tmp.path().join("profile");
std::fs::create_dir_all(&profile).unwrap();
std::fs::write(profile.join("MEMORY.md"), "").unwrap();
std::fs::write(profile.join("USER.md"), "\n \n\t\n").unwrap();
let workspace = profile.clone();
let sources = Sources {
config_dir: Some(&profile),
profile_dir: Some(&profile),
workspace: &workspace,
home: None,
user_file: "USER.md",
memory_file: "MEMORY.md",
};
let ctx = gather(
&sources,
Budget {
max_file_chars: 6000,
total_chars: 12000,
},
);
assert!(
ctx.user.is_none(),
"a whitespace-only USER.md is not a layer"
);
assert!(ctx.memory.is_none(), "an empty MEMORY.md is not a layer");
assert!(ctx.is_empty(), "nothing to inject: {ctx:?}");
}
#[test]
fn a_project_file_is_found_from_a_subdirectory_up_to_the_repository_root() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
write(&root.join(".git/HEAD"), "ref: refs/heads/main");
write(&root.join("AGENT.md"), "repo rules");
write(&root.join("sub/deeper/AGENT.md"), "leaf rules");
let workspace = root.join("sub/deeper");
let found = project_files(&workspace, None);
let names: Vec<_> = found
.iter()
.map(|p| p.strip_prefix(root).unwrap().to_string_lossy().to_string())
.collect();
assert_eq!(
names,
["AGENT.md", "sub/deeper/AGENT.md"],
"outermost first, so the nearest file has the last word"
);
}
#[test]
fn walking_up_stops_at_the_home_boundary_instead_of_reaching_root() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
let deep = home.join("work/proj");
std::fs::create_dir_all(&deep).unwrap();
write(&home.join("AGENT.md"), "home rules");
write(&deep.join("AGENT.md"), "project rules");
let found = project_files(&deep, Some(&home));
assert_eq!(found.len(), 2, "{found:?}");
write(&tmp.path().join("AGENT.md"), "above home");
let found = project_files(&deep, Some(&home));
assert_eq!(found.len(), 2, "{found:?}");
assert!(found.iter().all(|p| p.starts_with(&home)));
let elsewhere = tmp.path().join("elsewhere/a/b/proj");
std::fs::create_dir_all(&elsewhere).unwrap();
write(
&tmp.path().join("elsewhere/AGENT.md"),
"an unrelated project",
);
write(
&tmp.path().join("elsewhere/a/AGENT.md"),
"another unrelated project",
);
write(&elsewhere.join("AGENT.md"), "project rules");
assert_eq!(
project_files(&elsewhere, Some(&home)),
[elsewhere.join("AGENT.md")],
"the workspace's own file, and nothing from the trees above it"
);
}
#[test]
fn a_dot_eclipse_file_is_used_when_there_is_no_agent_md() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
write(&root.join(".git/HEAD"), "ref: refs/heads/main");
write(&root.join(".eclipse/AGENT.md"), "hidden rules");
let found = project_files(root, None);
assert_eq!(found, [root.join(".eclipse/AGENT.md")]);
}
#[test]
fn a_plain_agent_md_wins_over_the_hidden_one() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
write(&root.join(".git/HEAD"), "ref: refs/heads/main");
write(&root.join(".eclipse/AGENT.md"), "hidden rules");
write(&root.join("AGENT.md"), "visible rules");
assert_eq!(project_files(root, None), [root.join("AGENT.md")]);
}
#[test]
fn every_file_kind_lands_in_its_layer_and_in_injection_order() {
let tmp = tempfile::tempdir().unwrap();
let config = tmp.path().join("config");
let profile = config.join("profiles/work");
let repo = tmp.path().join("repo");
write(&repo.join(".git/HEAD"), "ref: refs/heads/main");
write(&config.join("AGENT.md"), "global rules");
write(&repo.join("AGENT.md"), "repo rules");
write(&profile.join("USER.md"), "I am Max, be direct");
write(&profile.join("MEMORY.md"), "the fleet is two servers");
let workspace = repo.join("crates");
let ctx = gather(&sources(&config, &profile, &workspace), Budget::default());
assert_eq!(ctx.instructions.len(), 2);
assert!(
ctx.instructions[0].path.starts_with(&config),
"global first"
);
assert!(ctx.instructions[1].path.starts_with(&repo), "then project");
assert_eq!(ctx.user.as_ref().unwrap().body, "I am Max, be direct");
assert_eq!(
ctx.memory.as_ref().unwrap().body,
"- the fleet is two servers"
);
let prompt = assemble("You are Eclipse.", &ctx, &["plugin says hi".into()]);
let order: Vec<&str> = [
"You are Eclipse.",
"global rules",
"repo rules",
"plugin says hi",
"I am Max, be direct",
"the fleet is two servers",
]
.to_vec();
let mut at = 0;
for needle in order {
let found = prompt[at..]
.find(needle)
.unwrap_or_else(|| panic!("{needle:?} missing or out of order in:\n{prompt}"));
at += found;
}
assert!(prompt.contains("## AGENT.md ("), "{prompt}");
assert!(prompt.contains("## USER.md ("), "{prompt}");
assert!(prompt.contains("## MEMORY.md ("), "{prompt}");
}
#[test]
fn a_long_file_keeps_its_head_and_its_tail_and_says_what_went() {
let tmp = tempfile::tempdir().unwrap();
let config = tmp.path().join("config");
let profile = config.join("profiles/default");
let workspace = tmp.path().join("ws");
std::fs::create_dir_all(&workspace).unwrap();
let body = format!("HEAD{}{}TAIL", "x".repeat(500), "y".repeat(500));
write(&profile.join("USER.md"), &body);
let budget = Budget {
max_file_chars: 200,
total_chars: 10_000,
};
let ctx = gather(&sources(&config, &profile, &workspace), budget);
let user = ctx.user.unwrap();
assert!(user.truncated());
assert_eq!(user.original_chars, body.chars().count());
assert!(user.body.starts_with("HEAD"), "{}", user.body);
assert!(user.body.ends_with("TAIL"), "{}", user.body);
assert!(
user.body.contains("[… truncated:") && user.body.contains("chars …]"),
"the cut is visible: {}",
user.body
);
assert!(
user.chars <= 200,
"the cap includes the marker: {} chars",
user.chars
);
}
#[test]
fn the_cap_is_a_hard_cap_marker_included() {
for max in [60usize, 120, 200, 1000] {
let text = "x".repeat(5000);
let out = clip(&text, max);
assert!(
out.chars().count() <= max,
"clip({max}) produced {} chars",
out.chars().count()
);
assert!(out.contains("[… truncated:"), "{out}");
}
assert_eq!(clip("short", 100), "short");
}
#[test]
fn truncation_never_splits_a_character() {
let text = "é".repeat(100);
let clipped = clip(&text, 80);
assert!(clipped.starts_with("éé"), "{clipped}");
assert!(clipped.ends_with('é'), "{clipped}");
assert!(clipped.chars().count() <= 80);
assert!(clipped.is_char_boundary(clipped.len()));
let cramped = clip(&text, 21);
assert!(cramped.chars().count() <= 21, "{cramped}");
assert!(cramped.contains("100"), "{cramped}");
assert!(!cramped.is_empty() && cramped.is_char_boundary(cramped.len()));
}
#[test]
fn over_the_total_the_broadest_file_goes_first_and_the_drop_is_named() {
let tmp = tempfile::tempdir().unwrap();
let config = tmp.path().join("config");
let profile = config.join("profiles/default");
let repo = tmp.path().join("repo");
write(&repo.join(".git/HEAD"), "ref: refs/heads/main");
write(&config.join("AGENT.md"), &"g".repeat(400));
write(&repo.join("AGENT.md"), &"r".repeat(400));
write(&profile.join("USER.md"), "user");
write(&profile.join("MEMORY.md"), "memory");
let budget = Budget {
max_file_chars: 6000,
total_chars: 900,
};
let ctx = gather(&sources(&config, &profile, &repo), budget);
assert_eq!(ctx.instructions.len(), 2);
assert!(ctx.notes.is_empty(), "{:?}", ctx.notes);
let budget = Budget {
max_file_chars: 6000,
total_chars: 500,
};
let ctx = gather(&sources(&config, &profile, &repo), budget);
assert_eq!(ctx.instructions.len(), 1, "the global file went first");
assert!(ctx.instructions[0].path.starts_with(&repo));
assert!(ctx.user.is_some() && ctx.memory.is_some());
assert!(
ctx.notes
.iter()
.any(|n| n.contains("dropped") && n.contains("chars")),
"{:?}",
ctx.notes
);
}
#[test]
fn a_missing_config_directory_is_not_an_error() {
let workspace = tempfile::tempdir().unwrap();
let ctx = gather(
&Sources {
config_dir: Some(Path::new("/nonexistent/eclipse")),
profile_dir: Some(Path::new("/nonexistent/eclipse/profiles/default")),
workspace: workspace.path(),
home: None,
user_file: "USER.md",
memory_file: "MEMORY.md",
},
Budget::default(),
);
assert!(ctx.is_empty());
assert_eq!(assemble("base", &ctx, &[]), "base");
}
#[test]
fn the_fragments_sit_between_the_instruction_files_and_the_user_model() {
let ctx = Context {
instructions: vec![Layer {
name: "AGENT.md".into(),
path: PathBuf::from("/r/AGENT.md"),
body: "rules".into(),
chars: 5,
original_chars: 5,
}],
user: Some(Layer {
name: "USER.md".into(),
path: PathBuf::from("/p/USER.md"),
body: "who".into(),
chars: 3,
original_chars: 3,
}),
memory: None,
skills: None,
notes: Vec::new(),
skill_notes: Vec::new(),
guidance: String::new(),
};
let prompt = assemble("base", &ctx, &["frag".into(), " ".into()]);
let prompt = prompt.replace("\n", " ");
let compact = prompt.split_whitespace().collect::<Vec<_>>().join(" ");
assert!(
compact.ends_with("rules frag ## USER.md (/p/USER.md) who"),
"{compact}"
);
assert_eq!(ctx.total_chars(), 8);
}
fn skill(dir: &Path, name: &str, description: &str) {
write(
&dir.join(name).join("SKILL.md"),
&format!("---\nname: {name}\ndescription: {description}\n---\nDo {name}.\n"),
);
}
fn env_for(home: &Path) -> impl Fn(&str) -> Option<String> {
let home = home.display().to_string();
move |key: &str| (key == "HOME").then(|| home.clone())
}
#[test]
fn the_skills_index_is_the_last_labelled_layer_after_memory() {
let tmp = tempfile::tempdir().unwrap();
let (config, profile, workspace) = (
tmp.path().join("c"),
tmp.path().join("p"),
tmp.path().join("w"),
);
write(&config.join("AGENT.md"), "RULES");
write(&profile.join("USER.md"), "WHO");
write(&profile.join("MEMORY.md"), "a fact");
skill(&config.join("skills"), "backup", "back things up");
let report = crate::skills::discover(&[crate::skills::Root {
source: crate::skills::Source::Shared,
dir: config.join("skills"),
}]);
let ctx = gather(&sources(&config, &profile, &workspace), Budget::default())
.with_skills(&report, 4000);
let prompt = assemble("base", &ctx, &[]);
let at = |needle: &str| {
prompt
.find(needle)
.unwrap_or_else(|| panic!("{needle}: {prompt}"))
};
assert!(at("a fact") < at("## Skills"), "after MEMORY.md: {prompt}");
assert!(prompt.contains("- backup: back things up"), "{prompt}");
assert!(
!prompt.contains("Do backup."),
"the body is loaded on demand: {prompt}"
);
assert!(prompt.trim_end().ends_with("back things up"), "{prompt}");
assert!(!ctx.is_empty());
assert_eq!(
ctx.total_chars(),
"RULES".len() + "WHO".len() + "- a fact".len()
);
}
#[test]
fn the_config_reaches_the_shared_profile_and_workspace_skills_and_the_budget() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path();
let config = home.join(".eclipse");
let workspace = home.join("ws");
skill(&config.join("skills"), "backup", "the shared one");
skill(&config.join("skills"), "other", "shared only");
skill(
&config.join("profiles/work/skills"),
"backup",
"the profile one",
);
skill(&workspace.join(".eclipse/skills"), "deploy", "this project");
let mut cfg = crate::config::Config {
profile: Some("work".into()),
..Default::default()
};
cfg.tools.workspace_root = Some(workspace.clone());
let env = env_for(home);
let plugins = crate::plugins::Plugins::default();
let ctx = for_config(&cfg, &env, &plugins);
let index = ctx.skills.as_ref().unwrap();
assert!(index.body.contains("the profile one"), "{}", index.body);
assert!(
!index.body.contains("the shared one"),
"the profile shadows it"
);
assert!(index.body.contains("- deploy: this project"));
assert!(index.body.contains("- other: shared only"));
assert!(ctx.skill_notes.is_empty(), "{:?}", ctx.skill_notes);
cfg.skills.index_budget_chars = index.chars - 10;
let ctx = for_config(&cfg, &env, &plugins);
assert_eq!(ctx.skills.as_ref().unwrap().names.len(), 2);
assert!(
ctx.skill_notes
.iter()
.any(|n| n.contains("left out 1 of 3")),
"{:?}",
ctx.skill_notes
);
}
fn under_home<'a>(
config: &'a Path,
profile: &'a Path,
workspace: &'a Path,
home: &'a Path,
) -> Sources<'a> {
Sources {
config_dir: Some(config),
profile_dir: Some(profile),
workspace,
home: Some(home),
user_file: "USER.md",
memory_file: "MEMORY.md",
}
}
#[test]
fn a_project_file_that_points_outside_the_tree_is_not_read() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
let workspace = home.join("work");
std::fs::create_dir_all(&workspace).unwrap();
let config = tmp.path().join("config");
let profile = tmp.path().join("profile");
let secret = tmp.path().join("id_rsa");
write(&secret, "-----BEGIN OPENSSH PRIVATE KEY-----\n");
std::os::unix::fs::symlink(&secret, workspace.join("AGENTS.md")).unwrap();
let ctx = gather(
&under_home(&config, &profile, &workspace, &home),
Budget::default(),
);
assert!(
ctx.instructions.is_empty(),
"nothing from the link: {:?}",
ctx.instructions
);
assert!(
ctx.notes
.iter()
.any(|n| n.contains("points outside the project")),
"{:?}",
ctx.notes
);
}
#[test]
fn a_project_file_that_points_inside_the_tree_is_still_read() {
let tmp = tempfile::tempdir().unwrap();
let (config, profile, workspace) = three(&tmp);
write(
&workspace.join("docs/conventions.md"),
"run make, never cargo test\n",
);
std::os::unix::fs::symlink(
workspace.join("docs/conventions.md"),
workspace.join("AGENTS.md"),
)
.unwrap();
let ctx = gather(
&under_home(&config, &profile, &workspace, tmp.path()),
Budget::default(),
);
assert_eq!(ctx.instructions.len(), 1, "{:?}", ctx.notes);
assert!(ctx.instructions[0].body.contains("run make"));
assert_eq!(
ctx.instructions[0].path,
std::fs::canonicalize(workspace.join("docs/conventions.md")).unwrap(),
"the label names the file that was read"
);
}
#[test]
fn the_operators_own_agent_file_may_still_be_a_symlink() {
let tmp = tempfile::tempdir().unwrap();
let (config, profile, workspace) = three(&tmp);
let shared = tmp.path().join("dotfiles/AGENT.md");
write(&shared, "my rules, kept outside any project\n");
std::fs::create_dir_all(&config).unwrap();
std::os::unix::fs::symlink(&shared, config.join("AGENT.md")).unwrap();
let ctx = gather(
&under_home(&config, &profile, &workspace, tmp.path()),
Budget::default(),
);
assert_eq!(ctx.instructions.len(), 1, "{:?}", ctx.notes);
assert!(ctx.instructions[0].body.contains("my rules"));
}
#[test]
fn a_context_file_that_is_not_a_regular_file_is_refused() {
let tmp = tempfile::tempdir().unwrap();
let (config, profile, workspace) = three(&tmp);
std::fs::create_dir_all(&profile).unwrap();
let fifo = profile.join("USER.md");
let made = std::process::Command::new("mkfifo").arg(&fifo).status();
assert!(
matches!(made, Ok(s) if s.success()),
"mkfifo is how this test makes the case: {made:?}"
);
let ctx = gather(
&under_home(&config, &profile, &workspace, tmp.path()),
Budget::default(),
);
assert!(ctx.user.is_none(), "no section, and no hang");
assert!(
ctx.notes
.iter()
.any(|n| n.contains("is not a regular file")),
"{:?}",
ctx.notes
);
}
#[test]
fn an_enormous_context_file_is_read_only_to_the_cap() {
let tmp = tempfile::tempdir().unwrap();
let (config, profile, workspace) = three(&tmp);
std::fs::create_dir_all(&profile).unwrap();
let body = "a".repeat(2 * 1024 * 1024);
std::fs::write(profile.join("USER.md"), &body).unwrap();
let mut ctx = gather(
&under_home(&config, &profile, &workspace, tmp.path()),
Budget::default(),
);
let layer = ctx.user.take().expect("the head of it is still read");
assert!(layer.truncated(), "the injected body is clipped");
assert_eq!(
layer.original_chars,
(MAX_LAYER_BYTES) as usize,
"read exactly to the cap, not to the end of the file"
);
assert!(
ctx.notes
.iter()
.any(|n| n.contains("read only to that point")),
"{:?}",
ctx.notes
);
}
}