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, serde::Serialize, serde::Deserialize)]
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, serde::Serialize, serde::Deserialize)]
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/// Load project instructions + the durable memory index for a one-shot,
324/// watcher-less run (`mermaid run` and subagents). The interactive TUI gets
325/// these from the config watcher's first poll; the headless and subagent
326/// drivers have no watcher, so they must load synchronously before the first
327/// model call — otherwise the request goes out with no MERMAID.md/AGENTS.md and
328/// no memory index, which is exactly the context `mermaid doctor` reports as
329/// loaded.
330pub fn load_project_context(
331    cwd: &Path,
332    mem_cfg: &crate::app::MemoryConfig,
333) -> (
334    Option<LoadedInstructions>,
335    Option<crate::app::memory::LoadedMemory>,
336) {
337    let (instructions, _) = refresh(None, cwd);
338    let (memory, _) = crate::app::memory::refresh(None, cwd, mem_cfg);
339    (instructions, memory)
340}
341
342/// Separator inserted between labeled instruction sections in the combined body.
343const INSTRUCTION_SECTION_SEPARATOR: &str = "\n\n---\n\n";
344
345/// Wrap each `(path, body)` in a labeled header — even a single file — so the
346/// content lands in the system prompt as clearly-bounded project data rather
347/// than blending into trusted system authority (#109). Returns the labeled
348/// sections in load order: lowest precedence first, highest precedence LAST (so
349/// `MERMAID.md` lands after `AGENTS.md`).
350fn label_instruction_bodies(bodies: Vec<(PathBuf, String)>) -> Vec<String> {
351    bodies
352        .into_iter()
353        .map(|(path, body)| {
354            let name = path
355                .file_name()
356                .and_then(|name| name.to_str())
357                .unwrap_or("instructions");
358            format!("# Project Instructions: {}\n\n{}", name, body)
359        })
360        .collect()
361}
362
363/// Join labeled `sections` into one body capped at `cap` bytes while PRESERVING
364/// the documented "MERMAID.md wins on conflict" contract under the cap (F61).
365///
366/// `sections` is in precedence order, **highest precedence last**. When the
367/// combined body fits, it is returned whole. When it overflows, the
368/// highest-precedence (last) section — `MERMAID.md` — is protected: the
369/// lower-precedence prefix (`AGENTS.md`) is head-truncated to fit, with the
370/// truncation marker at the elision point, so the winner survives intact and
371/// last (so it still overrides on conflict). Only when the winner *alone*
372/// overflows the cap is the winner itself head-clipped (lower-precedence
373/// sections dropped). The old code joined `[AGENTS, MERMAID]` then kept the
374/// HEAD, so a ≥ 40 KB AGENTS.md silently dropped the entire MERMAID.md tail —
375/// letting the lower-priority file win.
376///
377/// Truncation always lands on a UTF-8 char boundary (`floor_char_boundary`,
378/// stabilized in Rust 1.91.0 — matches the crate MSRV in `Cargo.toml`), and the
379/// result never exceeds `cap + INSTRUCTIONS_TRUNCATION_MARKER.len()` bytes.
380fn combine_and_cap_sections(sections: Vec<String>, cap: usize) -> (String, bool) {
381    const SEP: &str = INSTRUCTION_SECTION_SEPARATOR;
382    let marker = INSTRUCTIONS_TRUNCATION_MARKER;
383
384    let full = sections.join(SEP);
385    if full.len() <= cap {
386        return (full, false);
387    }
388    // Over cap. The winner (highest precedence = MERMAID.md) is the last section
389    // and must never be the file that's silently dropped.
390    let Some(winner) = sections.last() else {
391        return (String::new(), false);
392    };
393    // Even the winner alone exceeds the cap: there's no room for any
394    // lower-precedence content. Drop the rest and head-clip the winner — it
395    // still wins, merely truncated.
396    if winner.len() >= cap {
397        let cut = winner.floor_char_boundary(cap);
398        let mut clipped = winner[..cut].to_string();
399        clipped.push_str(marker);
400        return (clipped, true);
401    }
402    // The winner fits whole at the tail. Budget the remaining room for the
403    // lower-precedence prefix and head-truncate it, so the winner stays intact
404    // AND last (so it still overrides on conflict). `earlier_len >= 1` here: a
405    // lone section under the cap would have hit the fast path above.
406    let earlier_len = sections.len() - 1;
407    let earlier_full = sections[..earlier_len].join(SEP);
408    let avail = cap.saturating_sub(winner.len() + SEP.len());
409    let cut = earlier_full.floor_char_boundary(avail);
410    if cut == 0 {
411        // No lower-precedence content survives the budget: keep the winner whole
412        // (dropping the rest) with a trailing marker so the elision is visible.
413        let mut body = winner.clone();
414        body.push_str(marker);
415        return (body, true);
416    }
417    let mut body = String::with_capacity(cut + marker.len() + SEP.len() + winner.len());
418    body.push_str(&earlier_full[..cut]);
419    body.push_str(marker);
420    body.push_str(SEP);
421    body.push_str(winner.as_str());
422    (body, true)
423}
424
425#[cfg(test)]
426mod tests {
427    use super::*;
428    use std::fs;
429    use std::sync::Mutex;
430
431    /// Tests touch the filesystem; serialize them so concurrent test
432    /// runs don't see each other's temp files.
433    static FS_LOCK: Mutex<()> = Mutex::new(());
434
435    fn temp_dir(name: &str) -> PathBuf {
436        let p = std::env::temp_dir().join(format!("mermaid_instructions_test_{}", name));
437        let _ = fs::remove_dir_all(&p);
438        fs::create_dir_all(&p).expect("create temp dir");
439        p
440    }
441
442    #[test]
443    fn find_instruction_files_finds_in_cwd() {
444        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
445        let dir = temp_dir("cwd");
446        fs::write(dir.join("MERMAID.md"), "rules").unwrap();
447        let found = find_instruction_files(&dir);
448        assert_eq!(found, vec![dir.join("MERMAID.md")]);
449        let _ = fs::remove_dir_all(&dir);
450    }
451
452    #[test]
453    fn find_instruction_files_loads_both_in_precedence_order() {
454        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
455        let dir = temp_dir("both");
456        fs::write(dir.join("AGENTS.md"), "agent rules").unwrap();
457        fs::write(dir.join("MERMAID.md"), "mermaid rules").unwrap();
458        let found = find_instruction_files(&dir);
459        // AGENTS.md first, MERMAID.md last (last wins on conflict).
460        assert_eq!(found, vec![dir.join("AGENTS.md"), dir.join("MERMAID.md")]);
461        let loaded = load_from_paths(&found).expect("load combined");
462        assert!(loaded.content.contains("# Project Instructions: AGENTS.md"));
463        assert!(loaded.content.contains("agent rules"));
464        assert!(
465            loaded
466                .content
467                .contains("# Project Instructions: MERMAID.md")
468        );
469        assert!(loaded.content.contains("mermaid rules"));
470        // MERMAID.md body must appear AFTER AGENTS.md so it overrides.
471        assert!(
472            loaded.content.find("mermaid rules") > loaded.content.find("agent rules"),
473            "MERMAID.md must come last so its guidance overrides AGENTS.md"
474        );
475        assert_eq!(loaded.sources.len(), 2);
476        let _ = fs::remove_dir_all(&dir);
477    }
478
479    #[test]
480    fn find_instruction_files_walks_up_to_git_root() {
481        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
482        let root = temp_dir("walkup");
483        fs::create_dir(root.join(".git")).unwrap();
484        fs::write(root.join("MERMAID.md"), "root rules").unwrap();
485        let sub = root.join("subdir/deeper");
486        fs::create_dir_all(&sub).unwrap();
487        let found = find_instruction_files(&sub);
488        assert_eq!(found, vec![root.join("MERMAID.md")]);
489        let _ = fs::remove_dir_all(&root);
490    }
491
492    #[test]
493    fn find_instruction_files_stops_at_git_root_without_file() {
494        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
495        let root = temp_dir("git_no_md");
496        fs::create_dir(root.join(".git")).unwrap();
497        // Place a MERMAID.md ABOVE the git root — should NOT be found
498        // because the walk stops at the .git boundary.
499        let parent = root.parent().unwrap();
500        let above_md = parent.join("MERMAID.md");
501        fs::write(&above_md, "outside").unwrap();
502        let sub = root.join("subdir");
503        fs::create_dir_all(&sub).unwrap();
504        let found = find_instruction_files(&sub);
505        assert!(found.is_empty(), "walk must stop at .git boundary");
506        let _ = fs::remove_dir_all(&root);
507        let _ = fs::remove_file(&above_md);
508    }
509
510    #[test]
511    fn find_instruction_files_returns_empty_if_absent() {
512        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
513        let dir = temp_dir("absent");
514        // No instruction file anywhere. Plant a .git so the walk stops
515        // here deterministically rather than climbing the real tree.
516        fs::create_dir(dir.join(".git")).unwrap();
517        let found = find_instruction_files(&dir);
518        assert!(found.is_empty());
519        let _ = fs::remove_dir_all(&dir);
520    }
521
522    #[test]
523    fn find_instruction_files_stops_at_home_boundary() {
524        // #108: a walk that climbs into $HOME must NOT pick up the home-dir
525        // AGENTS.md. The boundary is injected (no global env mutation), so the
526        // test is race-free. Without the fix the walk would search `home`,
527        // find AGENTS.md, and return it before the home guard ever ran.
528        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
529        let home = temp_dir("home_boundary");
530        fs::write(home.join("AGENTS.md"), "home rules").unwrap();
531        let child = home.join("project");
532        fs::create_dir_all(&child).unwrap();
533        // No .git anywhere between child and home, so only the home guard can
534        // stop the climb.
535        let found = find_instruction_files_bounded(&child, Some(home.as_path()));
536        assert!(
537            found.is_empty(),
538            "walk must stop at $HOME and not load ~/AGENTS.md, got {found:?}"
539        );
540        let _ = fs::remove_dir_all(&home);
541    }
542
543    #[test]
544    fn single_file_instructions_get_labeled_header() {
545        // #109: even a single instruction file is wrapped in a labeled
546        // boundary so it reaches the system prompt as clearly-bounded project
547        // data, not unlabeled trusted-system text.
548        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
549        let dir = temp_dir("single_header");
550        fs::write(dir.join("MERMAID.md"), "do the thing").unwrap();
551        let loaded = load_from_path(&dir.join("MERMAID.md")).expect("load");
552        assert!(
553            loaded
554                .content
555                .starts_with("# Project Instructions: MERMAID.md"),
556            "single-file instructions must carry a labeled header, got: {:?}",
557            loaded.content
558        );
559        assert!(loaded.content.contains("do the thing"));
560        let _ = fs::remove_dir_all(&dir);
561    }
562
563    #[test]
564    fn load_from_path_truncates_oversized_file() {
565        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
566        let dir = temp_dir("oversized");
567        let path = dir.join("MERMAID.md");
568        // Write 50 KB — over the 40 KB cap.
569        let big = "a".repeat(50_000);
570        fs::write(&path, &big).unwrap();
571        let loaded = load_from_path(&path).expect("load");
572        assert!(loaded.truncated);
573        assert_eq!(loaded.byte_len, 50_000); // original size preserved
574        assert!(loaded.content.ends_with(INSTRUCTIONS_TRUNCATION_MARKER));
575        // Content should be exactly cap + marker length.
576        assert_eq!(
577            loaded.content.len(),
578            MAX_INSTRUCTIONS_BYTES + INSTRUCTIONS_TRUNCATION_MARKER.len()
579        );
580        let _ = fs::remove_dir_all(&dir);
581    }
582
583    #[test]
584    fn load_from_path_returns_none_when_missing() {
585        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
586        let dir = temp_dir("missing");
587        assert!(load_from_path(&dir.join("nope.md")).is_none());
588        let _ = fs::remove_dir_all(&dir);
589    }
590
591    #[test]
592    fn refresh_returns_unchanged_when_mtime_stable() {
593        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
594        let dir = temp_dir("stable");
595        let path = dir.join("MERMAID.md");
596        fs::write(&path, "v1").unwrap();
597        let prior = load_from_path(&path).unwrap();
598        let (after, outcome) = refresh(Some(prior.clone()), &dir);
599        assert_eq!(outcome, ReloadOutcome::Unchanged);
600        assert!(after.is_some());
601        let _ = fs::remove_dir_all(&dir);
602    }
603
604    #[test]
605    fn refresh_returns_reloaded_on_content_change() {
606        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
607        let dir = temp_dir("changed");
608        let path = dir.join("MERMAID.md");
609        fs::write(&path, "v1").unwrap();
610        let prior = load_from_path(&path).unwrap();
611        // Sleep briefly to ensure mtime resolution registers a change.
612        // Most filesystems track mtime at second granularity or finer.
613        std::thread::sleep(std::time::Duration::from_millis(1100));
614        fs::write(&path, "v2 longer content here").unwrap();
615        let (after, outcome) = refresh(Some(prior), &dir);
616        assert!(matches!(outcome, ReloadOutcome::Reloaded { .. }));
617        let content = after.unwrap().content;
618        assert!(content.contains("# Project Instructions: MERMAID.md"));
619        assert!(content.contains("v2 longer content here"));
620        let _ = fs::remove_dir_all(&dir);
621    }
622
623    #[test]
624    fn refresh_returns_removed_when_file_deleted() {
625        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
626        let dir = temp_dir("removed");
627        let path = dir.join("MERMAID.md");
628        fs::write(&path, "v1").unwrap();
629        let prior = load_from_path(&path).unwrap();
630        fs::remove_file(&path).unwrap();
631        let (after, outcome) = refresh(Some(prior), &dir);
632        assert_eq!(outcome, ReloadOutcome::Removed);
633        assert!(after.is_none());
634        let _ = fs::remove_dir_all(&dir);
635    }
636
637    #[test]
638    fn refresh_returns_loaded_first_on_initial_discovery() {
639        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
640        let dir = temp_dir("first");
641        // Plant .git so the walk stays inside `dir`.
642        fs::create_dir(dir.join(".git")).unwrap();
643        // No prior load. Call refresh — should discover the new file.
644        fs::write(dir.join("MERMAID.md"), "fresh").unwrap();
645        let (after, outcome) = refresh(None, &dir);
646        assert!(matches!(outcome, ReloadOutcome::LoadedFirst { .. }));
647        let content = after.unwrap().content;
648        assert!(content.contains("# Project Instructions: MERMAID.md"));
649        assert!(content.contains("fresh"));
650        let _ = fs::remove_dir_all(&dir);
651    }
652
653    #[test]
654    fn load_project_context_loads_instructions_synchronously() {
655        // The one-shot paths (headless `mermaid run`, subagents) call this
656        // instead of relying on the config watcher, so it must surface MERMAID.md
657        // immediately — the bug was that headless runs saw no instructions at all.
658        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
659        let dir = temp_dir("project_context");
660        fs::create_dir(dir.join(".git")).unwrap();
661        fs::write(dir.join("MERMAID.md"), "sync-loaded instructions").unwrap();
662        let (instructions, _memory) =
663            load_project_context(&dir, &crate::app::MemoryConfig::default());
664        let content = instructions
665            .expect("instructions must load synchronously")
666            .content;
667        assert!(content.contains("sync-loaded instructions"));
668        let _ = fs::remove_dir_all(&dir);
669    }
670
671    #[test]
672    fn oversized_agents_does_not_drop_mermaid_winner() {
673        // F61: when AGENTS.md alone is huge, head-truncating the COMBINED body
674        // used to drop the entire MERMAID.md tail — silently letting the
675        // lower-priority file "win". MERMAID.md must survive intact and last (so
676        // it still overrides on conflict); AGENTS.md is the file truncated.
677        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
678        let dir = temp_dir("agents_huge");
679        fs::write(dir.join("AGENTS.md"), "A".repeat(60_000)).unwrap();
680        fs::write(dir.join("MERMAID.md"), "MERMAID_WINS_SENTINEL").unwrap();
681        let loaded =
682            load_from_paths(&[dir.join("AGENTS.md"), dir.join("MERMAID.md")]).expect("load");
683        assert!(loaded.truncated, "combined body exceeds the cap");
684        assert!(
685            loaded.content.contains("MERMAID_WINS_SENTINEL"),
686            "MERMAID.md (the winner) must survive the cap, not be dropped"
687        );
688        assert!(
689            loaded
690                .content
691                .contains("# Project Instructions: MERMAID.md")
692        );
693        assert!(loaded.content.contains(INSTRUCTIONS_TRUNCATION_MARKER));
694        // The winner lands AFTER the elision marker — AGENTS.md was the file
695        // truncated, and MERMAID.md still comes last so it overrides on conflict.
696        let marker_at = loaded.content.find(INSTRUCTIONS_TRUNCATION_MARKER).unwrap();
697        let winner_at = loaded.content.find("MERMAID_WINS_SENTINEL").unwrap();
698        assert!(
699            winner_at > marker_at,
700            "MERMAID.md must come after the truncated AGENTS.md"
701        );
702        // Bounded: never more than the cap plus a single marker.
703        assert!(
704            loaded.content.len() <= MAX_INSTRUCTIONS_BYTES + INSTRUCTIONS_TRUNCATION_MARKER.len()
705        );
706        let _ = fs::remove_dir_all(&dir);
707    }
708
709    #[test]
710    fn combine_and_cap_protects_the_last_section() {
711        // Lower-precedence section is large; the small winner must survive whole
712        // and land last, with the marker at the elision point.
713        let lower = format!("# Project Instructions: AGENTS.md\n\n{}", "L".repeat(200));
714        let winner = "# Project Instructions: MERMAID.md\n\nWIN".to_string();
715        let (body, truncated) = combine_and_cap_sections(vec![lower, winner], 100);
716        assert!(truncated);
717        assert!(body.contains("WIN"), "winner survives the cap");
718        assert!(body.contains(INSTRUCTIONS_TRUNCATION_MARKER));
719        let marker_at = body.find(INSTRUCTIONS_TRUNCATION_MARKER).unwrap();
720        assert!(
721            body.find("WIN").unwrap() > marker_at,
722            "winner stays last so it overrides on conflict"
723        );
724        assert!(body.len() <= 100 + INSTRUCTIONS_TRUNCATION_MARKER.len());
725    }
726
727    #[test]
728    fn combine_and_cap_clips_winner_when_it_alone_overflows() {
729        // When even the winner exceeds the cap, it's head-clipped (not dropped)
730        // and the lower-precedence section is dropped entirely.
731        let lower = "# Project Instructions: AGENTS.md\n\nlower-content".to_string();
732        let winner = format!("# Project Instructions: MERMAID.md\n\n{}", "W".repeat(300));
733        let (body, truncated) = combine_and_cap_sections(vec![lower, winner], 100);
734        assert!(truncated);
735        assert!(body.ends_with(INSTRUCTIONS_TRUNCATION_MARKER));
736        assert_eq!(body.len(), 100 + INSTRUCTIONS_TRUNCATION_MARKER.len());
737        assert!(
738            !body.contains("lower-content"),
739            "no room for the lower-precedence section"
740        );
741    }
742
743    #[test]
744    fn combine_and_cap_passes_through_when_it_fits() {
745        let a = "# Project Instructions: AGENTS.md\n\naye".to_string();
746        let b = "# Project Instructions: MERMAID.md\n\nbee".to_string();
747        let (body, truncated) = combine_and_cap_sections(vec![a, b], 10_000);
748        assert!(!truncated);
749        assert!(body.contains("aye") && body.contains("bee"));
750        assert!(
751            body.find("bee").unwrap() > body.find("aye").unwrap(),
752            "highest-precedence section stays last"
753        );
754    }
755
756    #[test]
757    fn load_from_paths_tolerates_a_missing_file() {
758        // F62: if one path is missing (e.g. MERMAID.md removed in the race
759        // between discovery and load), the present file(s) must still load
760        // rather than the whole multi-file set returning None.
761        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
762        let dir = temp_dir("partial_load");
763        fs::write(dir.join("AGENTS.md"), "agent rules").unwrap();
764        let missing = dir.join("MERMAID.md"); // never created
765        let loaded = load_from_paths(&[dir.join("AGENTS.md"), missing])
766            .expect("AGENTS.md must still load when MERMAID.md is absent");
767        assert!(loaded.content.contains("# Project Instructions: AGENTS.md"));
768        assert!(loaded.content.contains("agent rules"));
769        assert_eq!(loaded.sources.len(), 1, "only the present file is a source");
770        assert_eq!(loaded.path, dir.join("AGENTS.md"));
771        let _ = fs::remove_dir_all(&dir);
772    }
773
774    #[test]
775    fn load_from_paths_none_when_all_missing() {
776        let _lock = FS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
777        let dir = temp_dir("all_missing");
778        assert!(
779            load_from_paths(&[dir.join("AGENTS.md"), dir.join("MERMAID.md")]).is_none(),
780            "no present files => None"
781        );
782        let _ = fs::remove_dir_all(&dir);
783    }
784
785    #[test]
786    fn pick_home_boundary_resolves_windows_home_vars() {
787        // F63: on Windows `HOME` is usually unset; the home boundary must fall
788        // back to `%USERPROFILE%`, then `%HOMEDRIVE%%HOMEPATH%`. Exercised here
789        // with synthetic values so it's verifiable on every platform.
790        use std::ffi::OsStr;
791        // HOME wins when present.
792        assert_eq!(
793            pick_home_boundary(
794                Some(OsStr::new("/home/me")),
795                Some(OsStr::new("C:\\Users\\me")),
796                None,
797                None
798            ),
799            Some(PathBuf::from("/home/me"))
800        );
801        // No HOME => USERPROFILE (the Windows home var) bounds the walk.
802        assert_eq!(
803            pick_home_boundary(None, Some(OsStr::new("C:\\Users\\me")), None, None),
804            Some(PathBuf::from("C:\\Users\\me"))
805        );
806        // No HOME/USERPROFILE => HOMEDRIVE + HOMEPATH joined.
807        assert_eq!(
808            pick_home_boundary(
809                None,
810                None,
811                Some(OsStr::new("C:")),
812                Some(OsStr::new("\\Users\\me"))
813            ),
814            Some(PathBuf::from("C:\\Users\\me"))
815        );
816        // Empty values are ignored (not a usable boundary).
817        assert_eq!(
818            pick_home_boundary(Some(OsStr::new("")), Some(OsStr::new("")), None, None),
819            None
820        );
821        // HOMEDRIVE without HOMEPATH (and vice-versa) => no boundary.
822        assert_eq!(
823            pick_home_boundary(None, None, Some(OsStr::new("C:")), None),
824            None
825        );
826        assert_eq!(
827            pick_home_boundary(None, None, None, Some(OsStr::new("\\Users\\me"))),
828            None
829        );
830    }
831}