Skip to main content

eclipse_core/
context_files.rs

1//! Layered context files: `AGENT.md`, `USER.md`, `MEMORY.md`.
2//!
3//! Three questions, three files, three scopes:
4//!
5//! | File | Who writes it | Scope | Purpose |
6//! |---|---|---|---|
7//! | `AGENT.md` | the user | global or per project | how to work here: conventions, commands, gotchas |
8//! | `USER.md` | the user | per profile | who the operator is: preferences, environment, standing rules |
9//! | `MEMORY.md` | the agent | per profile | durable facts it learned; `§`-separated, budgeted |
10//!
11//! A fourth layer, the skills index, comes after them. It is not a file and has its own budget
12//! (`[skills] index_budget_chars`), so it neither counts against the file budget nor is dropped by
13//! it; see [`crate::skills`].
14//!
15//! Everything here is pure: paths in, labelled text out. Nothing is written by this module
16//! except through [`crate::memory`], which owns `MEMORY.md`'s budget and lock.
17
18use std::io::Read;
19use std::path::{Path, PathBuf};
20
21/// Per-file ceiling before truncation, in characters.
22pub const DEFAULT_MAX_FILE_CHARS: usize = 6000;
23/// Ceiling across all the file layers, in characters.
24pub const DEFAULT_BUDGET_CHARS: usize = 12000;
25/// Below this much room, clipping the last file would leave a stub not worth sending, so it
26/// is dropped and said so.
27const MIN_CLIP: usize = 120;
28/// Deepest directory walk when looking for a project `AGENT.md`. A guard against a
29/// pathological tree, not a real limit.
30const MAX_WALK: usize = 64;
31/// The most of a context file that is read into memory, in bytes.
32///
33/// A context file is prose, and reading one is an allocation that happens before any budget
34/// applies — the clip only caps what enters the prompt. So the read itself is capped: a
35/// `AGENTS.md` that points at a disk image or a log must not become a startup allocation (`#358`).
36const MAX_LAYER_BYTES: u64 = 1 << 20;
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub struct Budget {
40    /// Truncate a single file past this many characters.
41    pub max_file_chars: usize,
42    /// Drop whole layers past this total.
43    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/// One context file as it will be injected.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Layer {
58    /// The file's name as the model sees it: `AGENT.md`, `USER.md`, `MEMORY.md`.
59    pub name: String,
60    pub path: PathBuf,
61    /// The text to inject — possibly truncated, and then it says so.
62    pub body: String,
63    /// Characters kept.
64    pub chars: usize,
65    /// Characters the file actually has, for `context show` to compare against.
66    pub original_chars: usize,
67}
68
69impl Layer {
70    pub fn truncated(&self) -> bool {
71        self.original_chars > self.chars
72    }
73}
74
75/// Everything gathered for one run, already in injection order.
76#[derive(Debug, Clone, Default, PartialEq, Eq)]
77pub struct Context {
78    /// `AGENT.md` layers: the global one, then project ones from the outermost (repo root)
79    /// to the innermost (the workspace), so the nearest file gets the last word.
80    pub instructions: Vec<Layer>,
81    pub user: Option<Layer>,
82    pub memory: Option<Layer>,
83    /// The skills index, after `MEMORY.md`. Absent when there are no skills to list, or when
84    /// the budget leaves room for none (and then `skill_notes` says so).
85    pub skills: Option<crate::skills::Index>,
86    /// What was truncated or dropped, in plain words, for the user and for `context show`.
87    pub notes: Vec<String>,
88    /// The same for skills: what the index left out, and every skill that is broken. Kept apart
89    /// from `notes` because the CLI warns about these when it starts, and a dropped context
90    /// file is not something it has ever warned about.
91    pub skill_notes: Vec<String>,
92    /// The standing instructions that go straight after the configured prompt (`#244`), resolved
93    /// for the model in force. Empty when `[agent] prompt_blocks = "off"` or no gate matched —
94    /// which is exactly "send only the prompt and these files", the issue's own wording.
95    pub guidance: String,
96}
97
98impl Context {
99    /// Resolve the standing blocks for the model in force (`#244`).
100    ///
101    /// `[provider] model` is what a request will name, and it is read here rather than passed in
102    /// because every caller of [`for_config`] is asking the same question: what does *this*
103    /// configuration put in front of the model.
104    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    /// Every layer that survived the budget, in injection order.
110    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    /// Add the skills index for `report`, within `budget` characters (0 = no cap).
126    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
134/// Where the files may be found. Separate from [`Config`](crate::config::Config) so the
135/// discovery rules can be tested without a config file on disk.
136pub struct Sources<'a> {
137    /// The config directory: holds the global `AGENT.md`.
138    pub config_dir: Option<&'a Path>,
139    /// Where `USER.md` / `MEMORY.md` live (the profile's directory).
140    pub profile_dir: Option<&'a Path>,
141    /// Where the agent was started: the project walk begins here.
142    pub workspace: &'a Path,
143    /// Never walk above this directory.
144    pub home: Option<&'a Path>,
145    /// File names, so a profile can point at different ones.
146    pub user_file: &'a str,
147    pub memory_file: &'a str,
148}
149
150/// Gather every context file for a run.
151pub 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    // A project file is read only from inside the tree the walk covered: the same boundary
168    // `read_file` enforces, so a repository cannot use a symlink to put something else into the
169    // system prompt (`#358`). The profile's own files above and below may still be links — they
170    // are the operator's, not a clone's.
171    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
204/// The `AGENT.md` files between the workspace and its repository root (or `$HOME`),
205/// outermost first so the nearest one can override.
206///
207/// Stops *after* the directory that holds `.git` — that directory is the repo root and its
208/// file belongs to the project. Stops at `$HOME` without going above it. Both
209/// `AGENT.md` and `.eclipse/AGENT.md` count; `AGENT.md` wins when both exist.
210pub fn project_files(workspace: &Path, home: Option<&Path>) -> Vec<PathBuf> {
211    project_walk(workspace, home).0
212}
213
214/// [`project_files`], plus the directory the walk stopped at.
215///
216/// That directory is the boundary for a project layer: a symlink is followed only when its target
217/// stays inside this tree, which is the rule `read_file`'s `confine` already applies (`#358`).
218pub 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        // A repository root is the top of the project: include it, then stop.
227        if dir.join(".git").exists() {
228            break;
229        }
230        let Some(parent) = dir.parent() else { break };
231        // Never above `$HOME`. Written as `starts_with`, not `==`: a workspace that is not under
232        // `$HOME` at all (a mount, a sandbox, a sibling tree) never equals it, and equality let the
233        // walk climb to `/`, collecting the `AGENT.md` of every unrelated project on the way. The
234        // guard sits on the step *down* the tree, so a workspace outside `$HOME` still contributes
235        // its own file before the walk stops.
236        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    // `dir` is canonical by construction whenever the workspace could be resolved; resolve it
245    // again so a workspace that could not be is compared against a real path rather than a
246    // lexical one that no layer would ever live under.
247    let top = std::fs::canonicalize(&dir).unwrap_or(dir);
248    (found, top)
249}
250
251fn agent_file_in(dir: &Path) -> Option<PathBuf> {
252    // `AGENT.md` is the documented name and wins over the alias; the dotted copy wins over the
253    // plain alias, because `.eclipse/` is this program's own shelf. `AGENTS.md` is the plural most
254    // people arrive with (it is what Codex and Cursor read) and it is read as a fallback: a file
255    // that exists and is silently ignored is the worse failure of the two.
256    [
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
266/// The config directory's copy: `AGENT.md`, or `AGENTS.md` beside it. No `.eclipse/` here — the
267/// config directory *is* the shelf.
268fn 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
275/// What the prompt calls this layer: the name the file actually has, so an alias is not reported
276/// as the file it is standing in for.
277fn 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
283/// Inject `MEMORY.md` as a readable list rather than as the file it is stored in: `§` on its
284/// own line is a storage detail, and a model reading `§` between facts is a model reading
285/// noise. Multi-line entries keep their shape under a hanging indent.
286fn 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
322/// Read one context file, or say in `notes` why it was not read.
323///
324/// `boundary` is the tree a symlink's target has to stay inside. Project layers pass the top of the
325/// walk; the operator's own files (the global `AGENT.md`, `USER.md`, `MEMORY.md`) pass `None` and may
326/// point anywhere, because those are not files a cloned repository gets to write (`#358`).
327///
328/// Three refusals, all of them before anything is allocated:
329///
330/// - a target that is not a regular file — a FIFO would block startup forever, a device or a
331///   directory is not prose;
332/// - a symlink that resolves outside the boundary — `AGENTS.md -> ~/.ssh/id_rsa` in a repository
333///   would otherwise put a key in the system prompt, with no tool call for an approval, hook or
334///   redaction rule to stop;
335/// - anything past [`MAX_LAYER_BYTES`], which is read no further than the cap and said so.
336fn 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    // `metadata` follows a link; `symlink_metadata` would describe the link itself. What is wanted
345    // is "wherever this ends up, is it a file", because the check is about reading, not about links.
346    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    // `repo/sub/../../home/...` in a prompt label helps nobody: use the real path.
359    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; // an empty file contributes nothing; do not print an empty section
373    }
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
385/// The file's text, up to [`MAX_LAYER_BYTES`].
386///
387/// `take` is what bounds the allocation: the clip in [`clip`] runs on the string this returns, so
388/// without a cap the whole file is in memory before a single character is budgeted. A cut in the
389/// middle of a character is this function's own doing and is dropped; a malformed byte anywhere else
390/// means the file is not text, which is how a context file has always been refused.
391fn 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
421/// Head and tail, with a marker in the middle saying how much went. Never silent, never
422/// cutting a multi-byte character in half, and never longer than `max` **including** the
423/// marker — a cap that the marker itself pushes past is not a cap.
424fn 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    // When the cap is smaller than a sentence, say it in as few characters as possible — a
431    // stub that names the count beats a stub that says nothing.
432    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    // The marker's own length depends on the number it prints, which depends on how much is
442    // kept: one pass to guess, then a pass that is computed from the real marker.
443    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
469/// Keep the total under `total`, cheapest first.
470///
471/// The drop order is the injection order reversed: the broadest `AGENT.md` goes first, then
472/// the narrower ones, then `MEMORY.md`, then `USER.md`. The last file is **clipped to whatever
473/// is left** rather than dropped — a 9000-character `USER.md` losing its tail is recoverable,
474/// an agent that no longer knows who it is talking to is not. Nothing is dropped or cut
475/// silently: every decision lands in `notes`.
476fn 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
518/// Gather the context files and the skills index this configuration describes — the one entry
519/// point both the runtime and `eclipse context show` use, so what the CLI prints is what gets
520/// injected. `plugins` is what loaded: a plugin's own skills are part of the index.
521pub 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
529/// [`for_config`], with the skills index narrowed to `only` when it is set (`#509`).
530///
531/// The index is what a bot *sees it can ask for*; the `skill_*` tools read the same filter, so a
532/// skill that is absent from the index is also refused by name. `None` is every root's skill.
533pub 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
548/// The file layers alone, with the budget this configuration asks for — the half of
549/// [`for_config`] that reads the three files and nothing else. The dashboard's context editor
550/// (#268) uses it directly: it edits what is injected, so it has to see what is injected.
551fn gather_for(cfg: &crate::config::Config, env: crate::config::EnvFn) -> Context {
552    let workspace = cfg.workspace_root(env);
553    // AGENT.md, USER.md and MEMORY.md are one folder: `memory/`. The global one is the profile's
554    // own, which for the default profile is the root's — one rule instead of two.
555    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/// Which of the three files a request means. A fixed set, never a path: the dashboard cannot ask
577/// for a file the loader would not inject, and there is no way to spell `../../.ssh/id_rsa` here.
578#[derive(Debug, Clone, Copy, PartialEq, Eq)]
579pub enum Which {
580    /// `AGENT.md` — the file this workspace injects last, or the profile's own when it has none.
581    Agent,
582    /// `USER.md`.
583    User,
584    /// `MEMORY.md`, whose writer is [`crate::memory::Memory`].
585    Memory,
586}
587
588impl Which {
589    /// The id a request uses. Deliberately not the file name: `AGENT.md` can be `AGENTS.md` or
590    /// `.eclipse/AGENT.md` on disk, and a request that names a file is a request that can name
591    /// another one.
592    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/// One of the three files, as the dashboard's editor needs it: where it is, what is in it, what the
611/// prompt will do with it, and the budget it is measured against.
612#[derive(Debug, Clone, PartialEq, Eq)]
613pub struct Editable {
614    pub which: Which,
615    /// What the file is called on disk — `AGENT.md`, or the alias it is actually standing in for.
616    pub file: String,
617    /// The resolved path. Canonicalised when the file exists; a prediction when it does not, so the
618    /// first save has somewhere to go.
619    pub path: PathBuf,
620    pub exists: bool,
621    /// The text as stored. For `MEMORY.md` that is the `§`-separated file, not the rendered list:
622    /// the editor shows what the writer wrote.
623    pub text: String,
624    /// Characters in the file.
625    pub chars: usize,
626    /// Characters the prompt will keep — below `chars` when the file is being clipped right now.
627    pub kept: usize,
628    /// The per-file ceiling (`agent.context_file_max_chars`); 0 when there is none.
629    pub max_chars: usize,
630    /// `MEMORY.md`'s own ceiling, which its writer refuses past rather than clipping. `None` for the
631    /// two prose files, which have no such thing.
632    pub own_budget: Option<usize>,
633    /// Every file layer as it will be injected, and the ceiling for all of them together.
634    pub total: usize,
635    pub total_budget: usize,
636    /// Where this file sits in the drop order, 1-based, among the layers that survived.
637    pub position: Option<usize>,
638    /// How many *other* `AGENT.md` layers are also injected above this one.
639    pub others: usize,
640}
641
642impl Editable {
643    pub fn truncated(&self) -> bool {
644        self.kept < self.chars
645    }
646}
647
648/// The three files, resolved by the loader's own discovery, with what the prompt does with them.
649///
650/// This is the only way the dashboard learns a path: `Which` is a closed set and the discovery walks
651/// the same tree [`for_config`] walks, so the page can edit exactly what would be injected and
652/// nothing else. A file that does not exist yet is reported with where it *would* be created —
653/// `AGENT.md` in the profile's `memory/` when this workspace has none, `USER.md` and `MEMORY.md`
654/// beside it.
655pub 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    // The walk's own boundary, which is the rule `gather` confines a project layer to (`#358`) —
667    // and the editor used to skip it (`#559`). A cloned repository whose `AGENT.md` is a symlink to
668    // `~/.ssh/id_rsa` was refused by the prompt and served here in full, then written through on
669    // save. `project_walk` already answers "where did the walk stop", so this is the loader's rule
670    // and not a second one that could drift. A link that resolves inside the tree — the dotfiles
671    // shape — is still offered.
672    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    // `AGENT.md`: the nearest one this workspace injects, because it gets the last word and is
681    // therefore the one a person means. With none in the tree, the profile's own — which the first
682    // save creates, and which the prompt reads first.
683    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        // How many *other* `AGENT.md` layers ride above this one: the global file, and any wider
690        // workspace file. Not every layer — `USER.md` and `MEMORY.md` come after and are not this
691        // file's business.
692        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
776/// Write one of the three, then answer with the file as it now stands.
777///
778/// The two prose files go through [`crate::memory::write_file_atomically`] — temp in the same
779/// directory, then rename. `MEMORY.md` goes through [`crate::memory::Memory`], because that type
780/// owns its lock and its budget: a third writer with its own `fs::write` would be a writer the
781/// `memory` tool cannot see, and the lock would be theatre.
782///
783/// `text` is stored as given. For `MEMORY.md` that means the `§`-separated file the page was shown;
784/// it is parsed and re-rendered by the same functions the tool uses, so a save cannot invent a
785/// separator style of its own.
786pub 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
827/// The system prompt: the configured base, then the instruction files, then plugin prompt
828/// fragments, then the user model, then memory, then the skills index.
829///
830/// Every file layer is labelled `## <file> (<path>)` so the model can tell a project rule
831/// from a global one, and so a bad rule is traceable to the path it came from.
832pub 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    // The standing blocks (`#244`) come first, right after the configured sentence: they are how to
839    // behave, and the files after them are what to know. `off` leaves this empty and the prompt is
840    // then the sentence plus the files, which is what it was before they existed.
841    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        // No path in the label: the index is drawn from several directories, and each entry's
862        // origin is one `skill_view` away.
863        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    /// Config, profile and workspace directories under one temp dir, all present.
889    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    /// A config that points at `home`, with the workspace under it — the shape the dashboard's
911    /// editor resolves against (#268).
912    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    /// `HOME` only, so the config directory is `<home>/.eclipse` and the three files are in
921    /// `<home>/.eclipse/memory`.
922    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    /// `#244`: the blocks reach the prompt that is actually assembled — and `off` reaches it as
930    /// nothing at all, which is the issue's "send only system_prompt and these files".
931    #[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        // No environment at all: this is about the prompt, not about where the files live.
939        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        // No `AGENT.md` in the tree, so the row promises where a save would create it — beside the
981        // other two, in the profile's `memory/`, which is where the prompt reads it.
982        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        // The editor shows the file, `§` and all — it is what the writer writes.
1006        assert!(mem.text.contains('§'));
1007        assert_eq!(mem.own_budget, Some(crate::memory::DEFAULT_BUDGET_CHARS));
1008        // Both files are injected, so each has a place in the drop order and neither is a stranger.
1009        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        // The one that gets the last word, not the widest one.
1032        assert_eq!(
1033            agent.path,
1034            std::fs::canonicalize(leaf.join("AGENT.md")).unwrap()
1035        );
1036        assert_eq!(agent.text, "LEAF RULE");
1037        // ...and the page can say that two more AGENT.md layers are also injected above it.
1038        assert_eq!(agent.others, 2);
1039        assert_eq!(agent.position, Some(3), "global, repo, leaf");
1040    }
1041
1042    /// A cloned repository is untrusted input, and the editor is a second reader of the very file
1043    /// the prompt confines: `AGENT.md -> ~/.ssh/id_rsa` was refused by `gather` and served in full
1044    /// by the dashboard, which then wrote through the link on save (`#559`).
1045    #[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        // The row is the profile's own file — the one the prompt reads after refusing the project
1067        // one, and the one a save creates.
1068        assert_eq!(agent.path, home.join(".eclipse/memory/AGENT.md"));
1069        assert!(!agent.exists);
1070
1071        // ...and the save cannot reach the secret either, because the row it writes is that one.
1072        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    /// The boundary is the target's location, not "symlinks are refused": a link to a file inside
1085    /// the project is the dotfiles shape and stays editable.
1086    #[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        // The page has to be able to say this before the save, not after it.
1135        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        // Nothing half-written is left in the directory.
1155        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        // A second save replaces it, rather than appending.
1164        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        // Two entries, in the storage format the page shows.
1186        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        // ...and `eclipse memory list` sees the same thing, because it is the same type.
1190        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        // The refusal left the two entries it found alone.
1200        assert_eq!(memory.read().unwrap().len(), 2);
1201    }
1202
1203    /// `AGENTS.md` is what people type — it is the name Codex and Cursor read — and a file that
1204    /// exists while the program reads nothing is the worst failure a doc can produce. It is read
1205    /// as a fallback, under its own name in the prompt label.
1206    #[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    /// Both present: the documented name wins, so adding an alias never changes what an existing
1227    /// install reads.
1228    #[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    /// `.eclipse/` is this program's own shelf, so its singular still beats a plain alias — the
1257    /// alias is a fallback, not a new precedence rule.
1258    #[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    /// The config directory takes the alias too — that is the copy a fresh install writes.
1285    #[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        // A seeded-but-unedited MEMORY.md: empty, and no section should be printed for it.
1309        std::fs::write(profile.join("MEMORY.md"), "").unwrap();
1310        // A blank USER.md: whitespace-only counts as empty too.
1311        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        // ...and nothing above $HOME was picked up (a file there is ignored).
1369        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        // A directory that is not under `home` at all: the walk must stop there. Comparing for
1374        // equality with `home` never fires in that case, and the loop used to climb to `/`,
1375        // collecting the `AGENT.md` of every unrelated project above the workspace.
1376        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        // Memory is injected as a list: `§` is how the file stores entries, not how a model
1436        // should have to read them.
1437        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        // ...and every file layer is labelled with its own path.
1460        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        // Short text is untouched.
1510        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        // Below the size of the marker itself there is nothing honest to keep: say so rather
1523        // than silently handing back the whole file or half a character.
1524        // With a cap smaller than the marker, the count is said in as few characters as
1525        // possible — but it is still said.
1526        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        // 400 + 400 + 4 + 6 = 810, under the cap: nothing dropped.
1550        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    // -- what a workspace may hand the prompt (`#358`) --------------------------------------------
1719
1720    /// `sources` with a `$HOME`, so the walk has the boundary a real run has.
1721    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    /// A repository is untrusted input. `AGENTS.md -> ../id_rsa` used to put the target's text into
1738    /// the system prompt with no tool call — and so no approval, hook or redaction rule — in the way.
1739    #[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        // The key lives outside `$HOME`, so it is outside the tree the walk covered.
1748        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    /// The rule is the target's location, not "symlinks are refused": a link to a file in the same
1771    /// project is the shape a dotfiles checkout has, and it keeps working.
1772    #[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    /// The operator's own files are not a clone's: the global `AGENT.md` may be a link wherever the
1800    /// person keeps it.
1801    #[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    /// A FIFO would block the read forever: `AGENT.md` selection already rejects one, but `USER.md`
1819    /// and `MEMORY.md` are opened by name, so the reader is where that has to be decided.
1820    #[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    /// The clip bounds what is injected; it never bounded what was read. A context file that is
1847    /// gigabytes is not prose, so the read itself stops at the cap and says so (`#358`).
1848    #[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        // Two megapixels of 'a', so the cap lands in the middle of the second half.
1854        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}