paladin-ai 0.5.1

Enterprise AI orchestration framework with multi-agent coordination patterns
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! File System Citadel Adapter
//!
//! This module provides a file system-based implementation of the CitadelPort
//! trait, persisting Paladin and Battalion states as JSON files.
//!
//! # Design
//!
//! - States are stored as individual JSON files in a configured directory
//! - File naming convention: `paladin-{uuid}.json` or `battalion-{uuid}.json`
//! - Pretty-printed JSON for human readability and debugging
//! - Directory is created automatically if it doesn't exist
//! - Atomic writes using tokio::fs async operations
//!
//! # Examples
//!
//! ```rust,no_run
//! use paladin::infrastructure::adapters::citadel::file_citadel::FileCitadel;
//! use paladin_ports::output::citadel_port::CitadelPort;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let citadel = FileCitadel::new("./citadel")?;
//!     // Use citadel to save/load states
//!     Ok(())
//! }
//! ```

use async_trait::async_trait;
use log::{info, warn};
use std::path::PathBuf;
use tokio::fs;
use uuid::Uuid;

use crate::application::errors::citadel_error::CitadelError;
use crate::core::platform::container::citadel::{
    BattalionState, PaladinState, StateSummary, StateType,
};
use paladin_ports::output::citadel_port::CitadelPort;

/// File system-based Citadel adapter
///
/// Persists Paladin and Battalion states as JSON files in a configured directory.
/// The adapter is thread-safe and can be safely shared across async tasks.
///
/// # Examples
///
/// ```rust,no_run
/// use paladin::infrastructure::adapters::citadel::file_citadel::FileCitadel;
///
/// let citadel = FileCitadel::new("./my-app/state")
///     .expect("Failed to create citadel");
/// ```
#[doc(hidden)]
#[derive(Debug, Clone)]
pub struct FileCitadel {
    state_dir: PathBuf,
}

impl FileCitadel {
    /// Creates a new FileCitadel adapter
    ///
    /// The state directory is created if it doesn't exist. Permissions are validated
    /// to ensure the directory is writable.
    ///
    /// # Arguments
    ///
    /// * `state_dir` - Path to the directory where state files will be stored
    ///
    /// # Returns
    ///
    /// * `Ok(FileCitadel)` - Successfully created adapter
    /// * `Err(CitadelError)` - Directory creation or validation failed
    ///
    /// # Errors
    ///
    /// - `CitadelError::DirectoryCreationFailed` - Cannot create directory
    /// - `CitadelError::PermissionDenied` - Directory is not writable
    /// - `CitadelError::InvalidDirectory` - Path is not a directory
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use paladin::infrastructure::adapters::citadel::file_citadel::FileCitadel;
    ///
    /// let citadel = FileCitadel::new("./citadel")?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn new(state_dir: impl Into<PathBuf>) -> Result<Self, CitadelError> {
        let state_dir = state_dir.into();

        // Validate directory
        if state_dir.exists() {
            if !state_dir.is_dir() {
                return Err(CitadelError::invalid_directory(format!(
                    "Path exists but is not a directory: {}",
                    state_dir.display()
                )));
            }

            // Check if directory is writable
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                if let Ok(metadata) = std::fs::metadata(&state_dir) {
                    let permissions = metadata.permissions();
                    // Check if owner has write permission (bit 7)
                    if permissions.mode() & 0o200 == 0 {
                        return Err(CitadelError::permission_denied(format!(
                            "Directory is not writable: {}",
                            state_dir.display()
                        )));
                    }
                }
            }
        } else {
            // Create directory if it doesn't exist
            std::fs::create_dir_all(&state_dir).map_err(|e| {
                CitadelError::directory_creation_failed(format!(
                    "Failed to create state directory {}: {}",
                    state_dir.display(),
                    e
                ))
            })?;
            info!("Created state directory: {}", state_dir.display());
        }

        Ok(Self { state_dir })
    }

    /// Generates the file path for a Paladin state
    fn paladin_path(&self, id: Uuid) -> PathBuf {
        self.state_dir.join(format!("paladin-{}.json", id))
    }

    /// Generates the file path for a Battalion state
    fn battalion_path(&self, id: Uuid) -> PathBuf {
        self.state_dir.join(format!("battalion-{}.json", id))
    }

    /// Parses a file name to extract UUID and state type
    fn parse_filename(filename: &str) -> Option<(Uuid, StateType)> {
        if let Some(stripped) = filename.strip_prefix("paladin-") {
            if let Some(uuid_str) = stripped.strip_suffix(".json")
                && let Ok(uuid) = Uuid::parse_str(uuid_str)
            {
                return Some((uuid, StateType::Paladin));
            }
        } else if let Some(stripped) = filename.strip_prefix("battalion-")
            && let Some(uuid_str) = stripped.strip_suffix(".json")
            && let Ok(uuid) = Uuid::parse_str(uuid_str)
        {
            return Some((uuid, StateType::Battalion));
        }
        None
    }
}

