codive-prompts 0.1.0

Prompt management system for Codive
Documentation
//! File-based prompt loading and overrides

use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

use thiserror::Error;
use tracing::{debug, warn};

use crate::prompts::EmbeddedPrompts;
use crate::ProviderFamily;

#[derive(Debug, Error)]
pub enum LoaderError {
    #[error("Failed to read file {path}: {source}")]
    ReadError {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error("Override directory does not exist: {0}")]
    DirectoryNotFound(PathBuf),
}

/// Stores prompts with support for file-based overrides
#[derive(Debug, Clone)]
pub struct PromptStore {
    /// Embedded prompts compiled into the binary
    embedded: EmbeddedPrompts,

    /// Runtime overrides loaded from files
    overrides: PromptOverrides,
}

#[derive(Debug, Clone, Default)]
struct PromptOverrides {
    base: Option<String>,
    verification: Option<String>,
    providers: HashMap<ProviderFamily, String>,
    tools: HashMap<String, String>,
}

impl PromptStore {
    /// Create a new PromptStore with only embedded defaults
    pub fn new() -> Self {
        Self {
            embedded: EmbeddedPrompts::load(),
            overrides: PromptOverrides::default(),
        }
    }

    /// Load overrides from a directory
    ///
    /// Directory structure:
    /// ```text
    /// prompts/
    /// ├── base.txt
    /// ├── verification.txt
    /// ├── providers/
    /// │   ├── anthropic.txt
    /// │   ├── openai.txt
    /// │   └── gemini.txt
    /// └── tools/
    ///     ├── bash.txt
    ///     ├── read_file.txt
    ///     └── ...
    /// ```
    pub fn with_overrides_dir(mut self, dir: &Path) -> Result<Self, LoaderError> {
        if !dir.exists() {
            return Err(LoaderError::DirectoryNotFound(dir.to_path_buf()));
        }

        debug!("Loading prompt overrides from: {}", dir.display());

        // Load base override
        let base_path = dir.join("base.txt");
        if base_path.exists() {
            self.overrides.base = Some(read_file(&base_path)?);
            debug!("Loaded base override");
        }

        // Load verification override
        let verification_path = dir.join("verification.txt");
        if verification_path.exists() {
            self.overrides.verification = Some(read_file(&verification_path)?);
            debug!("Loaded verification override");
        }

        // Load provider overrides
        let providers_dir = dir.join("providers");
        if providers_dir.exists() {
            self.load_provider_overrides(&providers_dir)?;
        }

        // Load tool overrides
        let tools_dir = dir.join("tools");
        if tools_dir.exists() {
            self.load_tool_overrides(&tools_dir)?;
        }

        Ok(self)
    }

    fn load_provider_overrides(&mut self, dir: &Path) -> Result<(), LoaderError> {
        let provider_files = [
            ("anthropic.txt", ProviderFamily::Anthropic),
            ("openai.txt", ProviderFamily::OpenAI),
            ("gemini.txt", ProviderFamily::Google),
            ("generic.txt", ProviderFamily::Generic),
        ];

        for (filename, family) in provider_files {
            let path = dir.join(filename);
            if path.exists() {
                let content = read_file(&path)?;
                self.overrides.providers.insert(family, content);
                debug!("Loaded provider override: {:?}", family);
            }
        }

        Ok(())
    }

