Skip to main content

mermaid_cli/app/
instructions.rs

1//! Project-instructions loader (Step 5h).
2//!
3//! On session start, walk UP from the current working directory looking
4//! for repo instruction files. Stop at the git root (any directory
5//! containing a `.git` entry) or at `$HOME`, whichever is reached first.
6//! Load every supported file in the nearest matching directory; cap the
7//! combined body at `MAX_INSTRUCTIONS_BYTES`; pass the content to the
8//! model as a dynamic suffix on the system prompt.
9//!
10//! Auto-reload: before every model call, `refresh()` stats the loaded
11//! file's path and compares mtime. If the mtime moved, re-read; if the
12//! file is gone, drop the instructions. One stat per turn is
13//! microseconds — no need for a filesystem watcher.
14
15use std::path::{Path, PathBuf};
16use std::time::{SystemTime, UNIX_EPOCH};
17
18use crate::constants::{INSTRUCTIONS_TRUNCATION_MARKER, MAX_INSTRUCTIONS_BYTES};
19
20/// Instruction files Mermaid understands, in load order. `AGENTS.md` (the
21/// cross-tool open standard) is read first; `MERMAID.md` (mermaid-specific) is
22/// read last so its guidance overrides `AGENTS.md` on conflict. These are the
23/// only two recognized — there is intentionally no CLAUDE.md/GEMINI.md support.
24pub const INSTRUCTION_FILENAMES: &[&str] = &["AGENTS.md", "MERMAID.md"];
25
26/// Hard cap on how many directory levels `find_instruction_files` walks up
27/// before giving up. Guards against pathological symlink loops.
28const MAX_WALK_DEPTH: usize = 32;
29
30/// One loaded instruction file inside a combined project-instructions
31/// snapshot.
32#[derive(Debug, Clone)]
33pub struct InstructionSource {
34    pub path: PathBuf,
35    pub mtime: SystemTime,
36    pub byte_len: usize,
37}
38
39/// One-shot snapshot of loaded project instructions. Stored on `App` and
40/// `NonInteractiveRunner` so the per-turn auto-reload check has
41/// something to compare against.
42#[derive(Debug, Clone)]
43pub struct LoadedInstructions {
44    /// Primary absolute path the content was read from. Kept for
45    /// compatibility with older renderer/status code; `sources`
46    /// carries the full set.
47    pub path: PathBuf,
48    /// File body, possibly truncated. The truncation marker is
49    /// appended in-place so the model sees the elision.
50    pub content: String,
51    /// mtime at last read — compared against the next `stat()` to
52    /// decide whether to re-read.
53    pub mtime: SystemTime,
54    /// Original file size on disk (before any truncation).
55    pub byte_len: usize,
56    /// True when the file was larger than `MAX_INSTRUCTIONS_BYTES`
57    /// and the content was clipped + marker appended.
58    pub truncated: bool,
59    /// All files that contributed to `content`.
60    pub sources: Vec<InstructionSource>,
61}
62
63impl LoadedInstructions {
64    /// Approximate token count for status messages. ~4 chars/token is
65    /// the rule of thumb that's correct enough for user-facing display.
66    pub fn approx_tokens(&self) -> usize {
67        self.content.len() / 4
68    }
69}
70
71/// Outcome of a `refresh()` call. Used to decide whether to emit a
72/// status line so the user knows their context shifted.
73#[derive(Debug, PartialEq, Eq)]
74pub enum ReloadOutcome {
75    /// File still has the same mtime (or was/still is absent).
76    Unchanged,
77    /// File was loaded for the first time this session — handles "user
78    /// created MERMAID.md mid-session" gracefully.
79    LoadedFirst { tokens: usize },
80    /// File content changed since the last read.
81    Reloaded {
82        old_tokens: usize,
83        new_tokens: usize,
84    },
85    /// File was previously loaded but has been deleted from disk.
86    Removed,
87}
88
89/// Walk UP from `start` looking for any supported instruction file.
90/// Stops at the first of:
91/// - a directory containing `.git` (the git root)
92/// - the user's home directory (`$HOME`, or `%USERPROFILE%` on Windows)
93/// - filesystem root
94/// - `MAX_WALK_DEPTH` levels (symlink-loop guard)
95///
96/// Returns all supported instruction files in the nearest matching
97/// directory, in precedence order, or an empty vec if none exist.
98pub fn find_instruction_files(start: &Path) -> Vec<PathBuf> {
99    find_instruction_files_bounded(start, home_dir_boundary().as_deref())
100}
101
102/// Resolve the user's home directory to use as the upward-walk boundary.
103///
104/// On Unix this is `$HOME`. On Windows `HOME` is usually unset — the home var is
105/// `%USERPROFILE%` (or `%HOMEDRIVE%%HOMEPATH%`) — so without consulting those the
106/// walk would have no home boundary on Windows and could climb above the user's
107/// profile, relying solely on `.git` / `MAX_WALK_DEPTH` (F63). An empty value is
108/// treated as unset.
109fn home_dir_boundary() -> Option<PathBuf> {
110    let home = std::env::var_os("HOME");
111    #[cfg(windows)]
112    let resolved = pick_home_boundary(
113        home.as_deref(),
114        std::env::var_os("USERPROFILE").as_deref(),
115        std::env::var_os("HOMEDRIVE").as_deref(),
116        std::env::var_os("HOMEPATH").as_deref(),
117    );
118    // Non-Windows: only `$HOME` bounds the walk.
119    #[cfg(not(windows))]
120    let resolved = pick_home_boundary(home.as_deref(), None, None, None);
121    resolved
122}
123
124/// Pick the home boundary from candidate env values in priority order: `HOME`,
125/// then `USERPROFILE`, then `HOMEDRIVE` + `HOMEPATH` (joined). The first present,
126/// non-empty value wins; empty values are ignored. Pure (takes its inputs rather
127/// than reading the environment) so the Windows fallback order is unit-testable
128/// without mutating process-global env (which would race other threads' tests).
129fn pick_home_boundary(
130    home: Option<&std::ffi::OsStr>,
131    userprofile: Option<&std::ffi::OsStr>,
132    homedrive: Option<&std::ffi::OsStr>,
133    homepath: Option<&std::ffi::OsStr>,
134) -> Option<PathBuf> {
135    fn nonempty(v: Option<&std::ffi::OsStr>) -> Option<&std::ffi::OsStr> {
136        v.filter(|s| !s.is_empty())
137    }
138    if let Some(home) = nonempty(home) {
139        return Some(PathBuf::from(home));
140    }
141    if let Some(profile) = nonempty(userprofile) {
142        return Some(PathBuf::from(profile));
143    }
144    if let (Some(drive), Some(path)) = (nonempty(homedrive), nonempty(homepath)) {
145        let mut combined = drive.to_os_string();
146        combined.push(path);
147        return Some(PathBuf::from(combined));
148    }
149    None
150}
151
152/// Walk implementation with the `$HOME` boundary injected, so tests can
153/// exercise the "stop at home" rule (#108) without mutating the process-global
154/// `HOME` env var (which would race other threads' tests).
155fn find_instruction_files_bounded(start: &Path, home: Option<&Path>) -> Vec<PathBuf> {
156    let mut current = start.to_path_buf();
157    for _ in 0..MAX_WALK_DEPTH {
158        // Stop at $HOME *before* searching — don't load the user's home-dir
159        // instruction files (or anything above home). Checked first so a walk
160        // that climbs into home can't pick up `~/AGENTS.md` (#108); the old
161        // order searched, found, and returned it before this guard ran.
162        if home == Some(current.as_path()) {
163            return Vec::new();
164        }
165        let found: Vec<PathBuf> = INSTRUCTION_FILENAMES
166            .iter()
167            .map(|name| current.join(name))
168            .filter(|candidate| candidate.is_file())
169            .collect();
170        if !found.is_empty() {
171            return found;
172        }
173        // Stop at the git root (the .git entry itself ends the walk; most
174        // projects vendor instruction files at the repo root). Checked *after*
175        // discovery so a file AT the git root still loads.
176        if current.join(".git").exists() {
177            return Vec::new();
178        }
179        // Move up one level. If we're at the filesystem root, stop.
180        match current.parent() {
181            Some(parent) if parent != current => current = parent.to_path_buf(),
182            _ => return Vec::new(),
183        }
184    }
185    Vec::new()
186}
187
188/// Read the file at `path`, truncate to `MAX_INSTRUCTIONS_BYTES` if
189/// oversized, and return a `LoadedInstructions`. Returns `None` if the
190/// file can't be read or doesn't exist.
191pub fn load_from_path(path: &Path) -> Option<LoadedInstructions> {
192    load_from_paths(&[path.to_path_buf()])
193}
194
195/// Read and combine the instruction files at `paths`, truncating the
196/// combined body to `MAX_INSTRUCTIONS_BYTES` if needed.
197pub fn load_from_paths(paths: &[PathBuf]) -> Option<LoadedInstructions> {
198    let mut sources = Vec::new();
199    let mut bodies = Vec::new();
200    let mut total_byte_len = 0usize;
201    let mut latest_mtime = UNIX_EPOCH;
202
203    for path in paths {
204        // Tolerate a per-file failure: if one path is missing or unreadable
205        // (e.g. MERMAID.md removed in the race between `find_instruction_files`
206        // and here), skip just that file and load the rest, rather than letting
207        // one stat/read failure drop the WHOLE multi-file set (F62). Only when
208        // EVERY file fails does the load return `None` (via `sources.first()?`).
209        let Ok(metadata) = std::fs::metadata(path) else {
210            continue;
211        };
212        let Ok(mtime) = metadata.modified() else {
213            continue;
214        };
215        let true_len = metadata.len() as usize;
216        // Bounded read: never slurp a giant MERMAID.md whole just to truncate it
217        // afterwards (#16). Read one byte past the cap so the combined-body
218        // truncation check below still detects an oversized single file; the
219        // true on-disk size comes from the stat above, so `byte_len` stays
220        // accurate rather than reflecting the capped read.
221        let Ok((bytes, _truncated)) =
222            crate::utils::read_file_capped(path, MAX_INSTRUCTIONS_BYTES.saturating_add(1))
223        else {
224            continue;
225        };
226        let raw = String::from_utf8_lossy(&bytes).into_owned();
227        total_byte_len = total_byte_len.saturating_add(true_len);
228        if mtime > latest_mtime {
229            latest_mtime = mtime;
230        }
231        sources.push(InstructionSource {
232            path: path.to_path_buf(),
233            mtime,
234            byte_len: true_len,
235        });
236        bodies.push((path.to_path_buf(), raw));
237    }
238    let primary = sources.first()?.path.clone();
239    let sections = label_instruction_bodies(bodies);
240    let byte_len = total_byte_len;
241    let (content, truncated) = combine_and_cap_sections(sections, MAX_INSTRUCTIONS_BYTES);
242    Some(LoadedInstructions {
243        path: primary,
244        content,
245        mtime: latest_mtime,
246        byte_len,
247        truncated,
248        sources,
249    })
250}
251
252/// Per-turn auto-reload check. Compares the previously-loaded mtime to
253/// the current mtime on disk; reloads only when they differ. The hot
254/// path (file unchanged) is one `stat()` syscall — no I/O.
255///
256/// `cwd` is used to re-discover MERMAID.md when `current` is `None`
257/// (handles "user created the file mid-session" by re-running the walk).
258pub fn refresh(
259    current: Option<LoadedInstructions>,
260    cwd: &Path,
261) -> (Option<LoadedInstructions>, ReloadOutcome) {
262    match current {
263        Some(prior) => {
264            // Stat the previously-loaded path to detect edits or removal.
265            let paths: Vec<PathBuf> = if prior.sources.is_empty() {
266                vec![prior.path.clone()]
267            } else {
268                prior
269                    .sources
270                    .iter()
271                    .map(|source| source.path.clone())
272                    .collect()
273            };
274            let changed = if prior.sources.is_empty() {
275                std::fs::metadata(&prior.path)
276                    .and_then(|m| m.modified())
277                    .map(|mtime| mtime != prior.mtime)
278                    .unwrap_or(true)
279            } else {
280                prior.sources.iter().any(|source| {
281                    std::fs::metadata(&source.path)
282                        .and_then(|m| m.modified())
283                        .map(|mtime| mtime != source.mtime)
284                        .unwrap_or(true)
285                })
286            };
287            if !changed {
288                return (Some(prior), ReloadOutcome::Unchanged);
289            }
290            let old_tokens = prior.approx_tokens();
291            match load_from_paths(&paths) {
292                Some(reloaded) => {
293                    let new_tokens = reloaded.approx_tokens();
294                    (
295                        Some(reloaded),
296                        ReloadOutcome::Reloaded {
297                            old_tokens,
298                            new_tokens,
299                        },
300                    )
301                },
302                None => {
303                    // mtime moved but read failed (race or permission)
304                    // — treat as removed for safety.
305                    (None, ReloadOutcome::Removed)
306                },
307            }
308        },
309        None => {
310            // No prior load — re-walk in case the user created
311            // instruction files after session start.
312            match load_from_paths(&find_instruction_files(cwd)) {
313                Some(loaded) => {
314                    let tokens = loaded.approx_tokens();
315                    (Some(loaded), ReloadOutcome::LoadedFirst { tokens })
316                },
317                None => (None, ReloadOutcome::Unchanged),
318            }
319        },
320    }
321}
322
323/// Separator inserted between labeled instruction sections in the combined body.
324const INSTRUCTION_SECTION_SEPARATOR: &str = "\n\n---\n\n";
325
326/// Wrap each `(path, body)` in a labeled header — even a single file — so the
327/// content lands in the system prompt as clearly-bounded project data rather
328/// than blending into trusted system authority (#109). Returns the labeled
329/// sections in load order: lowest precedence first, highest precedence LAST (so
330/// `MERMAID.md` lands after `AGENTS.md`).
331fn label_instruction_bodies(bodies: Vec<(PathBuf, String)>) -> Vec<String> {
332    bodies
333        .into_iter()
334        .map(|(path, body)| {
335            let name = path
336                .file_name()
337                .and_then(|name| name.to_str())
338                .unwrap_or("instructions");
339            format!("# Project Instructions: {}\n\n{}", name, body)
340        })
341        .collect()
342}
343
344/// Join labeled `sections` into one body capped at `cap` bytes while PRESERVING
345/// the documented "MERMAID.md wins on conflict" contract under the cap (F61).
346///
347/// `sections` is in precedence order, **highest precedence last**. When the
348/// combined body fits, it is returned whole. When it overflows, the
349/// highest-precedence (last) section — `MERMAID.md` — is protected: the
350/// lower-precedence prefix (`AGENTS.md`) is head-truncated to fit, with the
351/// truncation marker at the elision point, so the winner survives intact and
352/// last (so it still overrides on conflict). Only when the winner *alone*
353/// overflows the cap is the winner itself head-clipped (lower-precedence
354/// sections dropped). The old code joined `[AGENTS, MERMAID]` then kept the
355/// HEAD, so a ≥ 40 KB AGENTS.md silently dropped the entire MERMAID.md tail —
356/// letting the lower-priority file win.
357///
358/// Truncation always lands on a UTF-8 char boundary (`floor_char_boundary`,
359/// stabilized in Rust 1.91.0 — matches the crate MSRV in `Cargo.toml`), and the
360/// result never exceeds `cap + INSTRUCTIONS_TRUNCATION_MARKER.len()` bytes.
361fn combine_and_cap_sections(sections: Vec<String>, cap: usize) -> (String, bool) {
362    const SEP: &str = INSTRUCTION_SECTION_SEPARATOR;
363    let marker = INSTRUCTIONS_TRUNCATION_MARKER;
364
365    let full = sections.join(SEP);
366    if full.len() <= cap {
367        return (full, false);
368    }
369    // Over cap. The winner (highest precedence = MERMAID.md) is the last section
370    // and must never be the file that's silently dropped.
371    let Some(winner) = sections.last() else {
372        return (String::new(), false);
373    };
374    // Even the winner alone exceeds the cap: there's no room for any
375    // lower-precedence content. Drop the rest and head-clip the winner — it
376    // still wins, merely truncated.
377    if winner.len() >= cap {
378        let cut = winner.floor_char_boundary(cap);
379        let mut clipped = winner[..cut].to_string();
380        clipped.push_str(marker);
381        return (clipped, true);
382    }
383    // The winner fits whole at the tail. Budget the remaining room for the
384    // lower-precedence prefix and head-truncate it, so the winner stays intact
385    // AND last (so it still overrides on conflict). `earlier_len >= 1` here: a
386    // lone section under the cap would have hit the fast path above.
387    let earlier_len = sections.len() - 1;
388    let earlier_full = sections[..earlier_len].join(SEP);
389    let avail = cap.saturating_sub(winner.len() + SEP.len());
390    let cut = earlier_full.floor_char_boundary(avail);
391    if cut == 0 {
392        // No lower-precedence content survives the budget: keep the winner whole
393        // (dropping the rest) with a trailing marker so the elision is visible.
394        let mut body = winner.clone();
395        body.push_str(marker);
396        return (body, true);
397    }
398    let mut body = String::with_capacity(cut + marker.len() + SEP.len() + winner.len());
399    body.push_str(&earlier_full[..cut]);
400    body.push_str(marker);
401    body.push_str(SEP);
402    body.push_str(winner.as_str());
403    (body, true)
404}
405
406#[cfg(test)]
407mod tests {
408    use super::*;
409    use std::fs;
410    use std::sync::Mutex;
411
412    /// Tests touch the filesystem; serialize them so concurrent test
413    /// runs don't see each other's temp files.
414    static FS_LOCK: Mutex<()> = Mutex::new(());
415
416    fn temp_dir(name: &str) -> PathBuf {
417        let p = std::env::temp_dir().join(format!("mermaid_instructions_test_{}", name));
418        let _ = fs::remove_dir_all(&p);
419        fs::create_dir_all(&p).expect("create temp dir");
420        p
421    }
422
423    #[test]
424    fn find_instruction_files_finds_in_cwd() {
425        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
426        let dir = temp_dir("cwd");
427        fs::write(dir.join("MERMAID.md"), "rules").unwrap();
428        let found = find_instruction_files(&dir);
429        assert_eq!(found, vec![dir.join("MERMAID.md")]);
430        let _ = fs::remove_dir_all(&dir);
431    }
432
433    #[test]
434    fn find_instruction_files_loads_both_in_precedence_order() {
435        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
436        let dir = temp_dir("both");
437        fs::write(dir.join("AGENTS.md"), "agent rules").unwrap();
438        fs::write(dir.join("MERMAID.md"), "mermaid rules").unwrap();
439        let found = find_instruction_files(&dir);
440        // AGENTS.md first, MERMAID.md last (last wins on conflict).
441        assert_eq!(found, vec![dir.join("AGENTS.md"), dir.join("MERMAID.md")]);
442        let loaded = load_from_paths(&found).expect("load combined");
443        assert!(loaded.content.contains("# Project Instructions: AGENTS.md"));
444        assert!(loaded.content.contains("agent rules"));
445        assert!(
446            loaded
447                .content
448                .contains("# Project Instructions: MERMAID.md")
449        );
450        assert!(loaded.content.contains("mermaid rules"));
451        // MERMAID.md body must appear AFTER AGENTS.md so it overrides.
452        assert!(
453            loaded.content.find("mermaid rules") > loaded.content.find("agent rules"),
454            "MERMAID.md must come last so its guidance overrides AGENTS.md"
455        );
456        assert_eq!(loaded.sources.len(), 2);
457        let _ = fs::remove_dir_all(&dir);
458    }
459
460    #[test]
461    fn find_instruction_files_walks_up_to_git_root() {
462        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
463        let root = temp_dir("walkup");
464        fs::create_dir(root.join(".git")).unwrap();
465        fs::write(root.join("MERMAID.md"), "root rules").unwrap();
466        let sub = root.join("subdir/deeper");
467        fs::create_dir_all(&sub).unwrap();
468        let found = find_instruction_files(&sub);
469        assert_eq!(found, vec![root.join("MERMAID.md")]);
470        let _ = fs::remove_dir_all(&root);
471    }
472
473    #[test]
474    fn find_instruction_files_stops_at_git_root_without_file() {
475        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
476        let root = temp_dir("git_no_md");
477        fs::create_dir(root.join(".git")).unwrap();
478        // Place a MERMAID.md ABOVE the git root — should NOT be found
479        // because the walk stops at the .git boundary.
480        let parent = root.parent().unwrap();
481        let above_md = parent.join("MERMAID.md");
482        fs::write(&above_md, "outside").unwrap();
483        let sub = root.join("subdir");
484        fs::create_dir_all(&sub).unwrap();
485        let found = find_instruction_files(&sub);
486        assert!(found.is_empty(), "walk must stop at .git boundary");
487        let _ = fs::remove_dir_all(&root);
488        let _ = fs::remove_file(&above_md);
489    }
490
491    #[test]
492    fn find_instruction_files_returns_empty_if_absent() {
493        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
494        let dir = temp_dir("absent");
495        // No instruction file anywhere. Plant a .git so the walk stops
496        // here deterministically rather than climbing the real tree.
497        fs::create_dir(dir.join(".git")).unwrap();
498        let found = find_instruction_files(&dir);
499        assert!(found.is_empty());
500        let _ = fs::remove_dir_all(&dir);
501    }
502
503    #[test]
504    fn find_instruction_files_stops_at_home_boundary() {
505        // #108: a walk that climbs into $HOME must NOT pick up the home-dir
506        // AGENTS.md. The boundary is injected (no global env mutation), so the
507        // test is race-free. Without the fix the walk would search `home`,
508        // find AGENTS.md, and return it before the home guard ever ran.
509        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
510        let home = temp_dir("home_boundary");
511        fs::write(home.join("AGENTS.md"), "home rules").unwrap();
512        let child = home.join("project");
513        fs::create_dir_all(&child).unwrap();
514        // No .git anywhere between child and home, so only the home guard can
515        // stop the climb.
516        let found = find_instruction_files_bounded(&child, Some(home.as_path()));
517        assert!(
518            found.is_empty(),
519            "walk must stop at $HOME and not load ~/AGENTS.md, got {found:?}"
520        );
521        let _ = fs::remove_dir_all(&home);
522    }
523
524    #[test]
525    fn single_file_instructions_get_labeled_header() {
526        // #109: even a single instruction file is wrapped in a labeled
527        // boundary so it reaches the system prompt as clearly-bounded project
528        // data, not unlabeled trusted-system text.
529        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
530        let dir = temp_dir("single_header");
531        fs::write(dir.join("MERMAID.md"), "do the thing").unwrap();
532        let loaded = load_from_path(&dir.join("MERMAID.md")).expect("load");
533        assert!(
534            loaded
535                .content
536                .starts_with("# Project Instructions: MERMAID.md"),
537            "single-file instructions must carry a labeled header, got: {:?}",
538            loaded.content
539        );
540        assert!(loaded.content.contains("do the thing"));
541        let _ = fs::remove_dir_all(&dir);
542    }
543
544    #[test]
545    fn load_from_path_truncates_oversized_file() {
546        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
547        let dir = temp_dir("oversized");
548        let path = dir.join("MERMAID.md");
549        // Write 50 KB — over the 40 KB cap.
550        let big = "a".repeat(50_000);
551        fs::write(&path, &big).unwrap();
552        let loaded = load_from_path(&path).expect("load");
553        assert!(loaded.truncated);
554        assert_eq!(loaded.byte_len, 50_000); // original size preserved
555        assert!(loaded.content.ends_with(INSTRUCTIONS_TRUNCATION_MARKER));
556        // Content should be exactly cap + marker length.
557        assert_eq!(
558            loaded.content.len(),
559            MAX_INSTRUCTIONS_BYTES + INSTRUCTIONS_TRUNCATION_MARKER.len()
560        );
561        let _ = fs::remove_dir_all(&dir);
562    }
563
564    #[test]
565    fn load_from_path_returns_none_when_missing() {
566        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
567        let dir = temp_dir("missing");
568        assert!(load_from_path(&dir.join("nope.md")).is_none());
569        let _ = fs::remove_dir_all(&dir);
570    }
571
572    #[test]
573    fn refresh_returns_unchanged_when_mtime_stable() {
574        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
575        let dir = temp_dir("stable");
576        let path = dir.join("MERMAID.md");
577        fs::write(&path, "v1").unwrap();
578        let prior = load_from_path(&path).unwrap();
579        let (after, outcome) = refresh(Some(prior.clone()), &dir);
580        assert_eq!(outcome, ReloadOutcome::Unchanged);
581        assert!(after.is_some());
582        let _ = fs::remove_dir_all(&dir);
583    }
584
585    #[test]
586    fn refresh_returns_reloaded_on_content_change() {
587        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
588        let dir = temp_dir("changed");
589        let path = dir.join("MERMAID.md");
590        fs::write(&path, "v1").unwrap();
591        let prior = load_from_path(&path).unwrap();
592        // Sleep briefly to ensure mtime resolution registers a change.
593        // Most filesystems track mtime at second granularity or finer.
594        std::thread::sleep(std::time::Duration::from_millis(1100));
595        fs::write(&path, "v2 longer content here").unwrap();
596        let (after, outcome) = refresh(Some(prior), &dir);
597        assert!(matches!(outcome, ReloadOutcome::Reloaded { .. }));
598        let content = after.unwrap().content;
599        assert!(content.contains("# Project Instructions: MERMAID.md"));
600        assert!(content.contains("v2 longer content here"));
601        let _ = fs::remove_dir_all(&dir);
602    }
603
604    #[test]
605    fn refresh_returns_removed_when_file_deleted() {
606        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
607        let dir = temp_dir("removed");
608        let path = dir.join("MERMAID.md");
609        fs::write(&path, "v1").unwrap();
610        let prior = load_from_path(&path).unwrap();
611        fs::remove_file(&path).unwrap();
612        let (after, outcome) = refresh(Some(prior), &dir);
613        assert_eq!(outcome, ReloadOutcome::Removed);
614        assert!(after.is_none());
615        let _ = fs::remove_dir_all(&dir);
616    }
617
618    #[test]
619    fn refresh_returns_loaded_first_on_initial_discovery() {
620        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
621        let dir = temp_dir("first");
622        // Plant .git so the walk stays inside `dir`.
623        fs::create_dir(dir.join(".git")).unwrap();
624        // No prior load. Call refresh — should discover the new file.
625        fs::write(dir.join("MERMAID.md"), "fresh").unwrap();
626        let (after, outcome) = refresh(None, &dir);
627        assert!(matches!(outcome, ReloadOutcome::LoadedFirst { .. }));
628        let content = after.unwrap().content;
629        assert!(content.contains("# Project Instructions: MERMAID.md"));
630        assert!(content.contains("fresh"));
631        let _ = fs::remove_dir_all(&dir);
632    }
633
634    #[test]
635    fn oversized_agents_does_not_drop_mermaid_winner() {
636        // F61: when AGENTS.md alone is huge, head-truncating the COMBINED body
637        // used to drop the entire MERMAID.md tail — silently letting the
638        // lower-priority file "win". MERMAID.md must survive intact and last (so
639        // it still overrides on conflict); AGENTS.md is the file truncated.
640        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
641        let dir = temp_dir("agents_huge");
642        fs::write(dir.join("AGENTS.md"), "A".repeat(60_000)).unwrap();
643        fs::write(dir.join("MERMAID.md"), "MERMAID_WINS_SENTINEL").unwrap();
644        let loaded =
645            load_from_paths(&[dir.join("AGENTS.md"), dir.join("MERMAID.md")]).expect("load");
646        assert!(loaded.truncated, "combined body exceeds the cap");
647        assert!(
648            loaded.content.contains("MERMAID_WINS_SENTINEL"),
649            "MERMAID.md (the winner) must survive the cap, not be dropped"
650        );
651        assert!(
652            loaded
653                .content
654                .contains("# Project Instructions: MERMAID.md")
655        );
656        assert!(loaded.content.contains(INSTRUCTIONS_TRUNCATION_MARKER));
657        // The winner lands AFTER the elision marker — AGENTS.md was the file
658        // truncated, and MERMAID.md still comes last so it overrides on conflict.
659        let marker_at = loaded.content.find(INSTRUCTIONS_TRUNCATION_MARKER).unwrap();
660        let winner_at = loaded.content.find("MERMAID_WINS_SENTINEL").unwrap();
661        assert!(
662            winner_at > marker_at,
663            "MERMAID.md must come after the truncated AGENTS.md"
664        );
665        // Bounded: never more than the cap plus a single marker.
666        assert!(
667            loaded.content.len() <= MAX_INSTRUCTIONS_BYTES + INSTRUCTIONS_TRUNCATION_MARKER.len()
668        );
669        let _ = fs::remove_dir_all(&dir);
670    }
671
672    #[test]
673    fn combine_and_cap_protects_the_last_section() {
674        // Lower-precedence section is large; the small winner must survive whole
675        // and land last, with the marker at the elision point.
676        let lower = format!("# Project Instructions: AGENTS.md\n\n{}", "L".repeat(200));
677        let winner = "# Project Instructions: MERMAID.md\n\nWIN".to_string();
678        let (body, truncated) = combine_and_cap_sections(vec![lower, winner], 100);
679        assert!(truncated);
680        assert!(body.contains("WIN"), "winner survives the cap");
681        assert!(body.contains(INSTRUCTIONS_TRUNCATION_MARKER));
682        let marker_at = body.find(INSTRUCTIONS_TRUNCATION_MARKER).unwrap();
683        assert!(
684            body.find("WIN").unwrap() > marker_at,
685            "winner stays last so it overrides on conflict"
686        );
687        assert!(body.len() <= 100 + INSTRUCTIONS_TRUNCATION_MARKER.len());
688    }
689
690    #[test]
691    fn combine_and_cap_clips_winner_when_it_alone_overflows() {
692        // When even the winner exceeds the cap, it's head-clipped (not dropped)
693        // and the lower-precedence section is dropped entirely.
694        let lower = "# Project Instructions: AGENTS.md\n\nlower-content".to_string();
695        let winner = format!("# Project Instructions: MERMAID.md\n\n{}", "W".repeat(300));
696        let (body, truncated) = combine_and_cap_sections(vec![lower, winner], 100);
697        assert!(truncated);
698        assert!(body.ends_with(INSTRUCTIONS_TRUNCATION_MARKER));
699        assert_eq!(body.len(), 100 + INSTRUCTIONS_TRUNCATION_MARKER.len());
700        assert!(
701            !body.contains("lower-content"),
702            "no room for the lower-precedence section"
703        );
704    }
705
706    #[test]
707    fn combine_and_cap_passes_through_when_it_fits() {
708        let a = "# Project Instructions: AGENTS.md\n\naye".to_string();
709        let b = "# Project Instructions: MERMAID.md\n\nbee".to_string();
710        let (body, truncated) = combine_and_cap_sections(vec![a, b], 10_000);
711        assert!(!truncated);
712        assert!(body.contains("aye") && body.contains("bee"));
713        assert!(
714            body.find("bee").unwrap() > body.find("aye").unwrap(),
715            "highest-precedence section stays last"
716        );
717    }
718
719    #[test]
720    fn load_from_paths_tolerates_a_missing_file() {
721        // F62: if one path is missing (e.g. MERMAID.md removed in the race
722        // between discovery and load), the present file(s) must still load
723        // rather than the whole multi-file set returning None.
724        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
725        let dir = temp_dir("partial_load");
726        fs::write(dir.join("AGENTS.md"), "agent rules").unwrap();
727        let missing = dir.join("MERMAID.md"); // never created
728        let loaded = load_from_paths(&[dir.join("AGENTS.md"), missing])
729            .expect("AGENTS.md must still load when MERMAID.md is absent");
730        assert!(loaded.content.contains("# Project Instructions: AGENTS.md"));
731        assert!(loaded.content.contains("agent rules"));
732        assert_eq!(loaded.sources.len(), 1, "only the present file is a source");
733        assert_eq!(loaded.path, dir.join("AGENTS.md"));
734        let _ = fs::remove_dir_all(&dir);
735    }
736
737    #[test]
738    fn load_from_paths_none_when_all_missing() {
739        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
740        let dir = temp_dir("all_missing");
741        assert!(
742            load_from_paths(&[dir.join("AGENTS.md"), dir.join("MERMAID.md")]).is_none(),
743            "no present files => None"
744        );
745        let _ = fs::remove_dir_all(&dir);
746    }
747
748    #[test]
749    fn pick_home_boundary_resolves_windows_home_vars() {
750        // F63: on Windows `HOME` is usually unset; the home boundary must fall
751        // back to `%USERPROFILE%`, then `%HOMEDRIVE%%HOMEPATH%`. Exercised here
752        // with synthetic values so it's verifiable on every platform.
753        use std::ffi::OsStr;
754        // HOME wins when present.
755        assert_eq!(
756            pick_home_boundary(
757                Some(OsStr::new("/home/me")),
758                Some(OsStr::new("C:\\Users\\me")),
759                None,
760                None
761            ),
762            Some(PathBuf::from("/home/me"))
763        );
764        // No HOME => USERPROFILE (the Windows home var) bounds the walk.
765        assert_eq!(
766            pick_home_boundary(None, Some(OsStr::new("C:\\Users\\me")), None, None),
767            Some(PathBuf::from("C:\\Users\\me"))
768        );
769        // No HOME/USERPROFILE => HOMEDRIVE + HOMEPATH joined.
770        assert_eq!(
771            pick_home_boundary(
772                None,
773                None,
774                Some(OsStr::new("C:")),
775                Some(OsStr::new("\\Users\\me"))
776            ),
777            Some(PathBuf::from("C:\\Users\\me"))
778        );
779        // Empty values are ignored (not a usable boundary).
780        assert_eq!(
781            pick_home_boundary(Some(OsStr::new("")), Some(OsStr::new("")), None, None),
782            None
783        );
784        // HOMEDRIVE without HOMEPATH (and vice-versa) => no boundary.
785        assert_eq!(
786            pick_home_boundary(None, None, Some(OsStr::new("C:")), None),
787            None
788        );
789        assert_eq!(
790            pick_home_boundary(None, None, None, Some(OsStr::new("\\Users\\me"))),
791            None
792        );
793    }
794}