#[async_trait]
impl CitadelPort for FileCitadel {
    async fn save_paladin(&self, state: &PaladinState) -> Result<(), CitadelError> {
        let path = self.paladin_path(state.paladin.uuid);

        // Serialize to pretty JSON for human readability
        let json = serde_json::to_string_pretty(state)?;

        // Write to file atomically
        fs::write(&path, json).await.map_err(|e| {
            CitadelError::IoError(std::io::Error::new(
                e.kind(),
                format!("Failed to write Paladin state to {}: {}", path.display(), e),
            ))
        })?;

        info!(
            "Saved Paladin state: {} to {}",
            state.paladin.uuid,
            path.display()
        );

        Ok(())
    }

    async fn load_paladin(&self, id: Uuid) -> Result<Option<PaladinState>, CitadelError> {
        let path = self.paladin_path(id);

        // Check if file exists
        if !path.exists() {
            return Ok(None);
        }

        // Read file
        let json = fs::read_to_string(&path).await.map_err(|e| {
            CitadelError::IoError(std::io::Error::new(
                e.kind(),
                format!(
                    "Failed to read Paladin state from {}: {}",
                    path.display(),
                    e
                ),
            ))
        })?;

        // Deserialize
        let state: PaladinState = serde_json::from_str(&json).map_err(|e| {
            CitadelError::corrupted(format!(
                "Failed to parse Paladin state from {}: {}",
                path.display(),
                e
            ))
        })?;

        // Validate schema version (currently just log warning for MVP)
        if state.schema_version != "1.0.0" {
            warn!(
                "Loading Paladin state with schema version {} (expected 1.0.0)",
                state.schema_version
            );
        }

        info!("Loaded Paladin state: {} from {}", id, path.display());

        Ok(Some(state))
    }

    async fn save_battalion(&self, state: &BattalionState) -> Result<(), CitadelError> {
        let path = self.battalion_path(state.id);

        // Serialize to pretty JSON
        let json = serde_json::to_string_pretty(state)?;

        // Write to file
        fs::write(&path, json).await.map_err(|e| {
            CitadelError::IoError(std::io::Error::new(
                e.kind(),
                format!(
                    "Failed to write Battalion state to {}: {}",
                    path.display(),
                    e
                ),
            ))
        })?;

        info!("Saved Battalion state: {} to {}", state.id, path.display());

        Ok(())
    }

    async fn load_battalion(&self, id: Uuid) -> Result<Option<BattalionState>, CitadelError> {
        let path = self.battalion_path(id);

        // Check if file exists
        if !path.exists() {
            return Ok(None);
        }

        // Read file
        let json = fs::read_to_string(&path).await.map_err(|e| {
            CitadelError::IoError(std::io::Error::new(
                e.kind(),
                format!(
                    "Failed to read Battalion state from {}: {}",
                    path.display(),
                    e
                ),
            ))
        })?;

        // Deserialize
        let state: BattalionState = serde_json::from_str(&json).map_err(|e| {
            CitadelError::corrupted(format!(
                "Failed to parse Battalion state from {}: {}",
                path.display(),
                e
            ))
        })?;

        // Validate schema version
        if state.schema_version != "1.0.0" {
            warn!(
                "Loading Battalion state with schema version {} (expected 1.0.0)",
                state.schema_version
            );
        }

        info!("Loaded Battalion state: {} from {}", id, path.display());

        Ok(Some(state))
    }

