prodigy 0.4.4

Turn ad-hoc Claude sessions into reproducible development pipelines with parallel AI agents
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
//! Template registry for reusable workflow components

use super::ComposableWorkflow;
use anyhow::{Context, Result};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::RwLock;

/// Registry for workflow templates
pub struct TemplateRegistry {
    templates: Arc<RwLock<HashMap<String, TemplateEntry>>>,
    storage: Box<dyn TemplateStorage>,
}

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

impl TemplateRegistry {
    /// Create a new template registry with default file storage
    pub fn new() -> Self {
        Self::with_storage(Box::new(FileTemplateStorage::new(PathBuf::from(
            "templates",
        ))))
    }

    /// Create a new template registry with custom storage
    pub fn with_storage(storage: Box<dyn TemplateStorage>) -> Self {
        Self {
            templates: Arc::new(RwLock::new(HashMap::new())),
            storage,
        }
    }

    /// Register a new template
    pub async fn register_template(
        &self,
        name: String,
        template: ComposableWorkflow,
    ) -> Result<()> {
        // Validate template
        self.validate_template(&template)
            .with_context(|| format!("Template '{}' validation failed", name))?;

        let entry = TemplateEntry {
            name: name.clone(),
            template: template.clone(),
            metadata: TemplateMetadata {
                description: None,
                author: None,
                version: "1.0.0".to_string(),
                tags: Vec::new(),
                created_at: chrono::Utc::now(),
                updated_at: chrono::Utc::now(),
            },
        };

        // Store template
        self.storage
            .store(&name, &entry)
            .await
            .with_context(|| format!("Failed to store template '{}'", name))?;

        // Cache in memory
        self.templates.write().await.insert(name, entry);

        Ok(())
    }

    /// Register a template with metadata
    pub async fn register_template_with_metadata(
        &self,
        name: String,
        template: ComposableWorkflow,
        metadata: TemplateMetadata,
    ) -> Result<()> {
        // Validate template
        self.validate_template(&template)
            .with_context(|| format!("Template '{}' validation failed", name))?;

        let entry = TemplateEntry {
            name: name.clone(),
            template: template.clone(),
            metadata,
        };

        // Store template
        self.storage
            .store(&name, &entry)
            .await
            .with_context(|| format!("Failed to store template '{}'", name))?;

        // Cache in memory
        self.templates.write().await.insert(name, entry);

        Ok(())
    }

    /// Get a template by name
    pub async fn get(&self, name: &str) -> Result<ComposableWorkflow> {
        // Check cache
        {
            let templates = self.templates.read().await;
            if let Some(entry) = templates.get(name) {
                return Ok(entry.template.clone());
            }
        }

        // Load from storage
        let entry = self
            .storage
            .load(name)
            .await
            .with_context(|| format!("Template '{}' not found", name))?;

        let template = entry.template.clone();

        // Cache for future use
        self.templates.write().await.insert(name.to_string(), entry);

        Ok(template)
    }

    /// Get template with metadata
    pub async fn get_with_metadata(&self, name: &str) -> Result<TemplateEntry> {
        // Check cache
        {
            let templates = self.templates.read().await;
            if let Some(entry) = templates.get(name) {
                return Ok(entry.clone());
            }
        }

        // Load from storage
        let entry = self
            .storage
            .load(name)
            .await
            .with_context(|| format!("Template '{}' not found", name))?;

        // Cache for future use
        self.templates
            .write()
            .await
            .insert(name.to_string(), entry.clone());

        Ok(entry)
    }

    /// List all available templates
    pub async fn list(&self) -> Result<Vec<TemplateInfo>> {
        self.storage.list().await
    }

    /// Search templates by tags
    pub async fn search_by_tags(&self, tags: &[String]) -> Result<Vec<TemplateInfo>> {
        let all_templates = self.list().await?;

        Ok(all_templates
            .into_iter()
            .filter(|info| tags.iter().any(|tag| info.tags.contains(tag)))
            .collect())
    }

