lean-ctx 3.12.12

LeanCTX | OSS: the open-source runtime for the Context Gateway for AI agents. CLI, MCP server, and supported proxy integrations.
Documentation
// SPDX-License-Identifier: Apache-2.0
use std::path::{Path, PathBuf};

use lean_ctx::core::knowledge::{KnowledgeFact, ProjectKnowledge};

pub fn run(args: &[String]) {
    let format = args
        .iter()
        .position(|a| a == "--format")
        .and_then(|i| args.get(i + 1))
        .map_or("mdc", |s| s.as_str());

    let root_arg = args
        .iter()
        .position(|a| a == "--root")
        .and_then(|i| args.get(i + 1))
        .map_or(".", |s| s.as_str());

    let project_root = std::fs::canonicalize(root_arg).unwrap_or_else(|_| PathBuf::from(root_arg));
    let project_root_str = project_root.to_string_lossy();

    let Some(knowledge) = ProjectKnowledge::load(&project_root_str) else {
        eprintln!("No knowledge found for project: {project_root_str}");
        eprintln!("Run `lean-ctx` in a session first to accumulate knowledge.");
        std::process::exit(1);
    };

    let high_confidence: Vec<&KnowledgeFact> = knowledge
        .facts
        .iter()
        .filter(|f| f.confidence >= 0.6 && f.retrieval_count >= 2)
        // V04: rule files are instructions to agents; a fact from a context
        // package is third-party data and never becomes one. Nor does a fact
        // pulled from Cloud: other members' text is data (X5).
        .filter(|f| f.package_origin().is_none() && f.cloud_origin().is_none())
        .collect();

    if high_confidence.is_empty() {
        eprintln!(
            "No high-confidence knowledge facts found (need confidence >= 0.6 and at least 2 retrievals)."
        );
        std::process::exit(0);
    }

    match format {
        "mdc" => export_mdc(&high_confidence, &project_root),
        "agents-md" => export_marked(
            &high_confidence,
            &project_root,
            "AGENTS.md",
            "Project Knowledge",
        ),
        "claude-md" => {
            export_marked(
                &high_confidence,
                &project_root,
                "CLAUDE.md",
                "Project Rules",
            );
        }
        "codebuddy-md" => export_marked(
            &high_confidence,
            &project_root,
            "CODEBUDDY.md",
            "Project Rules",
        ),
        _ => {
            eprintln!(
                "Unknown format: {format}. Supported: mdc, agents-md, claude-md, codebuddy-md"
            );
            std::process::exit(1);
        }
    }
}

const MARKER_START: &str = "<!-- lean-ctx-knowledge-start -->";
const MARKER_END: &str = "<!-- lean-ctx-knowledge-end -->";
/// Mode of a rule file this command creates (the umask still applies).
const NEW_FILE_MODE: u32 = 0o644;

fn export_mdc(facts: &[&KnowledgeFact], project_root: &Path) {
    let rel = Path::new(".cursor/rules/lean-ctx-knowledge.mdc");
    let content = build_mdc_content(facts);
    let mode = match existing_rule_file(project_root, rel) {
        Ok(existing) => existing.map_or(NEW_FILE_MODE, |(_, mode)| mode),
        Err(e) => return eprintln!("Error writing {}: {e}", project_root.join(rel).display()),
    };
    match write_rule_file(project_root, rel, &content, mode) {
        Ok(path) => println!("Exported {} rules to {}", facts.len(), path.display()),
        Err(e) => eprintln!("Error writing {}: {e}", project_root.join(rel).display()),
    }
}

/// Write the knowledge section between its markers in `file_name` at the
/// project root, creating the file with `title` when it does not exist.
fn export_marked(facts: &[&KnowledgeFact], project_root: &Path, file_name: &str, title: &str) {
    let rel = Path::new(file_name);
    let shown = project_root.join(rel);
    let section = build_agents_section(facts);
    let (content, mode, created) = match existing_rule_file(project_root, rel) {
        Ok(Some((existing, mode))) => (upsert_section(&existing, &section), mode, false),
        Ok(None) => (
            format!(
                "# {title} (auto-generated by lean-ctx)\n\n{MARKER_START}\n{section}\n{MARKER_END}\n"
            ),
            NEW_FILE_MODE,
            true,
        ),
        Err(e) => return eprintln!("Error writing {}: {e}", shown.display()),
    };
    match write_rule_file(project_root, rel, &content, mode) {
        Ok(path) if created => println!("Created {} with {} rules", path.display(), facts.len()),
        Ok(path) => println!("Updated {} rules in {}", facts.len(), path.display()),
        Err(e) => eprintln!("Error writing {}: {e}", shown.display()),
    }
}

fn upsert_section(existing: &str, section: &str) -> String {
    if existing.contains(MARKER_START) {
        let before = existing.split(MARKER_START).next().unwrap_or("");
        let after = existing.split(MARKER_END).nth(1).unwrap_or("");
        format!("{before}{MARKER_START}\n{section}\n{MARKER_END}{after}")
    } else {
        format!("{existing}\n\n{MARKER_START}\n{section}\n{MARKER_END}\n")
    }
}

