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
//! Integration tests for documentation gap detection (Spec 124)
//!
//! These tests verify that the gap detection logic works correctly by:
//! 1. Creating mock features.json with known features
//! 2. Creating mock book structure with some chapters missing
//! 3. Simulating gap detection analysis
//! 4. Verifying correct chapters would be created
//! 5. Testing idempotence (running twice doesn't create duplicates)
//! 6. Verifying no false positives (existing chapters aren't duplicated)

use anyhow::Result;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use tempfile::TempDir;

/// Mock feature definition
#[derive(Debug, Clone)]
struct MockFeature {
    category: String,
    description: String,
    capabilities: Vec<String>,
}

/// Mock chapter definition
#[derive(Debug, Clone)]
struct MockChapter {
    id: String,
    title: String,
    file: String,
    topics: Vec<String>,
}

/// Test helper to create mock features.json
fn create_mock_features(temp_dir: &Path, features: &[MockFeature]) -> Result<PathBuf> {
    let features_path = temp_dir.join("features.json");

    let mut features_map: HashMap<String, Value> = HashMap::new();
    for feature in features {
        features_map.insert(
            feature.category.clone(),
            json!({
                "description": feature.description,
                "capabilities": feature.capabilities,
            }),
        );
    }

    let features_json = json!({
        "analysis_date": "2025-10-11T00:00:00Z",
        "features": features_map,
    });

    fs::write(
        &features_path,
        serde_json::to_string_pretty(&features_json)?,
    )?;
    Ok(features_path)
}

/// Test helper to create mock chapters.json
fn create_mock_chapters(temp_dir: &Path, chapters: &[MockChapter]) -> Result<PathBuf> {
    let chapters_path = temp_dir.join("prodigy-chapters.json");

    let chapters_array: Vec<Value> = chapters
        .iter()
        .map(|ch| {
            json!({
                "id": ch.id,
                "title": ch.title,
                "file": ch.file,
                "topics": ch.topics,
            })
        })
        .collect();

    fs::write(
        &chapters_path,
        serde_json::to_string_pretty(&chapters_array)?,
    )?;
    Ok(chapters_path)
}

/// Test helper to create mock book structure
fn create_mock_book_structure(temp_dir: &Path, chapters: &[MockChapter]) -> Result<PathBuf> {
    let book_dir = temp_dir.join("book");
    let src_dir = book_dir.join("src");
    fs::create_dir_all(&src_dir)?;

    // Create SUMMARY.md
    let summary_path = src_dir.join("SUMMARY.md");
    let mut summary_content = String::from("# Summary\n\n");
    summary_content.push_str("- [Introduction](introduction.md)\n\n");
    summary_content.push_str("## User Guide\n\n");
    for chapter in chapters {
        summary_content.push_str(&format!("- [{}]({})\n", chapter.title, chapter.file));
    }
    fs::write(&summary_path, summary_content)?;

    // Create chapter markdown files
    for chapter in chapters {
        let chapter_path = src_dir.join(&chapter.file);
        let chapter_content = format!(
            "# {}\n\nThis chapter covers: {}\n",
            chapter.title,
            chapter.topics.join(", ")
        );
        fs::write(&chapter_path, chapter_content)?;
    }

    Ok(book_dir)
}

/// Simulates gap detection logic based on the spec
fn detect_gaps(
    features: &[MockFeature],
    chapters: &[MockChapter],
) -> Vec<(String, String, String)> {
    let mut gaps = Vec::new();

    for feature in features {
        // Normalize feature category for comparison
        let normalized_category = feature.category.to_lowercase().replace('_', "-");

        // Check if any chapter covers this feature
        let is_covered = chapters.iter().any(|ch| {
            let normalized_id = ch.id.to_lowercase();
            let normalized_title = ch.title.to_lowercase();

            // Check exact or partial matches
            normalized_id.contains(&normalized_category)
                || normalized_category.contains(&normalized_id)
                || normalized_title.contains(&normalized_category)
                || ch.topics.iter().any(|topic| {
                    let normalized_topic = topic.to_lowercase();
                    normalized_topic.contains(&normalized_category)
                        || normalized_category.contains(&normalized_topic)
                })
        });

        if !is_covered {
            // Generate recommended chapter ID
            let chapter_id = feature.category.replace('_', "-");

            // Generate recommended title
            let title = feature
                .category
                .split('_')
                .map(|word| {
                    let mut chars = word.chars();
                    match chars.next() {
                        Some(first) => first.to_uppercase().chain(chars).collect::<String>(),
                        None => String::new(),
                    }
                })
                .collect::<Vec<_>>()
                .join(" ");

            gaps.push((chapter_id, title, feature.description.clone()));
        }
    }

    gaps
}