    /// Delete a template
    pub async fn delete(&self, name: &str) -> Result<()> {
        // Remove from storage
        self.storage
            .delete(name)
            .await
            .with_context(|| format!("Failed to delete template '{}'", name))?;

        // Remove from cache
        self.templates.write().await.remove(name);

        Ok(())
    }

    /// Validate a template
    fn validate_template(&self, template: &ComposableWorkflow) -> Result<()> {
        // Check for required parameters without defaults
        if let Some(params) = &template.parameters {
            for param in &params.required {
                if param.default.is_none() && param.validation.is_none() {
                    tracing::warn!(
                        "Template parameter '{}' has no default and no validation",
                        param.name
                    );
                }
            }
        }

        // Validate sub-workflow references
        if let Some(workflows) = &template.workflows {
            for (name, sub) in workflows {
                if !sub.source.exists() && !sub.source.to_str().unwrap_or("").starts_with("${") {
                    tracing::warn!(
                        "Template sub-workflow '{}' references non-existent source: {:?}",
                        name,
                        sub.source
                    );
                }
            }
        }

        Ok(())
    }

    /// Load all templates from storage
    pub async fn load_all(&self) -> Result<()> {
        let templates = self.storage.list().await?;

        for info in templates {
            if let Ok(entry) = self.storage.load(&info.name).await {
                self.templates
                    .write()
                    .await
                    .insert(info.name.clone(), entry);
            }
        }

        Ok(())
    }
}

/// Template storage interface
#[async_trait]
pub trait TemplateStorage: Send + Sync {
    /// Store a template
    async fn store(&self, name: &str, entry: &TemplateEntry) -> Result<()>;

    /// Load a template
    async fn load(&self, name: &str) -> Result<TemplateEntry>;

    /// List all templates
    async fn list(&self) -> Result<Vec<TemplateInfo>>;

    /// Delete a template
    async fn delete(&self, name: &str) -> Result<()>;

    /// Check if template exists
    async fn exists(&self, name: &str) -> Result<bool>;
}

/// File-based template storage
pub struct FileTemplateStorage {
    base_dir: PathBuf,
}

impl FileTemplateStorage {
    /// Create new file storage with base directory
    pub fn new(base_dir: PathBuf) -> Self {
        Self { base_dir }
    }

    fn template_path(&self, name: &str) -> PathBuf {
        self.base_dir.join(format!("{}.yml", name))
    }

    fn metadata_path(&self, name: &str) -> PathBuf {
        self.base_dir.join(format!("{}.meta.json", name))
    }

    /// Load template YAML from file
    async fn load_template_yaml(&self, name: &str) -> Result<ComposableWorkflow> {
        let template_path = self.template_path(name);
        let template_content = tokio::fs::read_to_string(&template_path)
            .await
            .with_context(|| format!("Failed to read template file: {:?}", template_path))?;

        serde_yaml::from_str(&template_content)
            .with_context(|| format!("Failed to parse template YAML: {:?}", template_path))
    }

    /// Load metadata from file if it exists, otherwise return default
    async fn load_metadata_if_exists(&self, name: &str) -> Result<TemplateMetadata> {
        let metadata_path = self.metadata_path(name);

        if metadata_path.exists() {
            let metadata_content = tokio::fs::read_to_string(&metadata_path)
                .await
                .with_context(|| format!("Failed to read metadata file: {:?}", metadata_path))?;

            serde_json::from_str(&metadata_content)
                .with_context(|| format!("Failed to parse metadata JSON: {:?}", metadata_path))
        } else {
            Ok(TemplateMetadata::default())
        }
    }

    /// Check if a path represents a template file (has .yml extension)
    ///
    /// # Arguments
    /// * `path` - The file path to check
    ///
    /// # Returns
    /// `true` if the file has a .yml extension, `false` otherwise
    fn is_template_file(path: &std::path::Path) -> bool {
        path.extension().and_then(|s| s.to_str()) == Some("yml")
    }