    async fn list_saved(&self) -> Result<Vec<StateSummary>, CitadelError> {
        let mut summaries = Vec::new();

        // Read directory entries
        let mut entries = fs::read_dir(&self.state_dir).await.map_err(|e| {
            CitadelError::IoError(std::io::Error::new(
                e.kind(),
                format!(
                    "Failed to read state directory {}: {}",
                    self.state_dir.display(),
                    e
                ),
            ))
        })?;

        while let Some(entry) = entries.next_entry().await.map_err(|e| {
            CitadelError::IoError(std::io::Error::new(
                e.kind(),
                format!("Failed to read directory entry: {}", e),
            ))
        })? {
            let path = entry.path();

            // Skip non-files
            if !path.is_file() {
                continue;
            }

            // Parse filename
            if let Some(filename) = path.file_name().and_then(|n| n.to_str())
                && let Some((id, state_type)) = Self::parse_filename(filename)
            {
                // Get file metadata for timestamps
                if let Ok(metadata) = fs::metadata(&path).await
                    && let Ok(created) = metadata.created()
                    && let Ok(modified) = metadata.modified()
                {
                    summaries.push(StateSummary {
                        id,
                        state_type,
                        created_at: created.into(),
                        updated_at: modified.into(),
                        file_path: path.clone(),
                    });
                }
            }
        }

        info!("Listed {} saved states", summaries.len());

        Ok(summaries)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::base::entity::node::Node;
    use crate::core::platform::container::citadel::{
        BattalionConfig, CheckpointData, PaladinData, PaladinStatus,
    };
    use crate::core::platform::container::paladin::MaxLoops;
    use tempfile::TempDir;

    fn create_test_paladin_state() -> PaladinState {
        let paladin_data = PaladinData {
            system_prompt: "test".to_string(),
            name: "test".to_string(),
            user_name: "test".to_string(),
            model: "gpt-4".to_string(),
            temperature: 0.7,
            max_loops: MaxLoops::Fixed(3),
            stop_words: vec![],
            status: PaladinStatus::Idle,
            vision_enabled: false,
            ..Default::default()
        };
        let paladin = Node::new(paladin_data, Some("test".to_string()));
        PaladinState::new(paladin, vec![], vec![])
    }

    #[test]
    fn test_file_citadel_creation() {
        let temp_dir = TempDir::new().unwrap();
        let citadel = FileCitadel::new(temp_dir.path());
        assert!(citadel.is_ok());
    }

    #[test]
    fn test_file_citadel_creates_directory() {
        let temp_dir = TempDir::new().unwrap();
        let state_dir = temp_dir.path().join("new_dir");
        assert!(!state_dir.exists());

        let citadel = FileCitadel::new(&state_dir);
        assert!(citadel.is_ok());
        assert!(state_dir.exists());
        assert!(state_dir.is_dir());
    }

    #[test]
    fn test_file_citadel_rejects_file_as_directory() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("notadir");
        std::fs::write(&file_path, "test").unwrap();

        let citadel = FileCitadel::new(&file_path);
        assert!(citadel.is_err());
        assert!(matches!(
            citadel.unwrap_err(),
            CitadelError::InvalidDirectory(_)
        ));
    }

    #[test]
    fn test_paladin_path_generation() {
        let temp_dir = TempDir::new().unwrap();
        let citadel = FileCitadel::new(temp_dir.path()).unwrap();
        let id = Uuid::new_v4();
        let path = citadel.paladin_path(id);
        assert_eq!(path, temp_dir.path().join(format!("paladin-{}.json", id)));
    }

    #[test]
    fn test_battalion_path_generation() {
        let temp_dir = TempDir::new().unwrap();
        let citadel = FileCitadel::new(temp_dir.path()).unwrap();
        let id = Uuid::new_v4();
        let path = citadel.battalion_path(id);
        assert_eq!(path, temp_dir.path().join(format!("battalion-{}.json", id)));
    }

    #[test]
    fn test_parse_filename_paladin() {
        let id = Uuid::new_v4();
        let filename = format!("paladin-{}.json", id);
        let result = FileCitadel::parse_filename(&filename);
        assert!(result.is_some());
        let (parsed_id, state_type) = result.unwrap();
        assert_eq!(parsed_id, id);
        assert_eq!(state_type, StateType::Paladin);
    }

    #[test]
    fn test_parse_filename_battalion() {
        let id = Uuid::new_v4();
        let filename = format!("battalion-{}.json", id);
        let result = FileCitadel::parse_filename(&filename);
        assert!(result.is_some());
        let (parsed_id, state_type) = result.unwrap();
        assert_eq!(parsed_id, id);
        assert_eq!(state_type, StateType::Battalion);
    }

    #[test]
    fn test_parse_filename_invalid() {
        assert!(FileCitadel::parse_filename("invalid.json").is_none());
        assert!(FileCitadel::parse_filename("paladin-notauuid.json").is_none());
        assert!(FileCitadel::parse_filename("paladin-123.txt").is_none());
    }