#[test]
fn test_gap_detection_identifies_missing_chapters() -> Result<()> {
    let temp_dir = TempDir::new()?;

    // Create features with some undocumented ones
    let features = vec![
        MockFeature {
            category: "workflow_basics".to_string(),
            description: "Basic workflow features".to_string(),
            capabilities: vec!["setup".to_string(), "commands".to_string()],
        },
        MockFeature {
            category: "mapreduce".to_string(),
            description: "MapReduce workflows".to_string(),
            capabilities: vec!["map".to_string(), "reduce".to_string()],
        },
        MockFeature {
            category: "agent_merge".to_string(),
            description: "Custom merge workflows for agents".to_string(),
            capabilities: vec!["validation".to_string(), "merge_config".to_string()],
        },
        MockFeature {
            category: "circuit_breaker".to_string(),
            description: "Circuit breaker for error handling".to_string(),
            capabilities: vec!["threshold".to_string(), "recovery".to_string()],
        },
    ];

    // Create chapters - only documenting first two features
    let chapters = vec![
        MockChapter {
            id: "workflow-basics".to_string(),
            title: "Workflow Basics".to_string(),
            file: "workflow-basics.md".to_string(),
            topics: vec!["Setup phase".to_string(), "Commands".to_string()],
        },
        MockChapter {
            id: "mapreduce-workflows".to_string(),
            title: "MapReduce Workflows".to_string(),
            file: "mapreduce-workflows.md".to_string(),
            topics: vec!["Map phase".to_string(), "Reduce phase".to_string()],
        },
    ];

    create_mock_features(temp_dir.path(), &features)?;
    create_mock_chapters(temp_dir.path(), &chapters)?;
    create_mock_book_structure(temp_dir.path(), &chapters)?;

    // Run gap detection
    let gaps = detect_gaps(&features, &chapters);

    // Verify gaps were detected
    assert_eq!(gaps.len(), 2, "Should detect 2 missing chapters");

    // Verify agent_merge gap
    assert!(
        gaps.iter().any(|(id, _, _)| id == "agent-merge"),
        "Should detect agent_merge gap"
    );

    // Verify circuit_breaker gap
    assert!(
        gaps.iter().any(|(id, _, _)| id == "circuit-breaker"),
        "Should detect circuit_breaker gap"
    );

    Ok(())
}

#[test]
fn test_gap_detection_idempotence() -> Result<()> {
    let temp_dir = TempDir::new()?;

    let features = vec![MockFeature {
        category: "new_feature".to_string(),
        description: "A new feature".to_string(),
        capabilities: vec!["capability1".to_string()],
    }];

    let chapters = vec![];

    create_mock_features(temp_dir.path(), &features)?;
    create_mock_chapters(temp_dir.path(), &chapters)?;

    // First run - should detect gap
    let gaps_first = detect_gaps(&features, &chapters);
    assert_eq!(gaps_first.len(), 1, "First run should detect 1 gap");

    // Simulate creating the chapter
    let new_chapter = MockChapter {
        id: "new-feature".to_string(),
        title: "New Feature".to_string(),
        file: "new-feature.md".to_string(),
        topics: vec!["New feature overview".to_string()],
    };

    let updated_chapters = vec![new_chapter];

    // Second run - should detect no gaps
    let gaps_second = detect_gaps(&features, &updated_chapters);
    assert_eq!(
        gaps_second.len(),
        0,
        "Second run should detect no gaps (idempotent)"
    );

    Ok(())
}

#[test]
fn test_gap_detection_prevents_false_positives() -> Result<()> {
    let temp_dir = TempDir::new()?;

    // Feature with multiple naming variations
    let features = vec![MockFeature {
        category: "retry_configuration".to_string(),
        description: "Retry configuration options".to_string(),
        capabilities: vec!["max_attempts".to_string(), "backoff".to_string()],
    }];

    // Chapter with similar but not exact name
    let chapters = vec![MockChapter {
        id: "retry-config".to_string(),
        title: "Retry Configuration".to_string(),
        file: "retry-config.md".to_string(),
        topics: vec![
            "Retry settings".to_string(),
            "Configuration options".to_string(),
        ],
    }];

    create_mock_features(temp_dir.path(), &features)?;
    create_mock_chapters(temp_dir.path(), &chapters)?;

    // Run gap detection
    let gaps = detect_gaps(&features, &chapters);

    // Should NOT detect a gap - the chapter exists with similar name
    assert_eq!(gaps.len(), 0, "Should not create duplicate chapters");

    Ok(())
}