    /// Extract template name from a file path, filtering out metadata files
    ///
    /// # Arguments
    /// * `path` - The file path to extract the template name from
    ///
    /// # Returns
    /// `Some(String)` with the template name if valid, `None` if the file is a metadata file
    /// or if the file stem cannot be extracted
    fn extract_template_name(path: &std::path::Path) -> Option<String> {
        let stem = path.file_stem().and_then(|s| s.to_str())?;

        // Skip metadata files
        if stem.ends_with(".meta") {
            return None;
        }

        Some(stem.to_string())
    }

    /// Load template metadata for listing, falling back to default on errors
    ///
    /// # Arguments
    /// * `name` - The template name to load metadata for
    ///
    /// # Returns
    /// The loaded metadata, or default metadata if the file doesn't exist or cannot be read/parsed.
    /// Errors are logged as warnings but don't fail the operation.
    async fn load_template_metadata(&self, name: &str) -> TemplateMetadata {
        let metadata_path = self.metadata_path(name);

        if !metadata_path.exists() {
            return TemplateMetadata::default();
        }

        match tokio::fs::read_to_string(&metadata_path).await {
            Ok(content) => serde_json::from_str(&content).unwrap_or_else(|e| {
                tracing::warn!(
                    "Failed to parse metadata for template '{}' at {:?}: {}. Using default metadata.",
                    name,
                    metadata_path,
                    e
                );
                TemplateMetadata::default()
            }),
            Err(e) => {
                tracing::warn!(
                    "Failed to read metadata file for template '{}' at {:?}: {}. Using default metadata.",
                    name,
                    metadata_path,
                    e
                );
                TemplateMetadata::default()
            }
        }
    }
}

#[async_trait]
impl TemplateStorage for FileTemplateStorage {
    async fn store(&self, name: &str, entry: &TemplateEntry) -> Result<()> {
        // Ensure directory exists
        tokio::fs::create_dir_all(&self.base_dir)
            .await
            .with_context(|| format!("Failed to create template directory: {:?}", self.base_dir))?;

        // Store template YAML
        let template_path = self.template_path(name);
        let template_yaml =
            serde_yaml::to_string(&entry.template).context("Failed to serialize template")?;

        tokio::fs::write(&template_path, template_yaml)
            .await
            .with_context(|| format!("Failed to write template file: {:?}", template_path))?;

        // Store metadata JSON
        let metadata_path = self.metadata_path(name);
        let metadata_json = serde_json::to_string_pretty(&entry.metadata)
            .context("Failed to serialize metadata")?;

        tokio::fs::write(&metadata_path, metadata_json)
            .await
            .with_context(|| format!("Failed to write metadata file: {:?}", metadata_path))?;

        Ok(())
    }

    async fn load(&self, name: &str) -> Result<TemplateEntry> {
        let template = self.load_template_yaml(name).await?;
        let metadata = self.load_metadata_if_exists(name).await?;

        Ok(TemplateEntry {
            name: name.to_string(),
            template,
            metadata,
        })
    }

    async fn list(&self) -> Result<Vec<TemplateInfo>> {
        let mut templates = Vec::new();

        if !self.base_dir.exists() {
            return Ok(templates);
        }

        let mut entries = tokio::fs::read_dir(&self.base_dir)
            .await
            .with_context(|| format!("Failed to read template directory: {:?}", self.base_dir))?;

        while let Some(entry) = entries.next_entry().await? {
            let path = entry.path();

            if !Self::is_template_file(&path) {
                continue;
            }

            let Some(name) = Self::extract_template_name(&path) else {
                continue;
            };

            let metadata = self.load_template_metadata(&name).await;

            templates.push(TemplateInfo {
                name,
                description: metadata.description.clone(),
                version: metadata.version.clone(),
                tags: metadata.tags.clone(),
            });
        }

        Ok(templates)
    }

    async fn delete(&self, name: &str) -> Result<()> {
        let template_path = self.template_path(name);
        if template_path.exists() {
            tokio::fs::remove_file(&template_path)
                .await
                .with_context(|| format!("Failed to delete template file: {:?}", template_path))?;
        }

        let metadata_path = self.metadata_path(name);
        if metadata_path.exists() {
            tokio::fs::remove_file(&metadata_path)
                .await
                .with_context(|| format!("Failed to delete metadata file: {:?}", metadata_path))?;
        }

        Ok(())
    }