/// The rule file's current text and permission bits, `None` when it does not
/// exist yet.
///
/// Rule files live in the working tree, which a cloned repository populates:
/// a symlinked `AGENTS.md`, `.cursor` or `.cursor/rules` must neither be read
/// into the project nor carry the write to a file outside it
/// (GHSA-mq5c-rjv9-2fc3). Every component below the root is checked here and
/// again by the confined write.
fn existing_rule_file(project_root: &Path, rel: &Path) -> Result<Option<(String, u32)>, String> {
    let path = lean_ctx::core::pathjail_write::rebuild_below(project_root, rel)?;
    let meta = match std::fs::symlink_metadata(&path) {
        Ok(meta) => meta,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(e.to_string()),
    };
    if !meta.is_file() {
        return Err(format!("{} is not a regular file", path.display()));
    }
    let text = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;
    Ok(Some((text, file_mode(&meta))))
}

#[cfg(unix)]
fn file_mode(meta: &std::fs::Metadata) -> u32 {
    use std::os::unix::fs::PermissionsExt;
    meta.permissions().mode() & 0o777
}

#[cfg(not(unix))]
fn file_mode(_meta: &std::fs::Metadata) -> u32 {
    NEW_FILE_MODE
}

fn write_rule_file(
    project_root: &Path,
    rel: &Path,
    content: &str,
    mode: u32,
) -> Result<PathBuf, String> {
    lean_ctx::core::pathjail_write::write_below(project_root, rel, content.as_bytes(), mode)
}

fn build_mdc_content(facts: &[&KnowledgeFact]) -> String {
    let mut out = String::from(
        "---\ndescription: \"Project knowledge (auto-generated by lean-ctx export-rules)\"\n\
         globs: \"**/*\"\nalwaysApply: true\n---\n\n\
         # Project Knowledge\n\n",
    );

    let mut by_category: std::collections::BTreeMap<&str, Vec<&&KnowledgeFact>> =
        std::collections::BTreeMap::new();

    for fact in facts {
        by_category.entry(&fact.category).or_default().push(fact);
    }

    for (category, cat_facts) in &by_category {
        out.push_str(&format!("## {category}\n\n"));
        for fact in cat_facts {
            out.push_str(&format!("- **{}**: {}\n", fact.key, fact.value));
        }
        out.push('\n');
    }

    out
}

fn build_agents_section(facts: &[&KnowledgeFact]) -> String {
    let mut out = String::from("## Project Knowledge (lean-ctx)\n\n");

    let mut by_category: std::collections::BTreeMap<&str, Vec<&&KnowledgeFact>> =
        std::collections::BTreeMap::new();

    for fact in facts {
        by_category.entry(&fact.category).or_default().push(fact);
    }

    for (category, cat_facts) in &by_category {
        out.push_str(&format!("### {category}\n\n"));
        for fact in cat_facts {
            out.push_str(&format!("- **{}**: {}\n", fact.key, fact.value));
        }
        out.push('\n');
    }

    out.trim_end().to_string()
}

#[cfg(all(test, unix))]
mod tests {
    use super::*;
    use std::os::unix::fs::{PermissionsExt, symlink};

    fn project() -> (tempfile::TempDir, PathBuf, PathBuf) {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("proj");
        let outside = tmp.path().join("outside");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::create_dir_all(&outside).unwrap();
        (tmp, root, outside)
    }

    /// A cloned repository ships `AGENTS.md` as a link to a file outside it:
    /// the export neither reads that file nor writes through the link.
    #[test]
    fn a_symlinked_rule_file_is_not_followed() {
        let (_tmp, root, outside) = project();
        let victim = outside.join("rc");
        std::fs::write(&victim, "keep\n").unwrap();
        symlink(&victim, root.join("AGENTS.md")).unwrap();
        // A dangling link, too: it would create the file outside.
        symlink(outside.join("new"), root.join("CLAUDE.md")).unwrap();

        export_marked(&[], &root, "AGENTS.md", "Project Knowledge");
        export_marked(&[], &root, "CLAUDE.md", "Project Rules");

        assert_eq!(std::fs::read_to_string(&victim).unwrap(), "keep\n");
        assert!(!outside.join("new").exists());
        assert!(
            std::fs::symlink_metadata(root.join("AGENTS.md"))
                .unwrap()
                .file_type()
                .is_symlink()
        );
    }

    /// A symlinked `.cursor` directory must not carry the `.mdc` file out.
    #[test]
    fn a_symlinked_rules_directory_is_not_followed() {
        let (_tmp, root, outside) = project();
        symlink(&outside, root.join(".cursor")).unwrap();
        export_mdc(&[], &root);
        assert!(!outside.join("rules").exists());
    }

    #[test]
    fn a_plain_rule_file_gets_the_section_and_keeps_its_mode() {
        let (_tmp, root, _outside) = project();
        let file = root.join("AGENTS.md");
        std::fs::write(&file, "# Mine\n").unwrap();
        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o700)).unwrap();

        export_marked(&[], &root, "AGENTS.md", "Project Knowledge");

        let text = std::fs::read_to_string(&file).unwrap();
        assert!(text.starts_with("# Mine\n"), "{text}");
        assert!(
            text.contains(MARKER_START) && text.contains(MARKER_END),
            "{text}"
        );
        assert_eq!(
            std::fs::metadata(&file).unwrap().permissions().mode() & 0o777,
            0o700
        );

        export_mdc(&[], &root);
        assert!(root.join(".cursor/rules/lean-ctx-knowledge.mdc").is_file());
    }
}