#[test]
fn test_gap_detection_normalizes_topic_names() -> Result<()> {
    let temp_dir = TempDir::new()?;

    // Features with underscores and various formats
    let features = vec![
        MockFeature {
            category: "command_types".to_string(),
            description: "Different command types".to_string(),
            capabilities: vec!["shell".to_string(), "claude".to_string()],
        },
        MockFeature {
            category: "error_handling".to_string(),
            description: "Error handling operations".to_string(),
            capabilities: vec!["validation".to_string()],
        },
    ];

    // Chapters with normalized names (hyphens)
    let chapters = vec![
        MockChapter {
            id: "command-types".to_string(),
            title: "Command Types".to_string(),
            file: "command-types.md".to_string(),
            topics: vec!["Shell commands".to_string(), "Claude commands".to_string()],
        },
        MockChapter {
            id: "error-handling".to_string(),
            title: "Error Handling".to_string(),
            file: "error-handling.md".to_string(),
            topics: vec!["Error validation".to_string()],
        },
    ];

    create_mock_features(temp_dir.path(), &features)?;
    create_mock_chapters(temp_dir.path(), &chapters)?;

    // Run gap detection
    let gaps = detect_gaps(&features, &chapters);

    // Should detect no gaps - normalization should match them
    assert_eq!(
        gaps.len(),
        0,
        "Normalization should match underscore and hyphen variations"
    );

    Ok(())
}

#[test]
fn test_chapter_definition_generation() -> Result<()> {
    let temp_dir = TempDir::new()?;

    let features = vec![MockFeature {
        category: "environment_variables".to_string(),
        description: "Environment variable support".to_string(),
        capabilities: vec![
            "global_env".to_string(),
            "secrets".to_string(),
            "profiles".to_string(),
        ],
    }];

    let chapters = vec![];

    create_mock_features(temp_dir.path(), &features)?;
    create_mock_chapters(temp_dir.path(), &chapters)?;

    // Run gap detection
    let gaps = detect_gaps(&features, &chapters);

    assert_eq!(gaps.len(), 1, "Should detect 1 gap");

    let (chapter_id, title, description) = &gaps[0];

    // Verify chapter ID uses hyphens
    assert_eq!(chapter_id, "environment-variables");
    assert!(!chapter_id.contains('_'), "Chapter ID should use hyphens");

    // Verify title is properly formatted
    assert_eq!(title, "Environment Variables");
    assert!(
        title.chars().next().unwrap().is_uppercase(),
        "Title should start with uppercase"
    );

    // Verify description is preserved
    assert_eq!(description, "Environment variable support");

    Ok(())
}

#[test]
fn test_stub_file_structure() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let book_dir = temp_dir.path().join("book");
    let src_dir = book_dir.join("src");
    fs::create_dir_all(&src_dir)?;

    // Create a mock stub file based on spec requirements
    let stub_content = r#"# New Feature

Brief introduction explaining the purpose of this feature/capability

## Overview

High-level description of what this feature enables

## Configuration

Configuration options and syntax

```yaml
# Example configuration
```

## Use Cases

### Use Case 1 Name

Description and example

## Examples

### Basic Example

```yaml
# Example workflow
```

## Best Practices

- Best practice 1
- Best practice 2

## Troubleshooting

### Common Issues

**Issue**: Common problem
**Solution**: How to fix

## See Also

- [Related documentation](link)
"#;

    let stub_path = src_dir.join("new-feature.md");
    fs::write(&stub_path, stub_content)?;

    // Verify stub file was created
    assert!(stub_path.exists(), "Stub file should be created");

    // Read and verify structure
    let content = fs::read_to_string(&stub_path)?;

    // Verify required sections exist
    assert!(content.contains("# New Feature"), "Should have title");
    assert!(content.contains("## Overview"), "Should have Overview");
    assert!(
        content.contains("## Configuration"),
        "Should have Configuration"
    );
    assert!(content.contains("## Use Cases"), "Should have Use Cases");
    assert!(content.contains("## Examples"), "Should have Examples");
    assert!(
        content.contains("## Best Practices"),
        "Should have Best Practices"
    );
    assert!(
        content.contains("## Troubleshooting"),
        "Should have Troubleshooting"
    );
    assert!(content.contains("## See Also"), "Should have See Also");

    // Verify code blocks are properly formatted
    assert!(content.contains("```yaml"), "Should have YAML code blocks");

    Ok(())
}

#[test]
fn test_gap_detection_with_partial_matches() -> Result<()> {
    let temp_dir = TempDir::new()?;

    // Feature that should match a chapter with partial name
    let features = vec![MockFeature {
        category: "mapreduce_workflows".to_string(),
        description: "MapReduce workflow system".to_string(),
        capabilities: vec!["map".to_string(), "reduce".to_string()],
    }];

    // Chapter with shorter name that partially matches
    let chapters = vec![MockChapter {
        id: "mapreduce".to_string(),
        title: "MapReduce".to_string(),
        file: "mapreduce.md".to_string(),
        topics: vec!["Map phase".to_string(), "Reduce phase".to_string()],
    }];

    create_mock_features(temp_dir.path(), &features)?;
    create_mock_chapters(temp_dir.path(), &chapters)?;

    // Run gap detection
    let gaps = detect_gaps(&features, &chapters);

    // Should not detect gap - partial match should work
    assert_eq!(
        gaps.len(),
        0,
        "Should match partial names (mapreduce matches mapreduce_workflows)"
    );

    Ok(())
}

