Skip to main content

grimoire_loader/
lib.rs

1//! # Grimoire Loader
2//!
3//! Integration with the Grimoire prompt management system.
4//!
5//! This crate provides utilities for loading personas and prompts
6//! from the Grimoire filesystem structure.
7//!
8//! # Configuration
9//!
10//! The Grimoire path can be configured via:
11//! 1. Environment variable: `INFERNUM_GRIMOIRE_PATH`
12//! 2. Programmatic: `GrimoireLoader::with_path(path)`
13//! 3. Default: `~/.local/share/infernum/personas/`
14
15#![warn(missing_docs)]
16#![warn(clippy::all)]
17
18use std::collections::HashMap;
19use std::path::{Path, PathBuf};
20
21use infernum_core::Result;
22use serde::{Deserialize, Serialize};
23
24/// Environment variable for customizing Grimoire path.
25pub const GRIMOIRE_PATH_ENV: &str = "INFERNUM_GRIMOIRE_PATH";
26
27/// Returns the default Grimoire personas path.
28///
29/// Checks in order:
30/// 1. `INFERNUM_GRIMOIRE_PATH` environment variable
31/// 2. `~/.local/share/infernum/personas/` (XDG data directory)
32#[must_use]
33pub fn default_grimoire_path() -> PathBuf {
34    // Check environment variable first
35    if let Ok(path) = std::env::var(GRIMOIRE_PATH_ENV) {
36        return PathBuf::from(path);
37    }
38
39    // Fall back to XDG data directory
40    dirs::data_local_dir()
41        .unwrap_or_else(|| PathBuf::from("."))
42        .join("infernum")
43        .join("personas")
44}
45
46/// Legacy constant for backwards compatibility.
47#[deprecated(since = "0.2.0", note = "Use default_grimoire_path() instead")]
48pub const DEFAULT_GRIMOIRE_PATH: &str = "~/.local/share/infernum/personas/";
49
50/// A loaded Grimoire persona.
51#[derive(Debug, Clone, Serialize, Deserialize)]
52pub struct GrimoirePersona {
53    /// Persona identifier.
54    pub id: String,
55    /// Display name.
56    pub name: String,
57    /// System prompt.
58    pub system_prompt: String,
59    /// Variants of the persona.
60    pub variants: HashMap<String, String>,
61    /// Metadata.
62    pub metadata: HashMap<String, String>,
63}
64
65/// Loader for Grimoire personas.
66pub struct GrimoireLoader {
67    base_path: PathBuf,
68    cache: dashmap::DashMap<String, GrimoirePersona>,
69}
70
71impl GrimoireLoader {
72    /// Creates a new loader with the default path.
73    ///
74    /// Uses `default_grimoire_path()` which checks `INFERNUM_GRIMOIRE_PATH`
75    /// environment variable first, then falls back to XDG data directory.
76    #[must_use]
77    pub fn new() -> Self {
78        Self::with_path(default_grimoire_path())
79    }
80
81    /// Creates a new loader with a custom path.
82    #[must_use]
83    pub fn with_path(path: impl Into<PathBuf>) -> Self {
84        Self {
85            base_path: path.into(),
86            cache: dashmap::DashMap::new(),
87        }
88    }
89
90    /// Loads a persona by ID.
91    ///
92    /// # Errors
93    ///
94    /// Returns an error if the persona cannot be loaded.
95    pub async fn load(&self, persona_id: &str) -> Result<GrimoirePersona> {
96        // Check cache first
97        if let Some(cached) = self.cache.get(persona_id) {
98            return Ok(cached.clone());
99        }
100
101        // Build path
102        let path = self.base_path.join(persona_id);
103        let prompt_path = if path.is_dir() {
104            path.join("prompt.md")
105        } else {
106            path.with_extension("md")
107        };
108
109        // Load file
110        let content = tokio::fs::read_to_string(&prompt_path)
111            .await
112            .map_err(|e| infernum_core::Error::Io(e))?;
113
114        // Parse persona
115        let persona = self.parse_persona(persona_id, &content)?;
116
117        // Cache it
118        self.cache.insert(persona_id.to_string(), persona.clone());
119
120        Ok(persona)
121    }
122
123    /// Parses persona content.
124    fn parse_persona(&self, id: &str, content: &str) -> Result<GrimoirePersona> {
125        // Simple parsing - in production, handle frontmatter YAML
126        Ok(GrimoirePersona {
127            id: id.to_string(),
128            name: id.to_string(),
129            system_prompt: content.to_string(),
130            variants: HashMap::new(),
131            metadata: HashMap::new(),
132        })
133    }
134
135    /// Lists all available personas.
136    ///
137    /// # Errors
138    ///
139    /// Returns an error if the directory cannot be read.
140    pub async fn list(&self) -> Result<Vec<String>> {
141        let mut personas = Vec::new();
142
143        if !self.base_path.exists() {
144            return Ok(personas);
145        }
146
147        let mut entries = tokio::fs::read_dir(&self.base_path).await?;
148        while let Some(entry) = entries.next_entry().await? {
149            let path = entry.path();
150            if path.is_dir() || path.extension().map_or(false, |e| e == "md") {
151                if let Some(name) = path.file_stem().and_then(|s| s.to_str()) {
152                    personas.push(name.to_string());
153                }
154            }
155        }
156
157        Ok(personas)
158    }
159
160    /// Clears the cache.
161    pub fn clear_cache(&self) {
162        self.cache.clear();
163    }
164
165    /// Returns the base path.
166    #[must_use]
167    pub fn base_path(&self) -> &Path {
168        &self.base_path
169    }
170}
171
172impl Default for GrimoireLoader {
173    fn default() -> Self {
174        Self::new()
175    }
176}