Skip to main content

cellix_agent/context/
mod.rs

1//! What an agent works from: the instruction files it loads and in what order, its skills,
2//! subagents, commands, hooks and MCP servers, what a session of it read, and checks on all of
3//! that. Every file here is read as data; nothing in one is ever followed. Nothing here writes.
4//!
5//! Each agent's rules are its own, so each has its own discovery. With a transcript, what the
6//! agent says it loaded wins over what the files suggest (`transcript`).
7
8mod checks;
9mod imports;
10mod transcript;
11
12use std::fs;
13use std::path::{Path, PathBuf};
14
15use serde_json::{Map, Value};
16
17pub use checks::{Check, CheckKind, checks};
18pub use imports::{IMPORT_DEPTH, imports};
19pub use transcript::{
20    Breakdown, FileRead, Loaded, Search, Session, claude_window, read_session, transcript_path,
21};
22
23/// Claude Code loads only this many lines of its auto memory's `MEMORY.md`.
24pub const MEMORY_LINES: usize = 200;
25/// Nor more than this many bytes of it, whichever comes first.
26pub const MEMORY_BYTES: usize = 25 * 1024;
27/// Codex stops reading project instructions after this many bytes (`project_doc_max_bytes`).
28pub const CODEX_BYTES: usize = 32 * 1024;
29/// Claude Code warns of an instruction file past this many characters.
30pub const LARGE_CHARS: usize = 40_000;
31/// How deep below the project to look for files an agent reads only when it works there.
32const NESTED_DEPTH: usize = 4;
33/// Folders never looked in for nested instructions: build output and tools' own.
34const SKIPPED: [&str; 7] = [
35    "target",
36    "node_modules",
37    ".git",
38    "dist",
39    "build",
40    ".venv",
41    "vendor",
42];
43
44#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
45pub enum Agent {
46    Claude,
47    Codex,
48    Gemini,
49}
50
51impl Agent {
52    pub const ALL: [Agent; 3] = [Agent::Claude, Agent::Codex, Agent::Gemini];
53
54    pub fn name(self) -> &'static str {
55        match self {
56            Agent::Claude => "Claude Code",
57            Agent::Codex => "Codex",
58            Agent::Gemini => "Gemini CLI",
59        }
60    }
61
62    /// The agent Cellix names `name`, as its tabs do.
63    pub fn named(name: &str) -> Option<Agent> {
64        Agent::ALL.into_iter().find(|a| a.name() == name)
65    }
66}
67
68/// Where a file or setting comes from, as the agent ranks them.
69#[derive(Clone, Copy, Debug, PartialEq, Eq)]
70pub enum Scope {
71    /// Set for the machine by an administrator.
72    Managed,
73    /// The user's, for every project.
74    User,
75    /// Checked in with the project.
76    Project,
77    /// The user's own for this project, not checked in.
78    Local,
79    /// The agent's own notes, written by it.
80    Memory,
81    /// Brought in by a plugin or extension.
82    Plugin,
83    /// Set for the user's account rather than in a file.
84    Account,
85}
86
87impl Scope {
88    pub fn label(self) -> &'static str {
89        match self {
90            Scope::Managed => "managed",
91            Scope::User => "user",
92            Scope::Project => "project",
93            Scope::Local => "local",
94            Scope::Memory => "auto memory",
95            Scope::Plugin => "plugin",
96            Scope::Account => "account",
97        }
98    }
99
100    /// The scope Claude Code's transcript gives a loaded file.
101    pub fn from_claude(kind: &str) -> Scope {
102        match kind {
103            "Managed" | "Policy" | "Enterprise" => Scope::Managed,
104            "User" => Scope::User,
105            "Local" => Scope::Local,
106            "AutoMem" | "Memory" | "AutoMemory" => Scope::Memory,
107            _ => Scope::Project,
108        }
109    }
110}
111
112/// Where each agent keeps the user's own settings. Tests point these at fixtures.
113#[derive(Clone, Debug, Default)]
114pub struct Homes {
115    /// `~/.claude`, or `CLAUDE_CONFIG_DIR`.
116    pub claude: Option<PathBuf>,
117    /// Where `.claude.json` is: the home folder, or `CLAUDE_CONFIG_DIR` when that's set.
118    pub claude_json: Option<PathBuf>,
119    /// `~/.codex`, or `CODEX_HOME`.
120    pub codex: Option<PathBuf>,
121    /// `~/.gemini`.
122    pub gemini: Option<PathBuf>,
123    /// The machine's managed instructions for Claude Code.
124    pub managed: Option<PathBuf>,
125}
126
127impl Homes {
128    pub fn from_env() -> Homes {
129        let var = |name: &str| {
130            std::env::var_os(name)
131                .filter(|v| !v.is_empty())
132                .map(PathBuf::from)
133        };
134        let home = var("HOME").or_else(|| var("USERPROFILE"));
135        let claude_dir = var("CLAUDE_CONFIG_DIR");
136        let managed = if cfg!(target_os = "macos") {
137            Some(PathBuf::from(
138                "/Library/Application Support/ClaudeCode/CLAUDE.md",
139            ))
140        } else if cfg!(windows) {
141            Some(PathBuf::from(r"C:\Program Files\ClaudeCode\CLAUDE.md"))
142        } else {
143            Some(PathBuf::from("/etc/claude-code/CLAUDE.md"))
144        };
145        Homes {
146            claude: claude_dir
147                .clone()
148                .or_else(|| home.as_ref().map(|h| h.join(".claude"))),
149            claude_json: claude_dir
150                .or_else(|| home.clone())
151                .map(|d| d.join(".claude.json")),
152            codex: var("CODEX_HOME").or_else(|| home.as_ref().map(|h| h.join(".codex"))),
153            gemini: home.as_ref().map(|h| h.join(".gemini")),
154            managed,
155        }
156    }
157}
158
159/// One instruction file, in the order the agent reads it.
160#[derive(Clone, Debug, PartialEq)]
161pub struct Instruction {
162    pub path: PathBuf,
163    pub scope: Scope,
164    /// The file and line that imported it, for a file brought in by `@path`.
165    pub imported_by: Option<(PathBuf, usize)>,
166    /// How many imports deep it is: 0 for a file the agent finds itself.
167    pub depth: usize,
168    /// Loaded only once the agent works in this folder, not at the start.
169    pub later: Option<PathBuf>,
170    /// The agent reads only this many lines of it.
171    pub limit: Option<usize>,
172    pub text: Option<String>,
173}
174
175impl Instruction {
176    fn new(path: PathBuf, scope: Scope) -> Instruction {
177        let text = read_text(&path);
178        Instruction {
179            path,
180            scope,
181            imported_by: None,
182            depth: 0,
183            later: None,
184            limit: None,
185            text,
186        }
187    }
188
189    pub fn exists(&self) -> bool {
190        self.text.is_some()
191    }
192
193    pub fn lines(&self) -> usize {
194        self.text.as_deref().map_or(0, |t| t.lines().count())
195    }
196
197    /// What the agent actually takes in: all of it, or the lines it reads.
198    pub fn loaded(&self) -> &str {
199        let text = self.text.as_deref().unwrap_or("");
200        match self.limit {
201            Some(limit) => {
202                let end = text.split_inclusive('\n').take(limit).map(str::len).sum();
203                &text[..end]
204            }
205            None => text,
206        }
207    }
208
209    pub fn tokens(&self) -> usize {
210        estimate_tokens(self.loaded())
211    }
212}
213
214/// Text is about four characters a token in English and code; good enough to compare parts.
215pub fn estimate_tokens(text: &str) -> usize {
216    text.chars().count().div_ceil(4)
217}
218
219#[derive(Clone, Copy, Debug, PartialEq, Eq)]
220pub enum ItemKind {
221    Skill,
222    Subagent,
223    Command,
224    Hook,
225    Mcp,
226    Extension,
227}
228
229impl ItemKind {
230    pub fn label(self) -> &'static str {
231        match self {
232            ItemKind::Skill => "skill",
233            ItemKind::Subagent => "subagent",
234            ItemKind::Command => "command",
235            ItemKind::Hook => "hook",
236            ItemKind::Mcp => "MCP server",
237            ItemKind::Extension => "extension",
238        }
239    }
240}
241
242/// A skill, subagent, command, hook or MCP server, and the file that defines it.
243#[derive(Clone, Debug, PartialEq)]
244pub struct Item {
245    pub kind: ItemKind,
246    pub name: String,
247    /// What it's for, as the agent is told: a description, or the hook's command.
248    pub about: String,
249    pub scope: Scope,
250    pub path: PathBuf,
251    /// The line it starts on, 1-based, where that isn't the top.
252    pub line: Option<usize>,
253}
254
255/// Everything an agent works from in one project, before any session.
256#[derive(Clone, Debug, Default)]
257pub struct Context {
258    pub instructions: Vec<Instruction>,
259    pub items: Vec<Item>,
260}
261
262/// What `agent` would load working in `project`, worked out from the files by its rules.
263pub fn discover(agent: Agent, project: &Path, homes: &Homes) -> Context {
264    match agent {
265        Agent::Claude => Context {
266            instructions: claude_instructions(project, homes),
267            items: claude_items(project, homes),
268        },
269        Agent::Codex => Context {
270            instructions: codex_instructions(project, homes),
271            items: codex_items(homes),
272        },
273        Agent::Gemini => Context {
274            instructions: gemini_instructions(project, homes),
275            items: gemini_items(project, homes),
276        },
277    }
278}
279
280fn read_text(path: &Path) -> Option<String> {
281    let meta = fs::metadata(path).ok()?;
282    if !meta.is_file() {
283        return None;
284    }
285    let bytes = fs::read(path).ok()?;
286    Some(String::from_utf8_lossy(&bytes).into_owned())
287}
288
289/// Each instruction file followed at once by what it imports, depth first, as Claude Code and
290/// Gemini CLI read them. A file already in the list isn't read twice.
291fn with_imports(found: Vec<Instruction>) -> Vec<Instruction> {
292    let mut out: Vec<Instruction> = Vec::new();
293    for file in found {
294        push_with_imports(file, &mut out);
295    }
296    out
297}
298
299fn push_with_imports(file: Instruction, out: &mut Vec<Instruction>) {
300    if out.iter().any(|i| i.path == file.path) {
301        return;
302    }
303    let refs = file.text.as_deref().map(imports).unwrap_or_default();
304    let (scope, depth, later, dir) = (
305        file.scope,
306        file.depth,
307        file.later.clone(),
308        file.path.parent().map(Path::to_path_buf),
309    );
310    let from = file.path.clone();
311    out.push(file);
312    if depth >= IMPORT_DEPTH {
313        return;
314    }
315    for import in refs {
316        let path = imports::resolve(&import.target, dir.as_deref().unwrap_or(Path::new("")));
317        let mut child = Instruction::new(path, scope);
318        child.imported_by = Some((from.clone(), import.line));
319        child.depth = depth + 1;
320        child.later = later.clone();
321        push_with_imports(child, out);
322    }
323}
324
325/// The folders from the top of the file system down to `project`, the order an agent reads
326/// instructions in, so the closest comes last and counts most.
327fn ancestors_down(project: &Path) -> Vec<PathBuf> {
328    let mut dirs: Vec<PathBuf> = project.ancestors().map(Path::to_path_buf).collect();
329    dirs.reverse();
330    dirs
331}
332
333/// The top of the git repository `project` is in, or `project` itself.
334fn repo_root(project: &Path) -> PathBuf {
335    project
336        .ancestors()
337        .find(|d| d.join(".git").exists())
338        .unwrap_or(project)
339        .to_path_buf()
340}
341
342/// The main checkout of the repository a worktree belongs to, from its `.git` file.
343fn main_checkout(project: &Path) -> Option<PathBuf> {
344    let root = repo_root(project);
345    let text = fs::read_to_string(root.join(".git")).ok()?;
346    let gitdir = PathBuf::from(text.strip_prefix("gitdir:")?.trim());
347    // <main>/.git/worktrees/<name>
348    let dot_git = gitdir.parent()?.parent()?;
349    (dot_git.file_name()? == ".git").then(|| dot_git.parent().map(Path::to_path_buf))?
350}
351
352/// The folder Claude Code keeps a project's sessions in: its path with every character that
353/// isn't a letter or digit made a dash.
354pub fn claude_project_dir(claude: &Path, project: &Path) -> PathBuf {
355    let name: String = project
356        .to_string_lossy()
357        .chars()
358        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
359        .collect();
360    claude.join("projects").join(name)
361}
362
363/// Claude Code's own notes for the project. They're kept for the repository, so a subfolder
364/// and a worktree share its main checkout's; outside a repository, for the folder. A folder
365/// set as `autoMemoryDirectory` in settings is used instead.
366fn claude_memory(project: &Path, claude: &Path) -> PathBuf {
367    if let Some(dir) = auto_memory_directory(project, claude) {
368        return dir.join("MEMORY.md");
369    }
370    let index = |p: &Path| {
371        claude_project_dir(claude, p)
372            .join("memory")
373            .join("MEMORY.md")
374    };
375    let repo = main_checkout(project).unwrap_or_else(|| repo_root(project));
376    let shared = index(&repo);
377    if shared.exists() {
378        return shared;
379    }
380    // Older versions kept them for the folder Claude Code was started in.
381    let own = index(project);
382    if own.exists() { own } else { shared }
383}
384
385/// `autoMemoryDirectory` from Claude Code's settings, the project's over the user's.
386fn auto_memory_directory(project: &Path, claude: &Path) -> Option<PathBuf> {
387    let files = [
388        project.join(".claude/settings.local.json"),
389        project.join(".claude/settings.json"),
390        claude.join("settings.json"),
391    ];
392    let dir = files.iter().find_map(|file| {
393        let text = fs::read_to_string(file).ok()?;
394        let settings: Value = serde_json::from_str(&text).ok()?;
395        settings["autoMemoryDirectory"]
396            .as_str()
397            .filter(|d| !d.is_empty())
398            .map(str::to_string)
399    })?;
400    let home = claude.parent();
401    Some(match (dir.strip_prefix("~/"), home) {
402        (Some(rest), Some(home)) => home.join(rest),
403        _ => PathBuf::from(dir),
404    })
405}
406
407/// Markdown files in `dir` and the folders under it, as Claude Code finds its rules.
408fn markdown_files(dir: &Path) -> Vec<PathBuf> {
409    let mut files = Vec::new();
410    let mut folders = vec![(dir.to_path_buf(), 0)];
411    while let Some((folder, depth)) = folders.pop() {
412        for path in fs::read_dir(&folder)
413            .into_iter()
414            .flatten()
415            .flatten()
416            .map(|e| e.path())
417        {
418            if path.is_dir() && depth < NESTED_DEPTH {
419                folders.push((path, depth + 1));
420            } else if path.extension().is_some_and(|e| e == "md") && path.is_file() {
421                files.push(path);
422            }
423        }
424    }
425    files.sort();
426    files
427}
428
429/// A rule as Claude Code loads it: at the start, or, with `paths` in its front matter, only
430/// once the agent works with a file those match, from the folder that holds its `.claude`.
431fn rule(path: PathBuf, scope: Scope, base: &Path) -> Instruction {
432    let mut rule = Instruction::new(path, scope);
433    let scoped = rule
434        .text
435        .as_deref()
436        .is_some_and(|text| front_matter(text).iter().any(|(key, _)| key == "paths"));
437    if scoped {
438        rule.later = Some(base.to_path_buf());
439    }
440    rule
441}
442
443/// Which instruction files Claude Code reads, as its built-in AGENTS.md plugin is set in the
444/// user's settings: `claude-md-or-agents-md` unless it says otherwise.
445fn claude_instruction_files(claude: Option<&Path>) -> String {
446    let setting = claude.and_then(|claude| {
447        let text = fs::read_to_string(claude.join("settings.json")).ok()?;
448        let settings: Value = serde_json::from_str(&text).ok()?;
449        ["cc-plugin-agents-md@builtin", "agents-md@builtin"]
450            .iter()
451            .find_map(|id| {
452                settings["pluginConfigs"][id]["options"]["instructionFiles"]
453                    .as_str()
454                    .map(str::to_string)
455            })
456    });
457    setting.unwrap_or_else(|| "claude-md-or-agents-md".to_string())
458}
459
460fn claude_instructions(project: &Path, homes: &Homes) -> Vec<Instruction> {
461    let mut found = Vec::new();
462    if let Some(managed) = &homes.managed {
463        found.push(Instruction::new(managed.clone(), Scope::Managed));
464    }
465    if let Some(claude) = &homes.claude {
466        found.push(Instruction::new(claude.join("CLAUDE.md"), Scope::User));
467        let home = claude.parent().unwrap_or(claude);
468        found.extend(
469            markdown_files(&claude.join("rules"))
470                .into_iter()
471                .map(|p| rule(p, Scope::User, home)),
472        );
473    }
474    let user_file = homes.claude.as_ref().map(|c| c.join("CLAUDE.md"));
475    let folders = ancestors_down(project);
476    // AGENTS.md is read in place of CLAUDE.md when the project has none, of the three names,
477    // from here up; the user's own CLAUDE.md doesn't count. A setting can read both, or neither.
478    let claude_files = ["CLAUDE.md", ".claude/CLAUDE.md", "CLAUDE.local.md"];
479    let has_claude_md = folders.iter().any(|dir| {
480        claude_files
481            .iter()
482            .map(|name| dir.join(name))
483            .any(|path| path.is_file() && Some(&path) != user_file.as_ref())
484    });
485    let reads_agents_md = match claude_instruction_files(homes.claude.as_deref()).as_str() {
486        "claude-md-and-agents-md" => true,
487        "managed-only" => false,
488        _ => !has_claude_md,
489    };
490    for dir in &folders {
491        for name in ["CLAUDE.md", ".claude/CLAUDE.md"] {
492            let path = dir.join(name);
493            if Some(&path) != user_file.as_ref() {
494                found.push(Instruction::new(path, Scope::Project));
495            }
496        }
497        if dir == project {
498            found.extend(
499                markdown_files(&dir.join(".claude").join("rules"))
500                    .into_iter()
501                    .map(|p| rule(p, Scope::Project, dir)),
502            );
503        }
504        found.push(Instruction::new(dir.join("CLAUDE.local.md"), Scope::Local));
505        if reads_agents_md {
506            for name in ["AGENTS.md", ".claude/AGENTS.md"] {
507                found.push(Instruction::new(dir.join(name), Scope::Project));
508            }
509        }
510    }
511    // Only what's there, but the user's file stays so its absence can be shown.
512    found.retain(|i| {
513        i.exists()
514            || (i.scope == Scope::User && i.path.file_name().is_some_and(|n| n == "CLAUDE.md"))
515    });
516    if let Some(claude) = &homes.claude {
517        let mut memory = Instruction::new(claude_memory(project, claude), Scope::Memory);
518        // The first 200 lines or 25 KB, whichever comes first.
519        let text = memory.text.as_deref().unwrap_or("");
520        let mut cut = MEMORY_BYTES.min(text.len());
521        while !text.is_char_boundary(cut) {
522            cut -= 1;
523        }
524        // The whole lines that fit.
525        let within = if cut < text.len() {
526            text[..cut].matches('\n').count()
527        } else {
528            MEMORY_LINES
529        };
530        memory.limit = Some(MEMORY_LINES.min(within));
531        if memory.exists() {
532            found.push(memory);
533        }
534    }
535    // Below here, each folder's files load once the agent works there: its CLAUDE.md and
536    // CLAUDE.local.md, or its AGENTS.md when it has neither.
537    let mut below = nested(project, &["CLAUDE.md", "CLAUDE.local.md"]);
538    if reads_agents_md {
539        below.extend(nested(project, &["AGENTS.md"]).into_iter().filter(|path| {
540            let dir = path.parent().unwrap_or(project);
541            !claude_files.iter().any(|name| dir.join(name).is_file())
542        }));
543    }
544    below.sort();
545    for path in below {
546        let scope = if path.ends_with("CLAUDE.local.md") {
547            Scope::Local
548        } else {
549            Scope::Project
550        };
551        let mut later = Instruction::new(path.clone(), scope);
552        later.later = path.parent().map(Path::to_path_buf);
553        found.push(later);
554    }
555    with_imports(found)
556}
557
558/// Instruction files in folders under `project`, which an agent loads only when it reads a file
559/// there.
560fn nested(project: &Path, names: &[&str]) -> Vec<PathBuf> {
561    let mut out = Vec::new();
562    let mut stack = vec![(project.to_path_buf(), 0)];
563    let mut seen = 0;
564    while let Some((dir, depth)) = stack.pop() {
565        seen += 1;
566        if seen > 4000 {
567            break;
568        }
569        let mut entries: Vec<PathBuf> = fs::read_dir(&dir)
570            .into_iter()
571            .flatten()
572            .flatten()
573            .map(|e| e.path())
574            .collect();
575        entries.sort();
576        for path in entries.into_iter().rev() {
577            let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
578                continue;
579            };
580            if path.is_dir() {
581                if depth < NESTED_DEPTH && !name.starts_with('.') && !SKIPPED.contains(&name) {
582                    stack.push((path, depth + 1));
583                }
584            } else if dir != project && names.contains(&name) {
585                out.push(path);
586            }
587        }
588    }
589    out.sort();
590    out
591}
592
593/// A Markdown file's front matter, as plain `key: value` pairs, quotes taken off.
594pub fn front_matter(text: &str) -> Vec<(String, String)> {
595    let mut lines = text.lines();
596    if lines.next().map(str::trim) != Some("---") {
597        return Vec::new();
598    }
599    let mut out = Vec::new();
600    for line in lines {
601        if line.trim() == "---" {
602            break;
603        }
604        if line.starts_with([' ', '\t']) {
605            continue;
606        }
607        if let Some((key, value)) = line.split_once(':') {
608            let value = value
609                .trim()
610                .trim_matches(|c| c == '"' || c == '\'')
611                .to_string();
612            out.push((key.trim().to_string(), value));
613        }
614    }
615    out
616}
617
618fn field(front: &[(String, String)], key: &str) -> Option<String> {
619    front
620        .iter()
621        .find(|(k, _)| k == key)
622        .map(|(_, v)| v.clone())
623        .filter(|v| !v.is_empty())
624}
625
626/// The first line of prose after the front matter, for a file that says what it's for there.
627fn first_line(text: &str) -> String {
628    let body = match text.strip_prefix("---") {
629        Some(rest) => rest.split_once("\n---").map_or("", |(_, b)| b),
630        None => text,
631    };
632    body.lines()
633        .map(|l| l.trim().trim_start_matches('#').trim())
634        .find(|l| !l.is_empty())
635        .unwrap_or("")
636        .to_string()
637}
638
639/// One item per Markdown file in `dir` (skills: one per folder holding `SKILL.md`).
640fn markdown_items(kind: ItemKind, dir: &Path, scope: Scope) -> Vec<Item> {
641    let files: Vec<PathBuf> = if kind == ItemKind::Skill {
642        let mut dirs: Vec<PathBuf> = fs::read_dir(dir)
643            .into_iter()
644            .flatten()
645            .flatten()
646            .map(|e| e.path().join("SKILL.md"))
647            .filter(|p| p.is_file())
648            .collect();
649        dirs.sort();
650        dirs
651    } else {
652        walk_files(dir, "md")
653    };
654    files
655        .into_iter()
656        .map(|path| {
657            let text = read_text(&path).unwrap_or_default();
658            let front = front_matter(&text);
659            let fallback = if kind == ItemKind::Skill {
660                path.parent().and_then(Path::file_name)
661            } else {
662                path.file_stem()
663            };
664            let mut name = field(&front, "name").unwrap_or_else(|| {
665                fallback
666                    .map(|n| n.to_string_lossy().into_owned())
667                    .unwrap_or_default()
668            });
669            if kind == ItemKind::Command {
670                // A command is named by its path under the folder, `a/b.md` being `/a:b`.
671                let rel = path.strip_prefix(dir).unwrap_or(&path).with_extension("");
672                name = rel
673                    .to_string_lossy()
674                    .replace(std::path::MAIN_SEPARATOR, ":");
675            }
676            let about = match kind {
677                ItemKind::Command => {
678                    field(&front, "description").unwrap_or_else(|| first_line(&text))
679                }
680                _ => field(&front, "description").unwrap_or_default(),
681            };
682            Item {
683                kind,
684                name,
685                about,
686                scope,
687                path,
688                line: None,
689            }
690        })
691        .collect()
692}
693
694/// Every file with `ext` under `dir`, sorted, a few folders deep.
695fn walk_files(dir: &Path, ext: &str) -> Vec<PathBuf> {
696    let mut out = Vec::new();
697    let mut stack = vec![(dir.to_path_buf(), 0)];
698    while let Some((d, depth)) = stack.pop() {
699        for entry in fs::read_dir(&d).into_iter().flatten().flatten() {
700            let path = entry.path();
701            if path.is_dir() && depth < 3 {
702                stack.push((path, depth + 1));
703            } else if path.extension().is_some_and(|e| e == ext) {
704                out.push(path);
705            }
706        }
707    }
708    out.sort();
709    out
710}
711
712fn read_json(path: &Path) -> Option<Map<String, Value>> {
713    match serde_json::from_str(&read_text(path)?).ok()? {
714        Value::Object(map) => Some(map),
715        _ => None,
716    }
717}
718
719/// The 1-based line where `needle` first shows in `text`, to open a setting where it is.
720fn line_of(text: &str, needle: &str) -> Option<usize> {
721    text.lines().position(|l| l.contains(needle)).map(|i| i + 1)
722}
723
724/// Claude Code's hooks in one settings file: one item per command, named by its event and,
725/// where it has one, what it matches.
726fn claude_hooks(path: &Path, scope: Scope) -> Vec<Item> {
727    let Some(settings) = read_json(path) else {
728        return Vec::new();
729    };
730    let text = read_text(path).unwrap_or_default();
731    let Some(Value::Object(events)) = settings.get("hooks") else {
732        return Vec::new();
733    };
734    let mut out = Vec::new();
735    for (event, groups) in events {
736        for group in groups.as_array().into_iter().flatten() {
737            let matcher = group["matcher"]
738                .as_str()
739                .filter(|m| !m.is_empty() && *m != "*");
740            for hook in group["hooks"].as_array().into_iter().flatten() {
741                let Some(command) = hook["command"].as_str() else {
742                    continue;
743                };
744                let name = match matcher {
745                    Some(m) => format!("{event} ยท {m}"),
746                    None => event.clone(),
747                };
748                let needle = serde_json::to_string(command).unwrap_or_default();
749                let needle = needle.trim_matches('"');
750                out.push(Item {
751                    kind: ItemKind::Hook,
752                    name,
753                    about: command.to_string(),
754                    scope,
755                    path: path.to_path_buf(),
756                    line: line_of(&text, needle),
757                });
758            }
759        }
760    }
761    out
762}
763
764/// MCP servers under `key` in a JSON settings file.
765fn json_servers(path: &Path, servers: Option<&Value>, scope: Scope) -> Vec<Item> {
766    let Some(Value::Object(servers)) = servers else {
767        return Vec::new();
768    };
769    let text = read_text(path).unwrap_or_default();
770    servers
771        .iter()
772        .map(|(name, server)| {
773            let about = server["url"]
774                .as_str()
775                .map(str::to_string)
776                .or_else(|| {
777                    let command = server["command"].as_str()?;
778                    let args: Vec<&str> = server["args"]
779                        .as_array()
780                        .into_iter()
781                        .flatten()
782                        .filter_map(Value::as_str)
783                        .collect();
784                    Some(
785                        std::iter::once(command)
786                            .chain(args)
787                            .collect::<Vec<_>>()
788                            .join(" "),
789                    )
790                })
791                .unwrap_or_default();
792            Item {
793                kind: ItemKind::Mcp,
794                name: name.clone(),
795                about,
796                scope,
797                path: path.to_path_buf(),
798                line: line_of(&text, &format!("\"{name}\"")),
799            }
800        })
801        .collect()
802}
803
804fn claude_items(project: &Path, homes: &Homes) -> Vec<Item> {
805    let mut items = Vec::new();
806    let local = project.join(".claude");
807    if let Some(user) = &homes.claude {
808        items.extend(markdown_items(
809            ItemKind::Skill,
810            &user.join("skills"),
811            Scope::User,
812        ));
813    }
814    items.extend(markdown_items(
815        ItemKind::Skill,
816        &local.join("skills"),
817        Scope::Project,
818    ));
819    if let Some(user) = &homes.claude {
820        items.extend(markdown_items(
821            ItemKind::Subagent,
822            &user.join("agents"),
823            Scope::User,
824        ));
825    }
826    items.extend(markdown_items(
827        ItemKind::Subagent,
828        &local.join("agents"),
829        Scope::Project,
830    ));
831    if let Some(user) = &homes.claude {
832        items.extend(markdown_items(
833            ItemKind::Command,
834            &user.join("commands"),
835            Scope::User,
836        ));
837    }
838    items.extend(markdown_items(
839        ItemKind::Command,
840        &local.join("commands"),
841        Scope::Project,
842    ));
843    if let Some(user) = &homes.claude {
844        items.extend(claude_hooks(&user.join("settings.json"), Scope::User));
845    }
846    items.extend(claude_hooks(&local.join("settings.json"), Scope::Project));
847    items.extend(claude_hooks(
848        &local.join("settings.local.json"),
849        Scope::Local,
850    ));
851    if let Some(path) = &homes.claude_json
852        && let Some(config) = read_json(path)
853    {
854        items.extend(json_servers(path, config.get("mcpServers"), Scope::User));
855        let key = project.to_string_lossy();
856        let mine = config
857            .get("projects")
858            .and_then(|p| p.get(key.as_ref()))
859            .and_then(|p| p.get("mcpServers"));
860        items.extend(json_servers(path, mine, Scope::Local));
861    }
862    let shared = project.join(".mcp.json");
863    if let Some(config) = read_json(&shared) {
864        items.extend(json_servers(
865            &shared,
866            config.get("mcpServers"),
867            Scope::Project,
868        ));
869    }
870    items
871}
872
873/// Codex reads its own `AGENTS.md`, then one per folder from the repository's top down to
874/// where it runs, an `AGENTS.override.md` in place of the `AGENTS.md` beside it, stopping once
875/// they come to `CODEX_BYTES` in all.
876fn codex_instructions(project: &Path, homes: &Homes) -> Vec<Instruction> {
877    let mut found = Vec::new();
878    if let Some(codex) = &homes.codex {
879        let over = codex.join("AGENTS.override.md");
880        let path = if over.is_file() {
881            over
882        } else {
883            codex.join("AGENTS.md")
884        };
885        found.push(Instruction::new(path, Scope::User));
886    }
887    let root = repo_root(project);
888    let mut budget = CODEX_BYTES;
889    for dir in ancestors_down(project)
890        .into_iter()
891        .filter(|d| d.starts_with(&root))
892    {
893        // Codex reads the first of the two that has something in it.
894        let over = dir.join("AGENTS.override.md");
895        let path = if fs::read_to_string(&over).is_ok_and(|t| !t.trim().is_empty()) {
896            over
897        } else {
898            dir.join("AGENTS.md")
899        };
900        let mut file = Instruction::new(path, Scope::Project);
901        if let Some(text) = &file.text {
902            if budget == 0 {
903                continue;
904            }
905            if text.len() > budget {
906                // Cut where a character ends, so a dash or a word in another script that the
907                // cut falls inside doesn't stop the reading.
908                let mut cut = budget.min(text.len());
909                while !text.is_char_boundary(cut) {
910                    cut -= 1;
911                }
912                file.limit = Some(text[..cut].lines().count());
913            }
914            budget = budget.saturating_sub(text.len());
915            found.push(file);
916        }
917    }
918    found.retain(|i| i.exists() || i.scope == Scope::User);
919    found
920}
921
922/// Names of tables under `[prefix.<name>]` in a TOML file, with their lines.
923fn toml_tables(text: &str, prefix: &str) -> Vec<(String, usize)> {
924    text.lines()
925        .enumerate()
926        .filter_map(|(i, line)| {
927            let inner = line.trim().strip_prefix('[')?.strip_suffix(']')?;
928            let name = inner.strip_prefix(prefix)?.strip_prefix('.')?;
929            (!name.contains('.')).then(|| (name.trim_matches('"').to_string(), i + 1))
930        })
931        .collect()
932}
933
934fn codex_items(homes: &Homes) -> Vec<Item> {
935    let Some(codex) = &homes.codex else {
936        return Vec::new();
937    };
938    let mut items = markdown_items(ItemKind::Skill, &codex.join("skills"), Scope::User);
939    items.extend(markdown_items(
940        ItemKind::Command,
941        &codex.join("prompts"),
942        Scope::User,
943    ));
944    let config = codex.join("config.toml");
945    if let Some(text) = read_text(&config) {
946        items.extend(
947            toml_tables(&text, "mcp_servers")
948                .into_iter()
949                .map(|(name, line)| Item {
950                    kind: ItemKind::Mcp,
951                    name,
952                    about: String::new(),
953                    scope: Scope::User,
954                    path: config.clone(),
955                    line: Some(line),
956                }),
957        );
958    }
959    items
960}
961
962/// The names Gemini CLI reads its instructions from: `context.fileName` in its settings,
963/// the project's over the user's, or `GEMINI.md`.
964pub fn gemini_names(project: &Path, homes: &Homes) -> Vec<String> {
965    let names = |path: PathBuf| -> Option<Vec<String>> {
966        let settings = read_json(&path)?;
967        match settings.get("context")?.get("fileName")? {
968            Value::String(name) => Some(vec![name.clone()]),
969            Value::Array(list) => Some(
970                list.iter()
971                    .filter_map(Value::as_str)
972                    .map(str::to_string)
973                    .collect(),
974            ),
975            _ => None,
976        }
977    };
978    names(project.join(".gemini").join("settings.json"))
979        .or_else(|| {
980            homes
981                .gemini
982                .as_ref()
983                .and_then(|g| names(g.join("settings.json")))
984        })
985        .filter(|n| !n.is_empty())
986        .unwrap_or_else(|| vec!["GEMINI.md".to_string()])
987}
988
989/// Gemini CLI reads its own file, then each folder's from the repository's top down to where
990/// it runs, then those in folders below, each followed by what it imports.
991fn gemini_instructions(project: &Path, homes: &Homes) -> Vec<Instruction> {
992    let names = gemini_names(project, homes);
993    let mut found = Vec::new();
994    if let Some(gemini) = &homes.gemini {
995        found.push(Instruction::new(gemini.join(&names[0]), Scope::User));
996        for name in &names[1..] {
997            found.push(Instruction::new(gemini.join(name), Scope::User));
998        }
999    }
1000    let root = repo_root(project);
1001    for dir in ancestors_down(project)
1002        .into_iter()
1003        .filter(|d| d.starts_with(&root))
1004    {
1005        for name in &names {
1006            found.push(Instruction::new(dir.join(name), Scope::Project));
1007        }
1008    }
1009    let refs: Vec<&str> = names.iter().map(String::as_str).collect();
1010    found.extend(
1011        nested(project, &refs)
1012            .into_iter()
1013            .map(|p| Instruction::new(p, Scope::Project)),
1014    );
1015    found.retain(|i| {
1016        i.exists()
1017            || (i.scope == Scope::User && i.path.file_name().is_some_and(|n| *n == *names[0]))
1018    });
1019    with_imports(found)
1020}
1021
1022fn gemini_items(project: &Path, homes: &Homes) -> Vec<Item> {
1023    let mut items = Vec::new();
1024    let local = project.join(".gemini");
1025    for (dir, scope) in [
1026        (homes.gemini.clone(), Scope::User),
1027        (Some(local.clone()), Scope::Project),
1028    ] {
1029        let Some(dir) = dir else { continue };
1030        for path in walk_files(&dir.join("commands"), "toml") {
1031            let text = read_text(&path).unwrap_or_default();
1032            let about = text
1033                .lines()
1034                .find_map(|l| {
1035                    l.trim()
1036                        .strip_prefix("description")?
1037                        .trim_start()
1038                        .strip_prefix('=')
1039                        .map(|v| v.trim().trim_matches('"').to_string())
1040                })
1041                .unwrap_or_default();
1042            let rel = path
1043                .strip_prefix(dir.join("commands"))
1044                .unwrap_or(&path)
1045                .with_extension("");
1046            items.push(Item {
1047                kind: ItemKind::Command,
1048                name: rel
1049                    .to_string_lossy()
1050                    .replace(std::path::MAIN_SEPARATOR, ":"),
1051                about,
1052                scope,
1053                path,
1054                line: None,
1055            });
1056        }
1057        let settings = dir.join("settings.json");
1058        if let Some(config) = read_json(&settings) {
1059            items.extend(json_servers(&settings, config.get("mcpServers"), scope));
1060        }
1061    }
1062    if let Some(gemini) = &homes.gemini {
1063        let mut extensions: Vec<PathBuf> = fs::read_dir(gemini.join("extensions"))
1064            .into_iter()
1065            .flatten()
1066            .flatten()
1067            .map(|e| e.path().join("gemini-extension.json"))
1068            .filter(|p| p.is_file())
1069            .collect();
1070        extensions.sort();
1071        for path in extensions {
1072            let config = read_json(&path).unwrap_or_default();
1073            let name = config
1074                .get("name")
1075                .and_then(Value::as_str)
1076                .map(str::to_string)
1077                .unwrap_or_else(|| {
1078                    path.parent()
1079                        .and_then(Path::file_name)
1080                        .map(|n| n.to_string_lossy().into_owned())
1081                        .unwrap_or_default()
1082                });
1083            items.push(Item {
1084                kind: ItemKind::Extension,
1085                name,
1086                about: config
1087                    .get("description")
1088                    .and_then(Value::as_str)
1089                    .unwrap_or("")
1090                    .to_string(),
1091                scope: Scope::Plugin,
1092                path: path.clone(),
1093                line: None,
1094            });
1095            items.extend(json_servers(&path, config.get("mcpServers"), Scope::Plugin));
1096        }
1097    }
1098    items
1099}
1100
1101#[cfg(test)]
1102mod tests;