#[test]
fn test_gap_detection_severity_classification() -> Result<()> {
    let temp_dir = TempDir::new()?;

    // Mix of documented and undocumented features
    let features = vec![
        MockFeature {
            category: "core_workflow".to_string(),
            description: "Core workflow engine (critical)".to_string(),
            capabilities: vec!["execution".to_string()],
        },
        MockFeature {
            category: "advanced_retry".to_string(),
            description: "Advanced retry features (optional)".to_string(),
            capabilities: vec!["jitter".to_string()],
        },
    ];

    let chapters = vec![MockChapter {
        id: "core-workflow".to_string(),
        title: "Core Workflow".to_string(),
        file: "core-workflow.md".to_string(),
        topics: vec!["Workflow execution".to_string()],
    }];

    create_mock_features(temp_dir.path(), &features)?;
    create_mock_chapters(temp_dir.path(), &chapters)?;

    // Run gap detection
    let gaps = detect_gaps(&features, &chapters);

    // Should detect the advanced_retry gap
    assert_eq!(gaps.len(), 1, "Should detect 1 missing chapter");

    let (chapter_id, _, _) = &gaps[0];
    assert_eq!(chapter_id, "advanced-retry");

    // Note: Severity classification would be done by the actual implementation
    // based on feature usage patterns and metadata

    Ok(())
}

#[test]
fn test_summary_update_logic() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let book_dir = temp_dir.path().join("book");
    let src_dir = book_dir.join("src");
    fs::create_dir_all(&src_dir)?;

    // Create initial SUMMARY.md
    let summary_path = src_dir.join("SUMMARY.md");
    let initial_summary = r#"# Summary

- [Introduction](introduction.md)

## User Guide

- [Workflow Basics](workflow-basics.md)

## Advanced Topics

- [MapReduce](mapreduce.md)
"#;
    fs::write(&summary_path, initial_summary)?;

    // Verify we can parse and update the summary
    let content = fs::read_to_string(&summary_path)?;

    assert!(content.contains("# Summary"), "Should have title");
    assert!(
        content.contains("## User Guide"),
        "Should have User Guide section"
    );
    assert!(
        content.contains("## Advanced Topics"),
        "Should have Advanced Topics section"
    );

    // Simulate adding a new chapter
    let updated_summary = content.replace(
        "## Advanced Topics\n\n- [MapReduce](mapreduce.md)",
        "## Advanced Topics\n\n- [Agent Merge](agent-merge.md)\n- [MapReduce](mapreduce.md)",
    );

    fs::write(&summary_path, updated_summary)?;

    // Verify update
    let final_content = fs::read_to_string(&summary_path)?;
    assert!(
        final_content.contains("[Agent Merge](agent-merge.md)"),
        "Should contain new chapter"
    );

    Ok(())
}

#[test]
fn test_gap_detection_with_empty_features() -> Result<()> {
    let temp_dir = TempDir::new()?;

    let features = vec![];
    let chapters = vec![MockChapter {
        id: "existing".to_string(),
        title: "Existing Chapter".to_string(),
        file: "existing.md".to_string(),
        topics: vec!["Topic".to_string()],
    }];

    create_mock_features(temp_dir.path(), &features)?;
    create_mock_chapters(temp_dir.path(), &chapters)?;

    // Run gap detection
    let gaps = detect_gaps(&features, &chapters);

    // Should detect no gaps with no features
    assert_eq!(gaps.len(), 0, "No features means no gaps");

    Ok(())
}

#[test]
fn test_gap_detection_with_empty_chapters() -> Result<()> {
    let temp_dir = TempDir::new()?;

    let features = vec![
        MockFeature {
            category: "feature1".to_string(),
            description: "Feature 1".to_string(),
            capabilities: vec!["cap1".to_string()],
        },
        MockFeature {
            category: "feature2".to_string(),
            description: "Feature 2".to_string(),
            capabilities: vec!["cap2".to_string()],
        },
    ];

    let chapters = vec![];

    create_mock_features(temp_dir.path(), &features)?;
    create_mock_chapters(temp_dir.path(), &chapters)?;

    // Run gap detection
    let gaps = detect_gaps(&features, &chapters);

    // Should detect gaps for all features
    assert_eq!(gaps.len(), 2, "All features should be gaps");

    Ok(())
}