    #[tokio::test]
    async fn test_save_and_load_paladin() {
        let temp_dir = TempDir::new().unwrap();
        let citadel = FileCitadel::new(temp_dir.path()).unwrap();

        let state = create_test_paladin_state();
        let id = state.paladin.uuid;

        // Save
        citadel.save_paladin(&state).await.unwrap();

        // Verify file exists
        let path = citadel.paladin_path(id);
        assert!(path.exists());

        // Load
        let loaded = citadel.load_paladin(id).await.unwrap();
        assert!(loaded.is_some());
        let loaded_state = loaded.unwrap();
        assert_eq!(loaded_state.paladin.uuid, id);
        assert_eq!(loaded_state.schema_version, "1.0.0");
    }

    #[tokio::test]
    async fn test_load_nonexistent_paladin() {
        let temp_dir = TempDir::new().unwrap();
        let citadel = FileCitadel::new(temp_dir.path()).unwrap();

        let result = citadel.load_paladin(Uuid::new_v4()).await;
        assert!(result.is_ok());
        assert!(result.unwrap().is_none());
    }

    #[tokio::test]
    async fn test_save_overwrites_existing() {
        let temp_dir = TempDir::new().unwrap();
        let citadel = FileCitadel::new(temp_dir.path()).unwrap();

        let state = create_test_paladin_state();

        // Save twice
        citadel.save_paladin(&state).await.unwrap();
        citadel.save_paladin(&state).await.unwrap();

        // Should only be one file
        let entries: Vec<_> = std::fs::read_dir(temp_dir.path()).unwrap().collect();
        assert_eq!(entries.len(), 1);
    }

    #[tokio::test]
    async fn test_save_and_load_battalion() {
        let temp_dir = TempDir::new().unwrap();
        let citadel = FileCitadel::new(temp_dir.path()).unwrap();

        let state = BattalionState::new(
            "Formation",
            BattalionConfig::default(),
            vec![],
            Some(CheckpointData::new()),
        );
        let id = state.id;

        // Save
        citadel.save_battalion(&state).await.unwrap();

        // Load
        let loaded = citadel.load_battalion(id).await.unwrap();
        assert!(loaded.is_some());
        let loaded_state = loaded.unwrap();
        assert_eq!(loaded_state.id, id);
        assert_eq!(loaded_state.battalion_type, "Formation");
    }

    #[tokio::test]
    async fn test_list_saved_empty() {
        let temp_dir = TempDir::new().unwrap();
        let citadel = FileCitadel::new(temp_dir.path()).unwrap();

        let summaries = citadel.list_saved().await.unwrap();
        assert_eq!(summaries.len(), 0);
    }

    #[tokio::test]
    async fn test_list_saved_multiple() {
        let temp_dir = TempDir::new().unwrap();
        let citadel = FileCitadel::new(temp_dir.path()).unwrap();

        // Save multiple states
        let state1 = create_test_paladin_state();
        let state2 = create_test_paladin_state();
        let battalion = BattalionState::new("Phalanx", BattalionConfig::default(), vec![], None);

        citadel.save_paladin(&state1).await.unwrap();
        citadel.save_paladin(&state2).await.unwrap();
        citadel.save_battalion(&battalion).await.unwrap();

        // List
        let summaries = citadel.list_saved().await.unwrap();
        assert_eq!(summaries.len(), 3);

        // Check types
        let paladin_count = summaries
            .iter()
            .filter(|s| s.state_type == StateType::Paladin)
            .count();
        let battalion_count = summaries
            .iter()
            .filter(|s| s.state_type == StateType::Battalion)
            .count();
        assert_eq!(paladin_count, 2);
        assert_eq!(battalion_count, 1);
    }

    #[tokio::test]
    async fn test_json_is_human_readable() {
        let temp_dir = TempDir::new().unwrap();
        let citadel = FileCitadel::new(temp_dir.path()).unwrap();

        let state = create_test_paladin_state();
        let id = state.paladin.uuid;

        citadel.save_paladin(&state).await.unwrap();

        // Read file and verify it's pretty-printed
        let path = citadel.paladin_path(id);
        let contents = std::fs::read_to_string(path).unwrap();
        assert!(contents.contains('\n')); // Multi-line
        assert!(contents.contains("  ")); // Indented
        assert!(contents.contains("\"schema_version\""));
    }
}