Skip to main content

ask/
agents.rs

1//! `AGENTS.md` generation — maintains the `<!-- BEGIN:ask-docs-auto-generated -->`
2//! block and a `@AGENTS.md` reference in `CLAUDE.md`. Rust port of `agents.ts`.
3
4use std::path::Path;
5
6const BEGIN_MARKER: &str = "<!-- BEGIN:ask-docs-auto-generated -->";
7const END_MARKER: &str = "<!-- END:ask-docs-auto-generated -->";
8
9/// A library to render into the AGENTS.md docs block.
10#[derive(Debug, Clone)]
11pub struct LazyLibraryInfo {
12    pub name: String,
13    pub version: String,
14    pub spec: String,
15}
16
17/// Regenerate the ask-docs block in `AGENTS.md`. With no libraries, strips a
18/// previously generated block (removing the file if it becomes empty). Returns
19/// the AGENTS.md path (empty string when the file was left absent/untouched).
20pub fn generate_agents_md(
21    project_dir: &Path,
22    libraries: &[LazyLibraryInfo],
23) -> anyhow::Result<String> {
24    let agents_path = project_dir.join("AGENTS.md");
25
26    if libraries.is_empty() {
27        strip_block(project_dir, &agents_path)?;
28        return Ok(String::new());
29    }
30
31    let sections: Vec<String> = libraries
32        .iter()
33        .map(|lib| {
34            let major = lib.version.split('.').next().unwrap_or(&lib.version);
35            let name = &lib.name;
36            let version = &lib.version;
37            format!(
38                "## {name} v{version}\n\n\
39                 > **WARNING:** This version may differ from your training data.\n\
40                 > Use `ask docs {name}` to read the documentation before writing any {name}-related code.\n\
41                 > Heed deprecation notices and breaking changes.\n\n\
42                 - **Version**: `{version}` — use `\"^{major}\"` in package.json (NOT older major versions)\n\
43                 - **Docs**: `ask docs {name}` — prints documentation paths (lazy fetch on first use)\n\
44                 - **Source**: `ask src {name}` — prints the cached source tree path"
45            )
46        })
47        .collect();
48
49    let generated_block = format!(
50        "{BEGIN_MARKER}\n\
51         # Documentation References\n\n\
52         The libraries in this project may have APIs and patterns that differ from your training data.\n\
53         **Always read the relevant documentation before writing code.**\n\n\
54         ## Accessing Library Documentation\n\n\
55         Use the lazy commands `ask src <package>` and `ask docs <package>` to access\n\
56         documentation on-demand. They print absolute paths to the cached source tree\n\
57         (and any `*doc*` directories), with automatic fetch on cache miss:\n\n\
58         ```bash\n\
59         rg \"pattern\" $(ask src <package>)\n\
60         cat \"$(ask src <package>)/README.md\"\n\
61         fd \"\\.md$\" \"$(ask docs <package> | head -n 1)\"\n\
62         ```\n\n\
63         {}\n\
64         {END_MARKER}",
65        sections.join("\n\n")
66    );
67
68    if let Ok(existing) = std::fs::read_to_string(&agents_path) {
69        match (existing.find(BEGIN_MARKER), existing.find(END_MARKER)) {
70            (Some(begin), Some(end)) => {
71                let updated = format!(
72                    "{}{generated_block}{}",
73                    &existing[..begin],
74                    &existing[end + END_MARKER.len()..]
75                );
76                std::fs::write(&agents_path, updated)?;
77            }
78            _ => {
79                std::fs::write(
80                    &agents_path,
81                    format!("{}\n\n{generated_block}\n", existing.trim_end()),
82                )?;
83            }
84        }
85    } else {
86        std::fs::write(&agents_path, format!("{generated_block}\n"))?;
87    }
88
89    update_claude_md(project_dir)?;
90    Ok(agents_path.to_string_lossy().into_owned())
91}
92
93/// Strip a previously generated block for the empty-libraries case.
94fn strip_block(project_dir: &Path, agents_path: &Path) -> anyhow::Result<()> {
95    let Ok(existing) = std::fs::read_to_string(agents_path) else {
96        return Ok(());
97    };
98    match (existing.find(BEGIN_MARKER), existing.find(END_MARKER)) {
99        (Some(begin), Some(end)) => {
100            let head = existing[..begin].trim_end_matches('\n');
101            let tail = existing[end + END_MARKER.len()..].trim_start_matches('\n');
102            let stripped = if head.is_empty() {
103                tail.to_string()
104            } else if tail.is_empty() {
105                format!("{head}\n")
106            } else {
107                format!("{head}\n\n{tail}")
108            };
109            if stripped.is_empty() {
110                std::fs::remove_file(agents_path)?;
111            } else {
112                std::fs::write(agents_path, stripped)?;
113            }
114        }
115        (Some(_), None) | (None, Some(_)) => {
116            // Unmatched marker — likely hand-edited/truncated. Leave it for the
117            // user to repair rather than emitting further corruption.
118            let rel = agents_path.strip_prefix(project_dir).unwrap_or(agents_path);
119            eprintln!(
120                "  Warning: {} has an unmatched ask-docs marker — leaving file untouched. Inspect \
121                 manually to restore the BEGIN/END pair.",
122                rel.display()
123            );
124        }
125        (None, None) => {}
126    }
127    Ok(())
128}
129
130/// Ensure `CLAUDE.md` references `@AGENTS.md`.
131fn update_claude_md(project_dir: &Path) -> anyhow::Result<()> {
132    let claude_path = project_dir.join("CLAUDE.md");
133    let claude_ref = "@AGENTS.md";
134    match std::fs::read_to_string(&claude_path) {
135        Ok(content) if content.contains(claude_ref) => {}
136        Ok(content) => {
137            std::fs::write(
138                &claude_path,
139                format!("{}\n{claude_ref}\n", content.trim_end()),
140            )?;
141        }
142        Err(_) => {
143            std::fs::write(&claude_path, format!("{claude_ref}\n"))?;
144        }
145    }
146    Ok(())
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    fn lib(name: &str, version: &str) -> LazyLibraryInfo {
154        LazyLibraryInfo {
155            name: name.into(),
156            version: version.into(),
157            spec: format!("npm:{name}"),
158        }
159    }
160
161    #[test]
162    fn generates_block_and_claude_ref() {
163        let dir = tempfile::tempdir().unwrap();
164        let path = generate_agents_md(dir.path(), &[lib("next", "15.0.3")]).unwrap();
165        assert!(!path.is_empty());
166        let content = std::fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
167        assert!(content.starts_with(BEGIN_MARKER));
168        assert!(content.contains("## next v15.0.3"));
169        assert!(content.contains(r#"use `"^15"`"#));
170        assert!(content.trim_end().ends_with(END_MARKER));
171        // CLAUDE.md gets the reference.
172        assert_eq!(
173            std::fs::read_to_string(dir.path().join("CLAUDE.md")).unwrap(),
174            "@AGENTS.md\n"
175        );
176    }
177
178    #[test]
179    fn replaces_existing_block_preserving_surrounding_text() {
180        let dir = tempfile::tempdir().unwrap();
181        std::fs::write(
182            dir.path().join("AGENTS.md"),
183            format!("# My Project\n\nIntro.\n\n{BEGIN_MARKER}\nold\n{END_MARKER}\n\n## Footer\n"),
184        )
185        .unwrap();
186        generate_agents_md(dir.path(), &[lib("vue", "3.4.0")]).unwrap();
187        let content = std::fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
188        assert!(content.starts_with("# My Project"));
189        assert!(content.contains("## Footer"));
190        assert!(content.contains("## vue v3.4.0"));
191        assert!(!content.contains("\nold\n"));
192    }
193
194    #[test]
195    fn appends_block_when_no_markers_present() {
196        let dir = tempfile::tempdir().unwrap();
197        std::fs::write(dir.path().join("AGENTS.md"), "# Existing\n").unwrap();
198        generate_agents_md(dir.path(), &[lib("next", "1.0.0")]).unwrap();
199        let content = std::fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
200        assert!(content.starts_with("# Existing"));
201        assert!(content.contains(BEGIN_MARKER));
202    }
203
204    #[test]
205    fn empty_libraries_strips_block() {
206        let dir = tempfile::tempdir().unwrap();
207        std::fs::write(
208            dir.path().join("AGENTS.md"),
209            format!("# Head\n\n{BEGIN_MARKER}\nx\n{END_MARKER}\n\n## Tail\n"),
210        )
211        .unwrap();
212        let result = generate_agents_md(dir.path(), &[]).unwrap();
213        assert_eq!(result, "");
214        let content = std::fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
215        assert_eq!(content, "# Head\n\n## Tail\n");
216        assert!(!content.contains(BEGIN_MARKER));
217    }
218
219    #[test]
220    fn empty_libraries_removes_file_when_block_was_all() {
221        let dir = tempfile::tempdir().unwrap();
222        std::fs::write(
223            dir.path().join("AGENTS.md"),
224            format!("{BEGIN_MARKER}\nx\n{END_MARKER}"),
225        )
226        .unwrap();
227        generate_agents_md(dir.path(), &[]).unwrap();
228        assert!(!dir.path().join("AGENTS.md").exists());
229    }
230
231    #[test]
232    fn does_not_duplicate_claude_ref() {
233        let dir = tempfile::tempdir().unwrap();
234        std::fs::write(dir.path().join("CLAUDE.md"), "# Rules\n@AGENTS.md\n").unwrap();
235        generate_agents_md(dir.path(), &[lib("next", "1.0.0")]).unwrap();
236        let content = std::fs::read_to_string(dir.path().join("CLAUDE.md")).unwrap();
237        assert_eq!(content.matches("@AGENTS.md").count(), 1);
238    }
239}