    async fn exists(&self, name: &str) -> Result<bool> {
        Ok(self.template_path(name).exists())
    }
}

/// Template entry with metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemplateEntry {
    /// Template name
    pub name: String,

    /// The template workflow
    pub template: ComposableWorkflow,

    /// Template metadata
    pub metadata: TemplateMetadata,
}

/// Template metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemplateMetadata {
    /// Template description
    pub description: Option<String>,

    /// Template author
    pub author: Option<String>,

    /// Template version
    pub version: String,

    /// Tags for categorization
    pub tags: Vec<String>,

    /// Creation timestamp
    pub created_at: chrono::DateTime<chrono::Utc>,

    /// Last update timestamp
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

impl Default for TemplateMetadata {
    fn default() -> Self {
        Self {
            description: None,
            author: None,
            version: "1.0.0".to_string(),
            tags: Vec::new(),
            created_at: chrono::Utc::now(),
            updated_at: chrono::Utc::now(),
        }
    }
}

/// Template information for listing
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemplateInfo {
    /// Template name
    pub name: String,

    /// Template description
    pub description: Option<String>,

    /// Template version
    pub version: String,

    /// Tags for categorization
    pub tags: Vec<String>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_template_registry() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let storage = Box::new(FileTemplateStorage::new(temp_dir.path().to_path_buf()));
        let registry = TemplateRegistry::with_storage(storage);

        let workflow = ComposableWorkflow::from_config(crate::config::WorkflowConfig {
            name: None,
            commands: vec![],
            env: None,
            secrets: None,
            env_files: None,
            profiles: None,
            merge: None,
        });

        // Register template
        registry
            .register_template("test-template".to_string(), workflow.clone())
            .await
            .unwrap();

        // Retrieve template
        let retrieved = registry.get("test-template").await.unwrap();
        assert_eq!(
            retrieved.config.commands.len(),
            workflow.config.commands.len()
        );
    }

    #[test]
    fn test_template_metadata() {
        let metadata = TemplateMetadata {
            description: Some("Test template".to_string()),
            author: Some("Test Author".to_string()),
            version: "2.0.0".to_string(),
            tags: vec!["test".to_string(), "example".to_string()],
            created_at: chrono::Utc::now(),
            updated_at: chrono::Utc::now(),
        };

        assert_eq!(metadata.version, "2.0.0");
        assert_eq!(metadata.tags.len(), 2);
    }

    #[tokio::test]
    async fn test_file_template_storage_load_with_metadata() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let storage = FileTemplateStorage::new(temp_dir.path().to_path_buf());

        let workflow = ComposableWorkflow::from_config(crate::config::WorkflowConfig {
            name: None,
            commands: vec![],
            env: None,
            secrets: None,
            env_files: None,
            profiles: None,
            merge: None,
        });

        let metadata = TemplateMetadata {
            description: Some("Test description".to_string()),
            author: Some("Test Author".to_string()),
            version: "2.1.0".to_string(),
            tags: vec!["test".to_string()],
            created_at: chrono::Utc::now(),
            updated_at: chrono::Utc::now(),
        };

        let entry = TemplateEntry {
            name: "test-template".to_string(),
            template: workflow,
            metadata: metadata.clone(),
        };

        // Store the template
        storage.store("test-template", &entry).await.unwrap();

        // Load it back
        let loaded = storage.load("test-template").await.unwrap();

        assert_eq!(loaded.name, "test-template");
        assert_eq!(
            loaded.metadata.description,
            Some("Test description".to_string())
        );
        assert_eq!(loaded.metadata.version, "2.1.0");
    }

    #[tokio::test]
    async fn test_file_template_storage_load_without_metadata() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let storage = FileTemplateStorage::new(temp_dir.path().to_path_buf());

        let workflow = ComposableWorkflow::from_config(crate::config::WorkflowConfig {
            name: None,
            commands: vec![],
            env: None,
            secrets: None,
            env_files: None,
            profiles: None,
            merge: None,
        });

        // Create directory
        tokio::fs::create_dir_all(temp_dir.path()).await.unwrap();

        // Write only the template YAML file (no metadata)
        let template_yaml = serde_yaml::to_string(&workflow).unwrap();
        let template_path = temp_dir.path().join("test-template.yml");
        tokio::fs::write(&template_path, template_yaml)
            .await
            .unwrap();

        // Load it back - should use default metadata
        let loaded = storage.load("test-template").await.unwrap();

        assert_eq!(loaded.name, "test-template");
        assert_eq!(loaded.metadata.version, "1.0.0"); // Default version
        assert_eq!(loaded.metadata.description, None); // Default no description
    }

    #[tokio::test]
    async fn test_file_template_storage_load_missing_template() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let storage = FileTemplateStorage::new(temp_dir.path().to_path_buf());

        // Attempt to load a template that doesn't exist
        let result = storage.load("nonexistent-template").await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("Failed to read template file"));
    }

    #[tokio::test]
    async fn test_file_template_storage_load_invalid_yaml() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let storage = FileTemplateStorage::new(temp_dir.path().to_path_buf());

        // Create directory
        tokio::fs::create_dir_all(temp_dir.path()).await.unwrap();

        // Write invalid YAML to template file
        let template_path = temp_dir.path().join("invalid-template.yml");
        tokio::fs::write(&template_path, "{ invalid yaml: [ unclosed")
            .await
            .unwrap();

        // Attempt to load - should fail with parse error
        let result = storage.load("invalid-template").await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("Failed to parse template YAML"));
    }

    #[tokio::test]
    async fn test_file_template_storage_load_invalid_metadata_json() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let storage = FileTemplateStorage::new(temp_dir.path().to_path_buf());

        let workflow = ComposableWorkflow::from_config(crate::config::WorkflowConfig {
            name: None,
            commands: vec![],
            env: None,
            secrets: None,
            env_files: None,
            profiles: None,
            merge: None,
        });

        // Create directory
        tokio::fs::create_dir_all(temp_dir.path()).await.unwrap();

        // Write valid template YAML
        let template_yaml = serde_yaml::to_string(&workflow).unwrap();
        let template_path = temp_dir.path().join("test-template.yml");
        tokio::fs::write(&template_path, template_yaml)
            .await
            .unwrap();

        // Write invalid JSON to metadata file
        let metadata_path = temp_dir.path().join("test-template.meta.json");
        tokio::fs::write(&metadata_path, "{ invalid json: [ unclosed")
            .await
            .unwrap();

        // Attempt to load - should fail with JSON parse error
        let result = storage.load("test-template").await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("Failed to parse metadata JSON"));
    }

    #[tokio::test]
    async fn test_file_template_storage_load_corrupted_metadata() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let storage = FileTemplateStorage::new(temp_dir.path().to_path_buf());

        let workflow = ComposableWorkflow::from_config(crate::config::WorkflowConfig {
            name: None,
            commands: vec![],
            env: None,
            secrets: None,
            env_files: None,
            profiles: None,
            merge: None,
        });

        // Create directory
        tokio::fs::create_dir_all(temp_dir.path()).await.unwrap();

        // Write valid template YAML
        let template_yaml = serde_yaml::to_string(&workflow).unwrap();
        let template_path = temp_dir.path().join("test-template.yml");
        tokio::fs::write(&template_path, template_yaml)
            .await
            .unwrap();

        // Write valid JSON but invalid metadata structure (missing required fields)
        let metadata_path = temp_dir.path().join("test-template.meta.json");
        tokio::fs::write(&metadata_path, r#"{"invalid": "structure"}"#)
            .await
            .unwrap();

        // Attempt to load - should fail due to invalid metadata structure
        let result = storage.load("test-template").await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("Failed to parse metadata JSON"));
    }
}