atomr-agents-coding-cli-vendor-codex 0.21.0

OpenAI Codex CLI adapter for the coding-cli harness: `codex exec` headless invocation + AGENTS.md projection.
Documentation
//! One-way projection: atomr concepts → Codex on-disk config.

use std::path::Path;

use tokio::fs;

use atomr_agents_coding_cli_core::{
    ConceptProjection, MapperError, PersonaSnapshot, SkillSnapshot, ToolSetSnapshot,
};

pub async fn materialize(projection: &ConceptProjection, workdir: &Path) -> Result<(), MapperError> {
    write_agents_md(projection, workdir).await?;
    write_mcp_toml(&projection.toolsets, workdir).await?;
    Ok(())
}

async fn write_agents_md(p: &ConceptProjection, workdir: &Path) -> Result<(), MapperError> {
    let body = compose_agents_md(p.persona.as_ref(), p.project_memory.as_deref(), &p.skills);
    let path = workdir.join("AGENTS.md");
    write_file(&path, body.as_bytes()).await
}

fn compose_agents_md(
    persona: Option<&PersonaSnapshot>,
    project_memory: Option<&str>,
    skills: &[SkillSnapshot],
) -> String {
    let mut out = String::new();
    out.push_str("# AGENTS.md\n\n");
    out.push_str("<!-- Generated by atomr-agents-coding-cli-harness. Do not edit by hand. -->\n\n");
    if let Some(p) = persona {
        out.push_str("## Identity\n\n");
        out.push_str(&p.identity);
        if !p.identity.ends_with('\n') {
            out.push('\n');
        }
        if !p.salient_traits.is_empty() {
            out.push_str("\n### Salient traits\n\n");
            for t in &p.salient_traits {
                out.push_str("- ");
                out.push_str(t);
                out.push('\n');
            }
        }
        if let Some(tone) = &p.style_tone {
            out.push_str("\n### Style / tone\n\n");
            out.push_str(tone);
            out.push('\n');
        }
        out.push('\n');
    }
    if let Some(mem) = project_memory {
        out.push_str("## Project memory\n\n");
        out.push_str(mem);
        if !mem.ends_with('\n') {
            out.push('\n');
        }
        out.push('\n');
    }
    if !skills.is_empty() {
        out.push_str("## Skills\n\n");
        out.push_str("Codex lacks a native skill registry, so each skill is inlined below.\n\n");
        for s in skills {
            out.push_str(&format!("### {} (priority {})\n\n", s.name, s.priority));
            if !s.keywords.is_empty() {
                out.push_str("Keywords: ");
                out.push_str(&s.keywords.join(", "));
                out.push_str("\n\n");
            }
            if !s.tools.is_empty() {
                out.push_str("Tools: ");
                out.push_str(&s.tools.join(", "));
                out.push_str("\n\n");
            }
            out.push_str(&s.instruction_fragment);
            if !s.instruction_fragment.ends_with('\n') {
                out.push('\n');
            }
            out.push('\n');
        }
    }
    out
}

async fn write_mcp_toml(toolsets: &[ToolSetSnapshot], workdir: &Path) -> Result<(), MapperError> {
    if toolsets.iter().all(|t| t.mcp_servers.is_empty()) {
        return Ok(());
    }
    let dir = workdir.join(".codex");
    fs::create_dir_all(&dir)
        .await
        .map_err(|e| MapperError::io(dir.display().to_string(), e))?;
    let mut toml = String::from("# Generated by atomr-agents-coding-cli-harness.\n");
    for ts in toolsets {
        for s in &ts.mcp_servers {
            toml.push_str(&format!("\n[mcp_servers.{}]\n", s.name));
            toml.push_str(&format!("command = {:?}\n", s.command));
            let args = s
                .args
                .iter()
                .map(|a| format!("{a:?}"))
                .collect::<Vec<_>>()
                .join(", ");
            toml.push_str(&format!("args = [{args}]\n"));
            if !s.env.is_empty() {
                toml.push_str("env = {\n");
                for (k, v) in &s.env {
                    toml.push_str(&format!("  {k:?} = {v:?},\n"));
                }
                toml.push_str("}\n");
            }
        }
    }
    let path = dir.join("config.toml");
    write_file(&path, toml.as_bytes()).await
}

async fn write_file(path: &Path, body: &[u8]) -> Result<(), MapperError> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .await
            .map_err(|e| MapperError::io(parent.display().to_string(), e))?;
    }
    fs::write(path, body)
        .await
        .map_err(|e| MapperError::io(path.display().to_string(), e))
}

#[cfg(test)]
mod tests {
    use super::*;
    use atomr_agents_coding_cli_core::{
        McpServerSnapshot, PersonaSnapshot, SkillSnapshot, ToolSetSnapshot,
    };
    use tempfile::TempDir;

    #[tokio::test]
    async fn materializes_agents_md_and_mcp() {
        let dir = TempDir::new().unwrap();
        let p = ConceptProjection {
            persona: Some(PersonaSnapshot {
                identity: "Codex backend hardener.".into(),
                salient_traits: vec!["paranoid".into()],
                style_tone: None,
            }),
            skills: vec![SkillSnapshot {
                id: "audit".into(),
                name: "Audit".into(),
                instruction_fragment: "Look for unsafe blocks.".into(),
                keywords: vec!["safety".into()],
                priority: 9,
                tools: vec!["Grep".into()],
            }],
            toolsets: vec![ToolSetSnapshot {
                id: "linear".into(),
                mcp_servers: vec![McpServerSnapshot {
                    name: "linear".into(),
                    command: "npx".into(),
                    args: vec!["@linear/mcp".into()],
                    env: Default::default(),
                }],
                tool_names: vec![],
            }],
            policy: Default::default(),
            project_memory: Some("Shard by tenant id.".into()),
        };
        materialize(&p, dir.path()).await.unwrap();
        let agents = std::fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
        assert!(agents.contains("Codex backend hardener"));
        assert!(agents.contains("### Audit (priority 9)"));
        assert!(agents.contains("Shard by tenant id"));
        let toml = std::fs::read_to_string(dir.path().join(".codex/config.toml")).unwrap();
        assert!(toml.contains("[mcp_servers.linear]"));
        assert!(toml.contains("command = \"npx\""));
    }
}