Skip to main content

agentmux_srv_core/backend/
startup_files.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The files a Claude Code session reads by itself at startup, listed for the
5//! "Given to the agent" card
6//! (SPEC_LAUNCH_CONTEXT_WORKSPACE_RULE_AND_STARTUP_FILES_2026_09_30.md §4,
7//! phase LC2). Before this the card showed only what the SessionStart hook
8//! carried, while the CLI had also loaded the user's `CLAUDE.md`, every
9//! `CLAUDE.md` up the folder tree (the hand-maintained
10//! `~/.agentmux/agents/CLAUDE.md` among them), their `@imports`, the skill
11//! listing and the MCP servers.
12//!
13//! This mirrors Claude Code's documented loading rules: it is what the CLI
14//! *should* have read, not proof that it did.
15
16use std::collections::HashSet;
17use std::path::{Path, PathBuf};
18
19/// Claude Code follows `@imports` this many hops deep.
20const MAX_IMPORT_DEPTH: usize = 5;
21
22/// Who writes a file: AgentMux, the user (a file in the agent's own
23/// workspace that AgentMux doesn't manage), or someone else (outside the
24/// workspace and not written by AgentMux, e.g. the hand-maintained shared
25/// `agents/CLAUDE.md`).
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum Owner {
28    Agentmux,
29    User,
30    External,
31}
32
33impl Owner {
34    pub fn as_str(self) -> &'static str {
35        match self {
36            Self::Agentmux => "agentmux",
37            Self::User => "user",
38            Self::External => "external",
39        }
40    }
41}
42
43/// One startup item.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct StartupFile {
46    /// `user_instructions`, `instructions`, `instructions_import`, `skills`
47    /// or `mcp_servers`.
48    pub role: &'static str,
49    /// Shown in the card: `~/…` for a path under the home dir.
50    pub name: String,
51    pub path: PathBuf,
52    pub owner: Owner,
53    /// The text as read; empty for the skills and MCP items, which list.
54    pub text: String,
55    /// For the skills and MCP items: how many are listed.
56    pub count: Option<usize>,
57    /// AgentMux sections the file carries: `global_memory`, `skills_index`.
58    pub contains: Vec<&'static str>,
59}
60
61/// Claude's startup files for a session in `cwd`, in the order the CLI loads
62/// them: the user's `CLAUDE.md` (in `config_dir`, else `~/.claude`), then
63/// each folder from the filesystem root down to `cwd` (its `CLAUDE.md`,
64/// `.claude/CLAUDE.md`, `CLAUDE.local.md`), each file followed by what it
65/// imports; then the skill listing and the MCP servers of `cwd`.
66pub fn claude_startup_files(cwd: &Path, config_dir: Option<&Path>, home: Option<&Path>) -> Vec<StartupFile> {
67    claude_startup_files_with_ancestors(cwd, config_dir, home, cwd.ancestors())
68}
69
70/// [`claude_startup_files`] for a host agent. In a folder a container agent can write
71/// (`mcp_folder_rule`), the CLI is started with AgentMux's own MCP config and not the folder's
72/// `.mcp.json`, so the servers listed are that config's.
73pub fn host_startup_files(cwd: &Path, config_dir: Option<&Path>, home: Option<&Path>) -> Vec<StartupFile> {
74    let folder = cwd.to_string_lossy();
75    let Some(own) = crate::backend::host_agent_files::dir_of(&folder) else {
76        return claude_startup_files(cwd, config_dir, home);
77    };
78    // There the CLI reads the person's own `CLAUDE.md` and what AgentMux keeps for the agent outside the
79    // folder (`host_agent_files`): its instructions, its skills and its MCP config. Nothing of the folder's.
80    let (mut out, mut seen) = (Vec::new(), HashSet::new());
81    let user_md = config_dir.map(Path::to_path_buf).or_else(|| home.map(|h| h.join(".claude"))).map(|d| d.join("CLAUDE.md"));
82    if let Some(p) = user_md {
83        add_instructions(&p, "user_instructions", cwd, home, 0, &mut seen, &mut out, None);
84    }
85    add_instructions(&crate::backend::host_agent_files::instructions_path(&own), "instructions", cwd, home, 0, &mut seen, &mut out, None);
86    out.extend(own_skills_item(&crate::backend::host_agent_files::plugin_dir(&own), home));
87    out.extend(mcp_item(&crate::backend::mcp_config_file::host_config_path(&folder), home, None));
88    out
89}
90
91/// The skills and commands AgentMux gives a host agent from `plugin`, its own folder outside the agent's
92/// working folder: one item with a count, as [`skills_item`] is for a working folder.
93fn own_skills_item(plugin: &Path, home: Option<&Path>) -> Option<StartupFile> {
94    let entries = |dir: &str| std::fs::read_dir(plugin.join(dir)).into_iter().flatten().flatten();
95    let count = entries("commands").filter(|e| e.path().extension().is_some_and(|x| x == "md")).count()
96        + entries("skills").filter(|e| e.path().join("SKILL.md").is_file()).count();
97    (count > 0).then(|| StartupFile {
98        role: "skills",
99        name: format!("Skills ({count}) in {}", display_name(plugin, home)),
100        path: plugin.to_path_buf(),
101        owner: Owner::Agentmux,
102        text: String::new(),
103        count: Some(count),
104        contains: Vec::new(),
105    })
106}
107
108pub fn claude_startup_files_with_ancestors<'a>(
109    cwd: &Path,
110    config_dir: Option<&Path>,
111    home: Option<&Path>,
112    ancestors: impl Iterator<Item = &'a Path>,
113) -> Vec<StartupFile> {
114    startup_files_confined(cwd, config_dir, home, ancestors, None)
115}
116
117/// The startup files of a container agent's workspace, which the container can write: only files that
118/// resolve (symlinks and `@` imports followed) to somewhere inside the workspace are read, so nothing
119/// it plants there makes srv read another path on the host.
120pub fn workspace_startup_files(workspace: &Path) -> Vec<StartupFile> {
121    let Ok(root) = std::fs::canonicalize(workspace) else { return Vec::new() };
122    startup_files_confined(workspace, None, None, std::iter::once(workspace), Some(&root))
123}
124
125/// `confine`: the canonical folder every file read must resolve inside, or `None` for no limit.
126fn startup_files_confined<'a>(
127    cwd: &Path,
128    config_dir: Option<&Path>,
129    home: Option<&Path>,
130    ancestors: impl Iterator<Item = &'a Path>,
131    confine: Option<&Path>,
132) -> Vec<StartupFile> {
133    let mut out = Vec::new();
134    let mut seen = HashSet::new();
135    let user_md = config_dir
136        .map(Path::to_path_buf)
137        .or_else(|| home.map(|h| h.join(".claude")))
138        .map(|d| d.join("CLAUDE.md"));
139    if let Some(p) = user_md {
140        add_instructions(&p, "user_instructions", cwd, home, 0, &mut seen, &mut out, confine);
141    }
142    let mut dirs: Vec<&Path> = ancestors.collect();
143    // "Up to, but not including, the root directory."
144    dirs.retain(|d| d.parent().is_some());
145    dirs.reverse();
146    for dir in dirs {
147        for name in ["CLAUDE.md", ".claude/CLAUDE.md", "CLAUDE.local.md"] {
148            add_instructions(&dir.join(name), "instructions", cwd, home, 0, &mut seen, &mut out, confine);
149        }
150    }
151    if let Some(skills) = skills_item(cwd, home, confine) {
152        out.push(skills);
153    }
154    if let Some(mcp) = mcp_item(&cwd.join(".mcp.json"), home, confine) {
155        out.push(mcp);
156    }
157    out
158}
159
160/// Whether `path` resolves inside the `confine` folder. For the skill listing, which reads no content (a
161/// count of names); file contents go through `confined_read`, which checks the file it opened.
162fn within(path: &Path, confine: Option<&Path>) -> bool {
163    match confine {
164        None => true,
165        Some(root) => std::fs::canonicalize(path).is_ok_and(|resolved| resolved.starts_with(root)),
166    }
167}
168
169fn add_instructions(
170    path: &Path,
171    role: &'static str,
172    cwd: &Path,
173    home: Option<&Path>,
174    depth: usize,
175    seen: &mut HashSet<PathBuf>,
176    out: &mut Vec<StartupFile>,
177    confine: Option<&Path>,
178) {
179    let Some(text) = crate::backend::confined_read::read_to_string_within(path, confine) else { return };
180    let key = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
181    if !seen.insert(key) {
182        return;
183    }
184    let owner = owner_of(path, &text, cwd);
185    let contains = contains(&text);
186    let imports = if depth < MAX_IMPORT_DEPTH { imports_of(&text, path, home) } else { Vec::new() };
187    out.push(StartupFile {
188        role,
189        name: display_name(path, home),
190        path: path.to_path_buf(),
191        owner,
192        text,
193        count: None,
194        contains,
195    });
196    for import in imports {
197        add_instructions(&import, "instructions_import", cwd, home, depth + 1, seen, out, confine);
198    }
199}
200
201fn owner_of(path: &Path, text: &str, cwd: &Path) -> Owner {
202    let agentmux_written = text.contains(crate::backend::agent_config::CLAUDE_MD_MANAGED_MARKER)
203        || text.contains("AgentMux: intentionally empty")
204        || path == cwd.join(crate::backend::agent_config::AGENTMUX_MEMORY_FILENAME);
205    if agentmux_written {
206        Owner::Agentmux
207    } else if path.starts_with(cwd) {
208        Owner::User
209    } else {
210        Owner::External
211    }
212}
213
214fn contains(text: &str) -> Vec<&'static str> {
215    let mut c = Vec::new();
216    if text.contains("# [AgentMux System] ") || text.contains("# [Workspace] ") {
217        c.push("global_memory");
218    }
219    if text.starts_with("# Available Skills") || text.contains("\n# Available Skills") {
220        c.push("skills_index");
221    }
222    c
223}
224
225/// `@path` imports in `text`, resolved against the importing file's folder
226/// (`~/` against the home dir), skipping fenced and inline code, which
227/// Claude Code doesn't evaluate. Only files that exist.
228fn imports_of(text: &str, file: &Path, home: Option<&Path>) -> Vec<PathBuf> {
229    let base = file.parent().unwrap_or(Path::new("."));
230    let mut out = Vec::new();
231    let mut fenced = false;
232    for line in text.lines() {
233        if line.trim_start().starts_with("```") {
234            fenced = !fenced;
235            continue;
236        }
237        if fenced {
238            continue;
239        }
240        // Odd segments between backticks are inline code.
241        for (i, segment) in line.split('`').enumerate() {
242            if i % 2 == 1 {
243                continue;
244            }
245            for token in segment.split_whitespace() {
246                let Some(raw) = token.strip_prefix('@') else { continue };
247                let raw = raw.trim_end_matches(|c: char| matches!(c, '.' | ',' | ';' | ':' | ')' | ']'));
248                if raw.is_empty() || raw.contains("://") {
249                    continue;
250                }
251                let path = match (raw.strip_prefix("~/"), home) {
252                    (Some(rest), Some(h)) => h.join(rest),
253                    (Some(_), None) => continue,
254                    (None, _) => {
255                        let p = Path::new(raw);
256                        if p.is_absolute() { p.to_path_buf() } else { base.join(p) }
257                    }
258                };
259                if path.is_file() {
260                    out.push(path);
261                }
262            }
263        }
264    }
265    out
266}
267
268/// The skill listing Claude Code builds from `.claude/commands/*.md` and
269/// `.claude/skills/*/SKILL.md`: one item with a count, no text (the CLI lists
270/// each by name and description).
271fn skills_item(cwd: &Path, home: Option<&Path>, confine: Option<&Path>) -> Option<StartupFile> {
272    if !within(&cwd.join(".claude"), confine) {
273        return None;
274    }
275    let mut count = 0usize;
276    // In a container's workspace, which the container can change, each folder and file counted must itself
277    // resolve inside it: a link to a host folder isn't listed.
278    let inside = |p: &Path| within(p, confine);
279    let commands = cwd.join(".claude/commands");
280    if let Some(entries) = inside(&commands).then(|| std::fs::read_dir(&commands).ok()).flatten() {
281        count += entries
282            .flatten()
283            .filter(|e| e.path().extension().is_some_and(|x| x == "md") && inside(&e.path()))
284            .count();
285    }
286    let skills = cwd.join(".claude/skills");
287    if let Some(entries) = inside(&skills).then(|| std::fs::read_dir(&skills).ok()).flatten() {
288        count += entries
289            .flatten()
290            .filter(|e| {
291                let skill = e.path().join("SKILL.md");
292                inside(&e.path()) && inside(&skill) && skill.is_file()
293            })
294            .count();
295    }
296    (count > 0).then(|| StartupFile {
297        role: "skills",
298        name: format!("Skills ({count}) in {}", display_name(&cwd.join(".claude"), home)),
299        path: cwd.join(".claude"),
300        owner: if cwd.join(crate::backend::agent_config::MANAGED_SKILL_FILES_MANIFEST).is_file() {
301            Owner::Agentmux
302        } else {
303            Owner::User
304        },
305        text: String::new(),
306        count: Some(count),
307        contains: Vec::new(),
308    })
309}
310
311/// The MCP servers in the config at `path`, by name only: the file carries the
312/// agent's signing keys, so its text never leaves this function.
313fn mcp_item(path: &Path, home: Option<&Path>, confine: Option<&Path>) -> Option<StartupFile> {
314    let path = path.to_path_buf();
315    let json: serde_json::Value = serde_json::from_str(&crate::backend::confined_read::read_to_string_within(&path, confine)?).ok()?;
316    let names: Vec<&str> = json.get("mcpServers")?.as_object()?.keys().map(String::as_str).collect();
317    if names.is_empty() {
318        return None;
319    }
320    Some(StartupFile {
321        role: "mcp_servers",
322        name: format!("MCP servers: {} ({})", names.join(", "), display_name(&path, home)),
323        path,
324        owner: if names.contains(&"agentmux") { Owner::Agentmux } else { Owner::User },
325        text: String::new(),
326        count: Some(names.len()),
327        contains: Vec::new(),
328    })
329}
330
331/// `~/x/y` for a path under `home`, else the path; forward slashes.
332fn display_name(path: &Path, home: Option<&Path>) -> String {
333    let shown = match home.and_then(|h| path.strip_prefix(h).ok()) {
334        Some(rest) => format!("~/{}", rest.display()),
335        None => path.display().to_string(),
336    };
337    shown.replace('\\', "/")
338}
339
340#[cfg(test)]
341mod tests {
342    use super::*;
343
344    fn write(p: &Path, text: &str) {
345        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
346        std::fs::write(p, text).unwrap();
347    }
348
349    /// A tree like a real agent's: home/.agentmux/agents/CLAUDE.md (shared,
350    /// hand-maintained), the agent's own foreign CLAUDE.md importing
351    /// AGENTMUX_MEMORY.md, a config-dir CLAUDE.md, skills and .mcp.json.
352    fn agent_tree() -> (tempfile::TempDir, PathBuf, PathBuf, PathBuf) {
353        let t = tempfile::tempdir().unwrap();
354        let home = t.path().join("home");
355        let agents = home.join(".agentmux/agents");
356        let cwd = agents.join("clamk-0612a");
357        let config = home.join(".agentmux/channels/c/identities/x/claude");
358        write(&agents.join("CLAUDE.md"), "# Jekt rules\n");
359        write(&cwd.join("CLAUDE.md"), "# Available Skills\n\n@.claude/AGENTMUX_MEMORY.md\n");
360        write(
361            &cwd.join(".claude/AGENTMUX_MEMORY.md"),
362            "# Memory\n# [AgentMux System] App API\n\n# Available Skills\n",
363        );
364        write(&config.join("CLAUDE.md"), "AgentMux: intentionally empty.\n");
365        write(&cwd.join(".claude/commands/tdd.md"), "x");
366        write(&cwd.join(".claude/commands/code-review.md"), "x");
367        write(&cwd.join(".claude/skills/run/SKILL.md"), "x");
368        write(&cwd.join(".claude/.agentmux-managed-skill-files.json"), "[]");
369        write(
370            &cwd.join(".mcp.json"),
371            r#"{"mcpServers":{"agentmux":{"env":{"AGENTMUX_JEKT_KEY":"secret"}}}}"#,
372        );
373        (t, home, cwd, config)
374    }
375
376    #[test]
377    fn lists_what_claude_loads_in_order_with_owners() {
378        let (tree, home, cwd, config) = agent_tree();
379        let files = claude_startup_files_with_ancestors(
380            &cwd, Some(&config), Some(&home), cwd.ancestors().take_while(|path| path.starts_with(tree.path())),
381        );
382        let got: Vec<(&str, &str, &str)> = files.iter().map(|f| (f.role, f.name.as_str(), f.owner.as_str())).collect();
383        assert_eq!(
384            got,
385            [
386                ("user_instructions", "~/.agentmux/channels/c/identities/x/claude/CLAUDE.md", "agentmux"),
387                ("instructions", "~/.agentmux/agents/CLAUDE.md", "external"),
388                ("instructions", "~/.agentmux/agents/clamk-0612a/CLAUDE.md", "user"),
389                ("instructions_import", "~/.agentmux/agents/clamk-0612a/.claude/AGENTMUX_MEMORY.md", "agentmux"),
390                ("skills", "Skills (3) in ~/.agentmux/agents/clamk-0612a/.claude", "agentmux"),
391                ("mcp_servers", "MCP servers: agentmux (~/.agentmux/agents/clamk-0612a/.mcp.json)", "agentmux"),
392            ]
393        );
394        let memory = &files[3];
395        assert_eq!(memory.contains, ["global_memory", "skills_index"]);
396        assert_eq!(files[2].contains, ["skills_index"]);
397    }
398
399    /// A container can write its workspace: an `@` import that points outside it (absolute, or up
400    /// through `..`) must not make srv read that file, or list it in the card.
401    #[test]
402    fn a_workspace_import_outside_the_workspace_is_not_read() {
403        let t = tempfile::tempdir().unwrap();
404        let ws = t.path().join("ws");
405        write(&t.path().join("outside.md"), "host file");
406        write(&t.path().join("abs.md"), "another host file");
407        write(&ws.join("inside.md"), "project file");
408        write(
409            &ws.join("CLAUDE.md"),
410            &format!("@inside.md
411@../outside.md
412@{}
413", t.path().join("abs.md").display()),
414        );
415        let files = workspace_startup_files(&ws);
416        let names: Vec<&str> = files.iter().map(|f| f.name.as_str()).collect();
417        assert!(names.iter().any(|n| n.ends_with("inside.md")), "{names:?}");
418        assert!(!names.iter().any(|n| n.ends_with("outside.md") || n.ends_with("abs.md")), "{names:?}");
419        assert!(files.iter().all(|f| !f.text.contains("host file")), "no host file's text was read");
420    }
421
422    #[cfg(unix)]
423    #[test]
424    fn a_workspace_symlink_to_a_host_file_is_not_read() {
425        let t = tempfile::tempdir().unwrap();
426        let ws = t.path().join("ws");
427        write(&t.path().join("host.json"), r#"{"mcpServers":{"hostsecret":{}}}"#);
428        std::fs::create_dir_all(&ws).unwrap();
429        std::os::unix::fs::symlink(t.path().join("host.json"), ws.join(".mcp.json")).unwrap();
430        std::os::unix::fs::symlink(t.path().join("host.json"), ws.join("CLAUDE.md")).unwrap();
431        assert!(workspace_startup_files(&ws).is_empty());
432    }
433
434    #[cfg(unix)]
435    #[test]
436    fn a_workspace_skills_link_to_a_host_folder_is_not_counted() {
437        let tmp = tempfile::tempdir().unwrap();
438        let ws = tmp.path().join("ws");
439        std::fs::create_dir_all(ws.join(".claude")).unwrap();
440        let outside = tempfile::tempdir().unwrap();
441        for name in ["a", "b", "c"] {
442            write(&outside.path().join(name).join("SKILL.md"), "x");
443            write(&outside.path().join(format!("{name}.md")), "x");
444        }
445        std::os::unix::fs::symlink(outside.path(), ws.join(".claude/skills")).unwrap();
446        std::os::unix::fs::symlink(outside.path(), ws.join(".claude/commands")).unwrap();
447        let files = workspace_startup_files(&ws);
448        assert!(files.iter().all(|f| f.role != "skills"), "nothing outside the workspace is counted");
449    }
450
451    /// In a folder a container agent has run in, a host agent is started with AgentMux's own config: the
452    /// servers listed are that file's, not the ones the folder's `.mcp.json` names.
453    #[test]
454    fn a_host_agent_in_a_container_agents_folder_lists_the_servers_it_is_given() {
455        let (data, was) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
456        let dir = was.path().to_string_lossy().into_owned();
457        std::fs::write(was.path().join(".mcp.json"), r#"{"mcpServers":{"agentmux":{"command":"x"},"of-the-folder":{"command":"y"}}}"#).unwrap();
458        crate::backend::mcp_config_file::with_data_home(data.path(), || {
459            let listed = |files: Vec<StartupFile>| files.into_iter().filter(|f| f.role == "mcp_servers").map(|f| (f.name, f.path)).collect::<Vec<_>>();
460            let before = listed(host_startup_files(was.path(), None, None));
461            assert!(before.len() == 1 && before[0].0.contains("of-the-folder") && before[0].1 == was.path().join(".mcp.json"), "{before:?}");
462
463            crate::backend::mcp_folder_rule::mark(&dir);
464            assert_eq!(listed(host_startup_files(was.path(), None, None)), Vec::new(), "nothing of the folder's file while AgentMux's is not written");
465            let ours = crate::backend::mcp_config_file::host_config_path(&dir);
466            crate::backend::mcp_config_file::write_relocated(&ours, r#"{"mcpServers":{"agentmux":{"command":"x"}}}"#).unwrap();
467            let after = listed(host_startup_files(was.path(), None, None));
468            assert!(after.len() == 1 && after[0].1 == ours && !after[0].0.contains("of-the-folder") && after[0].0.contains("agentmux"), "{after:?}");
469        });
470    }
471
472    /// What the card lists for a host agent there is what its CLI is given: the person's own `CLAUDE.md` and
473    /// AgentMux's instructions and skills from outside the folder. The folder's own instruction files and
474    /// skills, and those of the folders above it, are not listed: they are not loaded.
475    #[test]
476    fn a_host_agent_in_a_container_agents_folder_lists_the_instructions_and_skills_it_is_given() {
477        let (data, tree) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
478        let (config, was) = (tree.path().join("config"), tree.path().join("code").join("app"));
479        write(&config.join("CLAUDE.md"), "the person's own");
480        write(&tree.path().join("code").join("CLAUDE.md"), "of the folder above");
481        write(&was.join("CLAUDE.md"), "of the folder");
482        write(&was.join(".claude/CLAUDE.md"), "of the folder too");
483        write(&was.join(".claude/skills/theirs/SKILL.md"), "x");
484        let dir = was.to_string_lossy().into_owned();
485        crate::backend::mcp_config_file::with_data_home(data.path(), || {
486            crate::backend::mcp_folder_rule::mark(&dir);
487            let launch = [("CLAUDE.md", "# [Workspace] rule\nfrom AgentMux"), (".claude/skills/review/SKILL.md", "x"), (".claude/commands/go.md", "x")];
488            assert_eq!(crate::backend::host_agent_files::write(&dir, launch.into_iter()), Ok(true));
489            let own = crate::backend::host_agent_files::dir_of(&dir).unwrap();
490
491            let files = host_startup_files(&was, Some(&config), None);
492            let listed: Vec<(&str, &Path, Owner)> = files.iter().map(|f| (f.role, f.path.as_path(), f.owner)).collect();
493            let instructions = crate::backend::host_agent_files::instructions_path(&own);
494            let plugin = crate::backend::host_agent_files::plugin_dir(&own);
495            assert_eq!(
496                listed,
497                vec![
498                    ("user_instructions", config.join("CLAUDE.md").as_path(), Owner::External),
499                    ("instructions", instructions.as_path(), Owner::Agentmux),
500                    ("skills", plugin.as_path(), Owner::Agentmux),
501                ],
502                "nothing of the folder or of the folders above it"
503            );
504            assert_eq!(files[2].count, Some(2), "AgentMux's own skill and command");
505            assert!(files[1].contains.contains(&"global_memory"), "what the startup file carries is read from AgentMux's own file");
506        });
507    }
508
509    #[test]
510    fn the_mcp_item_never_carries_the_file() {
511        let (tree, home, cwd, config) = agent_tree();
512        let files = claude_startup_files_with_ancestors(
513            &cwd, Some(&config), Some(&home), cwd.ancestors().take_while(|path| path.starts_with(tree.path())),
514        );
515        let mcp = files.iter().find(|f| f.role == "mcp_servers").unwrap();
516        assert!(mcp.text.is_empty());
517        assert_eq!(mcp.count, Some(1));
518        assert!(!format!("{mcp:?}").contains("secret"));
519    }
520
521    #[test]
522    fn imports_resolve_relative_and_home_skip_code_and_stop_at_cycles() {
523        let t = tempfile::tempdir().unwrap();
524        let home = t.path().join("home");
525        let cwd = t.path().join("ws");
526        write(
527            &cwd.join("CLAUDE.md"),
528            "See @docs/a.md and @~/notes.md.\n`@docs/in-code.md`\n```\n@docs/fenced.md\n```\n@missing.md\n",
529        );
530        write(&cwd.join("docs/a.md"), "@../CLAUDE.md back again\n");
531        write(&cwd.join("docs/in-code.md"), "x");
532        write(&cwd.join("docs/fenced.md"), "x");
533        write(&home.join("notes.md"), "notes");
534        let files = claude_startup_files_with_ancestors(
535            &cwd, None, Some(&home), cwd.ancestors().take_while(|path| path.starts_with(t.path())),
536        );
537        let names: Vec<&str> = files.iter().map(|f| f.name.as_str()).collect();
538        let a = cwd.join("docs/a.md").display().to_string().replace('\\', "/");
539        let root_md = cwd.join("CLAUDE.md").display().to_string().replace('\\', "/");
540        assert_eq!(names, [root_md.as_str(), a.as_str(), "~/notes.md"]);
541        assert!(files[1..].iter().all(|f| f.role == "instructions_import"));
542    }
543
544    #[test]
545    fn nothing_there_lists_nothing() {
546        let tree = tempfile::tempdir().unwrap();
547        write(&tree.path().join("CLAUDE.md"), "Parent instructions outside the fixture");
548        write(&tree.path().join(".claude/CLAUDE.md"), "Parent home instructions outside the fixture");
549        let root = tree.path().join("fixture");
550        let cwd = root.join("ws");
551        let home = root.join("home");
552        assert!(claude_startup_files_with_ancestors(
553            &cwd, None, Some(&home), cwd.ancestors().take_while(|path| path.starts_with(&root)),
554        ).is_empty());
555    }
556
557    #[test]
558    fn home_instructions_and_imports_use_the_fixture_home() {
559        let tree = tempfile::tempdir().unwrap();
560        let home = tree.path().join("home");
561        let cwd = home.join("ws");
562        write(&home.join(".claude/CLAUDE.md"), "@~/notes.md");
563        write(&home.join("notes.md"), "Fixture home notes");
564        let files = claude_startup_files_with_ancestors(
565            &cwd, None, Some(&home), cwd.ancestors().take_while(|path| path.starts_with(tree.path())),
566        );
567        assert_eq!(files.iter().map(|file| (file.role, file.name.as_str())).collect::<Vec<_>>(), [
568            ("user_instructions", "~/.claude/CLAUDE.md"),
569            ("instructions_import", "~/notes.md"),
570        ]);
571        assert!(files.iter().all(|file| file.path.starts_with(&home)));
572    }
573}