Skip to main content

lean_ctx_cli/cli/
export_rules.rs

1// SPDX-License-Identifier: Apache-2.0
2use std::path::{Path, PathBuf};
3
4use lean_ctx::core::knowledge::{KnowledgeFact, ProjectKnowledge};
5
6pub fn run(args: &[String]) {
7    let format = args
8        .iter()
9        .position(|a| a == "--format")
10        .and_then(|i| args.get(i + 1))
11        .map_or("mdc", |s| s.as_str());
12
13    let root_arg = args
14        .iter()
15        .position(|a| a == "--root")
16        .and_then(|i| args.get(i + 1))
17        .map_or(".", |s| s.as_str());
18
19    let project_root = std::fs::canonicalize(root_arg).unwrap_or_else(|_| PathBuf::from(root_arg));
20    let project_root_str = project_root.to_string_lossy();
21
22    let Some(knowledge) = ProjectKnowledge::load(&project_root_str) else {
23        eprintln!("No knowledge found for project: {project_root_str}");
24        eprintln!("Run `lean-ctx` in a session first to accumulate knowledge.");
25        std::process::exit(1);
26    };
27
28    let high_confidence: Vec<&KnowledgeFact> = knowledge
29        .facts
30        .iter()
31        .filter(|f| f.confidence >= 0.6 && f.retrieval_count >= 2)
32        // V04: rule files are instructions to agents; a fact from a context
33        // package is third-party data and never becomes one. Nor does a fact
34        // pulled from Cloud: other members' text is data (X5).
35        .filter(|f| f.package_origin().is_none() && f.cloud_origin().is_none())
36        .collect();
37
38    if high_confidence.is_empty() {
39        eprintln!(
40            "No high-confidence knowledge facts found (need confidence >= 0.6 and at least 2 retrievals)."
41        );
42        std::process::exit(0);
43    }
44
45    match format {
46        "mdc" => export_mdc(&high_confidence, &project_root),
47        "agents-md" => export_marked(
48            &high_confidence,
49            &project_root,
50            "AGENTS.md",
51            "Project Knowledge",
52        ),
53        "claude-md" => {
54            export_marked(
55                &high_confidence,
56                &project_root,
57                "CLAUDE.md",
58                "Project Rules",
59            );
60        }
61        "codebuddy-md" => export_marked(
62            &high_confidence,
63            &project_root,
64            "CODEBUDDY.md",
65            "Project Rules",
66        ),
67        _ => {
68            eprintln!(
69                "Unknown format: {format}. Supported: mdc, agents-md, claude-md, codebuddy-md"
70            );
71            std::process::exit(1);
72        }
73    }
74}
75
76const MARKER_START: &str = "<!-- lean-ctx-knowledge-start -->";
77const MARKER_END: &str = "<!-- lean-ctx-knowledge-end -->";
78/// Mode of a rule file this command creates (the umask still applies).
79const NEW_FILE_MODE: u32 = 0o644;
80
81fn export_mdc(facts: &[&KnowledgeFact], project_root: &Path) {
82    let rel = Path::new(".cursor/rules/lean-ctx-knowledge.mdc");
83    let content = build_mdc_content(facts);
84    let mode = match existing_rule_file(project_root, rel) {
85        Ok(existing) => existing.map_or(NEW_FILE_MODE, |(_, mode)| mode),
86        Err(e) => return eprintln!("Error writing {}: {e}", project_root.join(rel).display()),
87    };
88    match write_rule_file(project_root, rel, &content, mode) {
89        Ok(path) => println!("Exported {} rules to {}", facts.len(), path.display()),
90        Err(e) => eprintln!("Error writing {}: {e}", project_root.join(rel).display()),
91    }
92}
93
94/// Write the knowledge section between its markers in `file_name` at the
95/// project root, creating the file with `title` when it does not exist.
96fn export_marked(facts: &[&KnowledgeFact], project_root: &Path, file_name: &str, title: &str) {
97    let rel = Path::new(file_name);
98    let shown = project_root.join(rel);
99    let section = build_agents_section(facts);
100    let (content, mode, created) = match existing_rule_file(project_root, rel) {
101        Ok(Some((existing, mode))) => (upsert_section(&existing, &section), mode, false),
102        Ok(None) => (
103            format!(
104                "# {title} (auto-generated by lean-ctx)\n\n{MARKER_START}\n{section}\n{MARKER_END}\n"
105            ),
106            NEW_FILE_MODE,
107            true,
108        ),
109        Err(e) => return eprintln!("Error writing {}: {e}", shown.display()),
110    };
111    match write_rule_file(project_root, rel, &content, mode) {
112        Ok(path) if created => println!("Created {} with {} rules", path.display(), facts.len()),
113        Ok(path) => println!("Updated {} rules in {}", facts.len(), path.display()),
114        Err(e) => eprintln!("Error writing {}: {e}", shown.display()),
115    }
116}
117
118fn upsert_section(existing: &str, section: &str) -> String {
119    if existing.contains(MARKER_START) {
120        let before = existing.split(MARKER_START).next().unwrap_or("");
121        let after = existing.split(MARKER_END).nth(1).unwrap_or("");
122        format!("{before}{MARKER_START}\n{section}\n{MARKER_END}{after}")
123    } else {
124        format!("{existing}\n\n{MARKER_START}\n{section}\n{MARKER_END}\n")
125    }
126}
127
128/// The rule file's current text and permission bits, `None` when it does not
129/// exist yet.
130///
131/// Rule files live in the working tree, which a cloned repository populates:
132/// a symlinked `AGENTS.md`, `.cursor` or `.cursor/rules` must neither be read
133/// into the project nor carry the write to a file outside it
134/// (GHSA-mq5c-rjv9-2fc3). Every component below the root is checked here and
135/// again by the confined write.
136fn existing_rule_file(project_root: &Path, rel: &Path) -> Result<Option<(String, u32)>, String> {
137    let path = lean_ctx::core::pathjail_write::rebuild_below(project_root, rel)?;
138    let meta = match std::fs::symlink_metadata(&path) {
139        Ok(meta) => meta,
140        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
141        Err(e) => return Err(e.to_string()),
142    };
143    if !meta.is_file() {
144        return Err(format!("{} is not a regular file", path.display()));
145    }
146    let text = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;
147    Ok(Some((text, file_mode(&meta))))
148}
149
150#[cfg(unix)]
151fn file_mode(meta: &std::fs::Metadata) -> u32 {
152    use std::os::unix::fs::PermissionsExt;
153    meta.permissions().mode() & 0o777
154}
155
156#[cfg(not(unix))]
157fn file_mode(_meta: &std::fs::Metadata) -> u32 {
158    NEW_FILE_MODE
159}
160
161fn write_rule_file(
162    project_root: &Path,
163    rel: &Path,
164    content: &str,
165    mode: u32,
166) -> Result<PathBuf, String> {
167    lean_ctx::core::pathjail_write::write_below(project_root, rel, content.as_bytes(), mode)
168}
169
170fn build_mdc_content(facts: &[&KnowledgeFact]) -> String {
171    let mut out = String::from(
172        "---\ndescription: \"Project knowledge (auto-generated by lean-ctx export-rules)\"\n\
173         globs: \"**/*\"\nalwaysApply: true\n---\n\n\
174         # Project Knowledge\n\n",
175    );
176
177    let mut by_category: std::collections::BTreeMap<&str, Vec<&&KnowledgeFact>> =
178        std::collections::BTreeMap::new();
179
180    for fact in facts {
181        by_category.entry(&fact.category).or_default().push(fact);
182    }
183
184    for (category, cat_facts) in &by_category {
185        out.push_str(&format!("## {category}\n\n"));
186        for fact in cat_facts {
187            out.push_str(&format!("- **{}**: {}\n", fact.key, fact.value));
188        }
189        out.push('\n');
190    }
191
192    out
193}
194
195fn build_agents_section(facts: &[&KnowledgeFact]) -> String {
196    let mut out = String::from("## Project Knowledge (lean-ctx)\n\n");
197
198    let mut by_category: std::collections::BTreeMap<&str, Vec<&&KnowledgeFact>> =
199        std::collections::BTreeMap::new();
200
201    for fact in facts {
202        by_category.entry(&fact.category).or_default().push(fact);
203    }
204
205    for (category, cat_facts) in &by_category {
206        out.push_str(&format!("### {category}\n\n"));
207        for fact in cat_facts {
208            out.push_str(&format!("- **{}**: {}\n", fact.key, fact.value));
209        }
210        out.push('\n');
211    }
212
213    out.trim_end().to_string()
214}
215
216#[cfg(all(test, unix))]
217mod tests {
218    use super::*;
219    use std::os::unix::fs::{PermissionsExt, symlink};
220
221    fn project() -> (tempfile::TempDir, PathBuf, PathBuf) {
222        let tmp = tempfile::tempdir().unwrap();
223        let root = tmp.path().join("proj");
224        let outside = tmp.path().join("outside");
225        std::fs::create_dir_all(&root).unwrap();
226        std::fs::create_dir_all(&outside).unwrap();
227        (tmp, root, outside)
228    }
229
230    /// A cloned repository ships `AGENTS.md` as a link to a file outside it:
231    /// the export neither reads that file nor writes through the link.
232    #[test]
233    fn a_symlinked_rule_file_is_not_followed() {
234        let (_tmp, root, outside) = project();
235        let victim = outside.join("rc");
236        std::fs::write(&victim, "keep\n").unwrap();
237        symlink(&victim, root.join("AGENTS.md")).unwrap();
238        // A dangling link, too: it would create the file outside.
239        symlink(outside.join("new"), root.join("CLAUDE.md")).unwrap();
240
241        export_marked(&[], &root, "AGENTS.md", "Project Knowledge");
242        export_marked(&[], &root, "CLAUDE.md", "Project Rules");
243
244        assert_eq!(std::fs::read_to_string(&victim).unwrap(), "keep\n");
245        assert!(!outside.join("new").exists());
246        assert!(
247            std::fs::symlink_metadata(root.join("AGENTS.md"))
248                .unwrap()
249                .file_type()
250                .is_symlink()
251        );
252    }
253
254    /// A symlinked `.cursor` directory must not carry the `.mdc` file out.
255    #[test]
256    fn a_symlinked_rules_directory_is_not_followed() {
257        let (_tmp, root, outside) = project();
258        symlink(&outside, root.join(".cursor")).unwrap();
259        export_mdc(&[], &root);
260        assert!(!outside.join("rules").exists());
261    }
262
263    #[test]
264    fn a_plain_rule_file_gets_the_section_and_keeps_its_mode() {
265        let (_tmp, root, _outside) = project();
266        let file = root.join("AGENTS.md");
267        std::fs::write(&file, "# Mine\n").unwrap();
268        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o700)).unwrap();
269
270        export_marked(&[], &root, "AGENTS.md", "Project Knowledge");
271
272        let text = std::fs::read_to_string(&file).unwrap();
273        assert!(text.starts_with("# Mine\n"), "{text}");
274        assert!(
275            text.contains(MARKER_START) && text.contains(MARKER_END),
276            "{text}"
277        );
278        assert_eq!(
279            std::fs::metadata(&file).unwrap().permissions().mode() & 0o777,
280            0o700
281        );
282
283        export_mdc(&[], &root);
284        assert!(root.join(".cursor/rules/lean-ctx-knowledge.mdc").is_file());
285    }
286}