    fn load_tool_overrides(&mut self, dir: &Path) -> Result<(), LoaderError> {
        let entries = match fs::read_dir(dir) {
            Ok(entries) => entries,
            Err(e) => {
                warn!("Failed to read tools directory: {}", e);
                return Ok(());
            }
        };

        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().map_or(false, |ext| ext == "txt") {
                if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
                    let content = read_file(&path)?;
                    self.overrides.tools.insert(stem.to_string(), content);
                    debug!("Loaded tool override: {}", stem);
                }
            }
        }

        Ok(())
    }

    /// Get the base system prompt
    pub fn base(&self) -> &str {
        self.overrides.base.as_deref().unwrap_or(self.embedded.base)
    }

    /// Get the verification instructions
    pub fn verification(&self) -> &str {
        self.overrides
            .verification
            .as_deref()
            .unwrap_or(self.embedded.verification)
    }

    /// Get provider-specific prompt
    pub fn provider(&self, family: ProviderFamily) -> &str {
        self.overrides
            .providers
            .get(&family)
            .map(|s| s.as_str())
            .unwrap_or_else(|| self.embedded.provider(family))
    }

    /// Get tool description by name
    pub fn tool(&self, name: &str) -> Option<&str> {
        self.overrides
            .tools
            .get(name)
            .map(|s| s.as_str())
            .or_else(|| self.embedded.tool(name))
    }

    /// Get all available tool names
    pub fn tool_names(&self) -> Vec<&str> {
        let mut names: Vec<&str> = self.embedded.tool_names().copied().collect();

        // Add any override-only tools
        for name in self.overrides.tools.keys() {
            if !names.contains(&name.as_str()) {
                names.push(name.as_str());
            }
        }

        names
    }

    /// Check if using embedded defaults only (no overrides)
    pub fn is_default(&self) -> bool {
        self.overrides.base.is_none()
            && self.overrides.verification.is_none()
            && self.overrides.providers.is_empty()
            && self.overrides.tools.is_empty()
    }
}

impl Default for PromptStore {
    fn default() -> Self {
        Self::new()
    }
}

fn read_file(path: &Path) -> Result<String, LoaderError> {
    fs::read_to_string(path).map_err(|e| LoaderError::ReadError {
        path: path.to_path_buf(),
        source: e,
    })
}

/// Get the default prompt overrides directory
pub fn default_overrides_dir() -> Option<PathBuf> {
    dirs::config_dir().map(|d| d.join("agent").join("prompts"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_store_defaults() {
        let store = PromptStore::new();

        assert!(!store.base().is_empty());
        assert!(!store.verification().is_empty());
        assert!(!store.provider(ProviderFamily::Anthropic).is_empty());
        assert!(store.tool("bash").is_some());
        assert!(store.is_default());
    }

    #[test]
    fn test_store_with_overrides() {
        let temp_dir = TempDir::new().unwrap();
        let prompts_dir = temp_dir.path();

        // Create base override
        fs::write(prompts_dir.join("base.txt"), "Custom base prompt").unwrap();

        // Create provider override
        let providers_dir = prompts_dir.join("providers");
        fs::create_dir(&providers_dir).unwrap();
        fs::write(providers_dir.join("anthropic.txt"), "Custom Claude prompt").unwrap();

        // Create tool override
        let tools_dir = prompts_dir.join("tools");
        fs::create_dir(&tools_dir).unwrap();
        fs::write(tools_dir.join("bash.txt"), "Custom bash description").unwrap();

        let store = PromptStore::new()
            .with_overrides_dir(prompts_dir)
            .unwrap();

        assert_eq!(store.base(), "Custom base prompt");
        assert_eq!(store.provider(ProviderFamily::Anthropic), "Custom Claude prompt");
        assert_eq!(store.tool("bash"), Some("Custom bash description"));
        assert!(!store.is_default());

        // Non-overridden values should use defaults
        assert!(!store.provider(ProviderFamily::OpenAI).is_empty());
        assert!(store.tool("read_file").is_some());
    }

    #[test]
    fn test_nonexistent_overrides_dir() {
        let result = PromptStore::new().with_overrides_dir(Path::new("/nonexistent/path"));
        assert!(matches!(result, Err(LoaderError::DirectoryNotFound(_))));
    }

    #[test]
    fn test_tool_names() {
        let store = PromptStore::new();
        let names = store.tool_names();

        assert!(names.contains(&"bash"));
        assert!(names.contains(&"read_file"));
        assert!(names.contains(&"write_file"));
        assert!(names.contains(&"edit_file"));
        assert!(names.contains(&"glob"));
        assert!(names.contains(&"grep"));
        assert!(names.contains(&"lsp"));
    }
}