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
use super::manager_queries::{filter_sessions_by_status, load_state_from_file};
use super::*;
use crate::subprocess::SubprocessManager;
use crate::testing::fixtures::isolation::TestGitRepo;
use std::process::Command;
use tempfile::TempDir;

fn setup_test_repo() -> anyhow::Result<TempDir> {
    let temp_dir = TempDir::new()?;

    // Initialize git repo
    Command::new("git")
        .current_dir(&temp_dir)
        .args(["init"])
        .output()?;

    // Configure git user
    Command::new("git")
        .current_dir(&temp_dir)
        .args(["config", "user.email", "test@test.com"])
        .output()?;
    Command::new("git")
        .current_dir(&temp_dir)
        .args(["config", "user.name", "Test User"])
        .output()?;

    // Create initial commit
    std::fs::write(temp_dir.path().join("README.md"), "# Test Repo")?;
    Command::new("git")
        .current_dir(&temp_dir)
        .args(["add", "."])
        .output()?;
    Command::new("git")
        .current_dir(&temp_dir)
        .args(["commit", "-m", "Initial commit"])
        .output()?;

    Ok(temp_dir)
}

// Clean up worktree manager's base directory after tests
fn cleanup_worktree_dir(manager: &WorktreeManager) {
    if manager.base_dir.exists() {
        std::fs::remove_dir_all(&manager.base_dir).ok();
    }
}

#[test]
fn test_worktree_manager_creation() -> anyhow::Result<()> {
    let temp_dir = setup_test_repo()?;
    let subprocess = SubprocessManager::production();
    let manager = WorktreeManager::new(temp_dir.path().to_path_buf(), subprocess)?;

    assert!(manager.base_dir.exists());

    // During tests, the manager uses a temp directory instead of home directory
    // Just verify the base_dir exists and contains expected structure
    assert!(manager.base_dir.to_string_lossy().contains("worktrees"));

    // The repo name is derived from temp_dir's file name
    let repo_name = temp_dir.path().file_name().unwrap().to_str().unwrap();
    assert!(manager.base_dir.to_string_lossy().contains(repo_name));

    // Clean up
    cleanup_worktree_dir(&manager);
    Ok(())
}

#[tokio::test]
async fn test_create_session_with_generated_name() -> anyhow::Result<()> {
    let temp_dir = setup_test_repo()?;
    let subprocess = SubprocessManager::production();
    let manager = WorktreeManager::new(temp_dir.path().to_path_buf(), subprocess)?;

    let session = manager.create_session().await?;

    assert!(session.name.starts_with("session-"));
    assert!(session.path.exists());
    assert_eq!(session.branch, format!("prodigy-{}", session.name));

    // Verify worktree was created
    let worktrees_output = Command::new("git")
        .current_dir(&temp_dir)
        .args(["worktree", "list"])
        .output()?;
    let worktrees = String::from_utf8_lossy(&worktrees_output.stdout);
    assert!(worktrees.contains(&session.name));

    // Clean up
    manager.cleanup_session(&session.name, false).await?;
    cleanup_worktree_dir(&manager);
    Ok(())
}

#[tokio::test]
async fn test_create_session_with_uuid_name() -> anyhow::Result<()> {
    let temp_dir = setup_test_repo()?;
    let subprocess = SubprocessManager::production();
    let manager = WorktreeManager::new(temp_dir.path().to_path_buf(), subprocess)?;

    let session = manager.create_session().await?;

    assert!(session.name.starts_with("session-"));
    assert!(session.path.exists());

    // Clean up
    manager.cleanup_session(&session.name, false).await?;
    cleanup_worktree_dir(&manager);
    Ok(())
}

#[tokio::test]
async fn test_list_sessions() -> anyhow::Result<()> {
    let temp_dir = setup_test_repo()?;
    let subprocess = SubprocessManager::production();
    let manager = WorktreeManager::new(temp_dir.path().to_path_buf(), subprocess)?;

    // Create multiple sessions
    let session1 = manager.create_session().await?;
    let session2 = manager.create_session().await?;

    // List sessions
    let sessions = manager.list_sessions().await?;
    assert!(sessions.len() >= 2);

    // Clean up
    manager.cleanup_session(&session1.name, false).await?;
    manager.cleanup_session(&session2.name, false).await?;
    cleanup_worktree_dir(&manager);
    Ok(())
}

#[tokio::test]
async fn test_cleanup_session() -> anyhow::Result<()> {
    let temp_dir = setup_test_repo()?;
    let subprocess = SubprocessManager::production();
    let manager = WorktreeManager::new(temp_dir.path().to_path_buf(), subprocess)?;

    let session = manager.create_session().await?;
    let session_path = session.path.clone();

    // Verify session exists
    assert!(session_path.exists());

    // Cleanup session
    manager.cleanup_session(&session.name, false).await?;

    // Verify session is removed
    assert!(!session_path.exists());

    // Verify worktree is removed
    let worktrees_output = Command::new("git")
        .current_dir(&temp_dir)
        .args(["worktree", "list"])
        .output()?;
    let worktrees = String::from_utf8_lossy(&worktrees_output.stdout);
    assert!(!worktrees.contains(&session.name));

    cleanup_worktree_dir(&manager);
    Ok(())
}

#[tokio::test]
async fn test_merge_session() -> anyhow::Result<()> {
    let temp_dir = setup_test_repo()?;
    let subprocess = SubprocessManager::production();
    let manager = WorktreeManager::new(temp_dir.path().to_path_buf(), subprocess)?;

    let session = manager.create_session().await?;

    // Make a change in the worktree
    std::fs::write(session.path.join("test.txt"), "test content")?;
    Command::new("git")
        .current_dir(&session.path)
        .args(["add", "test.txt"])
        .output()?;
    Command::new("git")
        .current_dir(&session.path)
        .args(["commit", "-m", "test commit"])
        .output()?;

    // We can't actually test merge without Claude CLI
    // But we can verify the setup is correct

    // Clean up - use force=true since we made commits in the worktree
    manager.cleanup_session(&session.name, true).await?;
    cleanup_worktree_dir(&manager);
    Ok(())
}

#[tokio::test]
async fn test_merge_already_merged() -> anyhow::Result<()> {
    let temp_dir = setup_test_repo()?;
    let subprocess = SubprocessManager::production();
    let manager = WorktreeManager::new(temp_dir.path().to_path_buf(), subprocess)?;

    let session = manager.create_session().await?;

    // Clean up
    manager.cleanup_session(&session.name, false).await?;
    cleanup_worktree_dir(&manager);
    Ok(())
}

#[tokio::test]
async fn test_list_interrupted_sessions_empty() -> anyhow::Result<()> {
    let temp_dir = setup_test_repo()?;
    let subprocess = SubprocessManager::production();
    let manager = WorktreeManager::new(temp_dir.path().to_path_buf(), subprocess)?;

    // With no sessions, should return empty list
    let interrupted = manager.list_interrupted_sessions()?;
    assert_eq!(interrupted.len(), 0);

    cleanup_worktree_dir(&manager);
    Ok(())
}

#[tokio::test]
async fn test_list_interrupted_sessions_with_mixed_states() -> anyhow::Result<()> {
    let temp_dir = setup_test_repo()?;
    let subprocess = SubprocessManager::production();
    let manager = WorktreeManager::new(temp_dir.path().to_path_buf(), subprocess)?;

    // Create multiple sessions
    let session1 = manager.create_session().await?;
    let session2 = manager.create_session().await?;
    let session3 = manager.create_session().await?;

    // Set different states for each session
    manager.update_session_state(&session1.name, |state| {
        state.status = WorktreeStatus::Interrupted;
    })?;

    manager.update_session_state(&session2.name, |state| {
        state.status = WorktreeStatus::Completed;
    })?;

    manager.update_session_state(&session3.name, |state| {
        state.status = WorktreeStatus::Interrupted;
    })?;

    // Should return only interrupted sessions
    let interrupted = manager.list_interrupted_sessions()?;
    assert_eq!(interrupted.len(), 2);

    // Verify the interrupted sessions are the correct ones
    let interrupted_names: Vec<String> = interrupted.iter().map(|s| s.session_id.clone()).collect();
    assert!(interrupted_names.contains(&session1.name));
    assert!(interrupted_names.contains(&session3.name));
    assert!(!interrupted_names.contains(&session2.name));

    // Clean up
    manager.cleanup_session(&session1.name, false).await?;
    manager.cleanup_session(&session2.name, false).await?;
    manager.cleanup_session(&session3.name, false).await?;
    cleanup_worktree_dir(&manager);
    Ok(())
}

#[tokio::test]
async fn test_list_interrupted_sessions_all_interrupted() -> anyhow::Result<()> {
    let temp_dir = setup_test_repo()?;
    let subprocess = SubprocessManager::production();
    let manager = WorktreeManager::new(temp_dir.path().to_path_buf(), subprocess)?;

    // Create sessions and mark all as interrupted
    let session1 = manager.create_session().await?;
    let session2 = manager.create_session().await?;

    manager.update_session_state(&session1.name, |state| {
        state.status = WorktreeStatus::Interrupted;
        state.iterations.completed = 3;
    })?;

    manager.update_session_state(&session2.name, |state| {
        state.status = WorktreeStatus::Interrupted;
        state.iterations.completed = 5;
    })?;

    // Should return all sessions
    let interrupted = manager.list_interrupted_sessions()?;
    assert_eq!(interrupted.len(), 2);

    // Verify iteration counts are preserved
    for state in &interrupted {
        if state.session_id == session1.name {
            assert_eq!(state.iterations.completed, 3);
        } else if state.session_id == session2.name {
            assert_eq!(state.iterations.completed, 5);
        }
    }

    // Clean up
    manager.cleanup_session(&session1.name, false).await?;
    manager.cleanup_session(&session2.name, false).await?;
    cleanup_worktree_dir(&manager);
    Ok(())
}

#[tokio::test]
async fn test_list_interrupted_sessions_none_interrupted() -> anyhow::Result<()> {
    let temp_dir = setup_test_repo()?;
    let subprocess = SubprocessManager::production();
    let manager = WorktreeManager::new(temp_dir.path().to_path_buf(), subprocess)?;

    // Create sessions with non-interrupted states
    let session1 = manager.create_session().await?;
    let session2 = manager.create_session().await?;

    manager.update_session_state(&session1.name, |state| {
        state.status = WorktreeStatus::Completed;
    })?;

    manager.update_session_state(&session2.name, |state| {
        state.status = WorktreeStatus::Merged;
    })?;

    // Should return empty list
    let interrupted = manager.list_interrupted_sessions()?;
    assert_eq!(interrupted.len(), 0);

    // Clean up
    manager.cleanup_session(&session1.name, false).await?;
    manager.cleanup_session(&session2.name, false).await?;
    cleanup_worktree_dir(&manager);
    Ok(())
}

#[test]
fn test_filter_sessions_by_status() {
    use super::{IterationInfo, WorktreeState, WorktreeStats, WorktreeStatus};
    use chrono::Utc;

    // Create test states with different statuses
    let states = vec![
        WorktreeState {
            session_id: "session1".to_string(),
            worktree_name: "wt1".to_string(),
            branch: "branch1".to_string(),
            original_branch: String::new(),
            status: WorktreeStatus::Interrupted,
            created_at: Utc::now(),
            updated_at: Utc::now(),
            iterations: IterationInfo {
                completed: 0,
                max: 10,
            },
            stats: WorktreeStats::default(),
            merged: false,
            merged_at: None,
            error: None,
            merge_prompt_shown: false,
            merge_prompt_response: None,
            interrupted_at: None,
            interruption_type: None,
            last_checkpoint: None,
            resumable: true,
        },
        WorktreeState {
            session_id: "session2".to_string(),
            worktree_name: "wt2".to_string(),
            branch: "branch2".to_string(),
            original_branch: String::new(),
            status: WorktreeStatus::Completed,
            created_at: Utc::now(),
            updated_at: Utc::now(),
            iterations: IterationInfo {
                completed: 5,
                max: 10,
            },
            stats: WorktreeStats::default(),
            merged: false,
            merged_at: None,
            error: None,
            merge_prompt_shown: false,
            merge_prompt_response: None,
            interrupted_at: None,
            interruption_type: None,
            last_checkpoint: None,
            resumable: true,
        },
        WorktreeState {
            session_id: "session3".to_string(),
            worktree_name: "wt3".to_string(),
            branch: "branch3".to_string(),
            original_branch: String::new(),
            status: WorktreeStatus::Interrupted,
            created_at: Utc::now(),
            updated_at: Utc::now(),
            iterations: IterationInfo {
                completed: 2,
                max: 10,
            },
            stats: WorktreeStats::default(),
            merged: false,
            merged_at: None,
            error: None,
            merge_prompt_shown: false,
            merge_prompt_response: None,
            interrupted_at: None,
            interruption_type: None,
            last_checkpoint: None,
            resumable: true,
        },
    ];

    // Test filtering for interrupted sessions
    let interrupted = filter_sessions_by_status(states.clone(), WorktreeStatus::Interrupted);
    assert_eq!(interrupted.len(), 2);
    assert!(interrupted
        .iter()
        .all(|s| s.status == WorktreeStatus::Interrupted));

    // Test filtering for completed sessions
    let completed = filter_sessions_by_status(states.clone(), WorktreeStatus::Completed);
    assert_eq!(completed.len(), 1);
    assert_eq!(completed[0].session_id, "session2");

    // Test filtering for non-existent status
    let merged = filter_sessions_by_status(states, WorktreeStatus::Merged);
    assert_eq!(merged.len(), 0);
}

#[test]
fn test_load_state_from_file() {
    use super::{IterationInfo, WorktreeState, WorktreeStats, WorktreeStatus};
    use chrono::Utc;
    use std::fs;
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();

    // Create a valid state
    let state = WorktreeState {
        session_id: "test-session".to_string(),
        worktree_name: "test-wt".to_string(),
        branch: "test-branch".to_string(),
        original_branch: String::new(),
        status: WorktreeStatus::InProgress,
        created_at: Utc::now(),
        updated_at: Utc::now(),
        iterations: IterationInfo {
            completed: 0,
            max: 10,
        },
        stats: WorktreeStats::default(),
        merged: false,
        merged_at: None,
        error: None,
        merge_prompt_shown: false,
        merge_prompt_response: None,
        interrupted_at: None,
        interruption_type: None,
        last_checkpoint: None,
        resumable: true,
    };

    // Write valid JSON file
    let json_path = temp_dir.path().join("state.json");
    fs::write(&json_path, serde_json::to_string(&state).unwrap()).unwrap();

    // Should successfully load the state
    let loaded = load_state_from_file(&json_path);
    assert!(loaded.is_some());
    assert_eq!(loaded.unwrap().session_id, "test-session");

    // Test with non-JSON file
    let txt_path = temp_dir.path().join("state.txt");
    fs::write(&txt_path, "not json").unwrap();
    assert!(load_state_from_file(&txt_path).is_none());

    // Test with invalid JSON
    let bad_json_path = temp_dir.path().join("bad.json");
    fs::write(&bad_json_path, "{ invalid json }").unwrap();
    assert!(load_state_from_file(&bad_json_path).is_none());

    // Test with non-existent file
    let missing_path = temp_dir.path().join("missing.json");
    assert!(load_state_from_file(&missing_path).is_none());
}

#[tokio::test]
async fn test_worktree_tracks_feature_branch() -> anyhow::Result<()> {
    // Use TestGitRepo for isolation
    let repo = TestGitRepo::new()?;

    // Create initial commit
    std::fs::write(repo.path().join("README.md"), "# Test Repo")?;
    Command::new("git")
        .current_dir(repo.path())
        .args(["add", "."])
        .output()?;
    repo.commit("Initial commit")?;

    let subprocess = SubprocessManager::production();
    let manager = WorktreeManager::new(repo.path().to_path_buf(), subprocess)?;

    // Create a feature branch and check it out
    repo.create_branch("feature/my-feature")?;

    // Create session from the feature branch
    let session = manager.create_session().await?;

    // Verify the session was created with correct original branch
    let state = manager.get_session_state(&session.name)?;
    assert_eq!(state.original_branch, "feature/my-feature");

    // Verify get_merge_target returns the feature branch
    let merge_target = manager.get_merge_target(&session.name).await?;
    assert_eq!(merge_target, "feature/my-feature");

    // Clean up
    manager.cleanup_session(&session.name, false).await?;
    cleanup_worktree_dir(&manager);
    Ok(())
}

#[tokio::test]
async fn test_worktree_from_detached_head() -> anyhow::Result<()> {
    let temp_dir = setup_test_repo()?;
    let subprocess = SubprocessManager::production();
    let manager = WorktreeManager::new(temp_dir.path().to_path_buf(), subprocess)?;

    // Get the current commit hash
    let commit_output = Command::new("git")
        .current_dir(&temp_dir)
        .args(["rev-parse", "HEAD"])
        .output()?;
    let commit_hash = String::from_utf8_lossy(&commit_output.stdout)
        .trim()
        .to_string();

    // Checkout detached HEAD
    Command::new("git")
        .current_dir(&temp_dir)
        .args(["checkout", &commit_hash])
        .output()?;

    // Determine the default branch
    let default_branch_output = Command::new("git")
        .current_dir(&temp_dir)
        .args(["rev-parse", "--abbrev-ref", "HEAD"])
        .output()?;
    let default_branch_str = String::from_utf8_lossy(&default_branch_output.stdout);
    let default_branch = default_branch_str.trim();

    // If HEAD is detached, this should return "HEAD", so we need to find the default branch
    let default_branch = if default_branch == "HEAD" {
        // Get the default branch from symbolic-ref
        let symbolic_output = Command::new("git")
            .current_dir(&temp_dir)
            .args(["symbolic-ref", "refs/remotes/origin/HEAD"])
            .output();

        if let Ok(output) = symbolic_output {
            let symbolic_ref = String::from_utf8_lossy(&output.stdout);
            symbolic_ref
                .trim()
                .strip_prefix("refs/remotes/origin/")
                .unwrap_or("master")
                .to_string()
        } else {
            // Fallback: check if master or main exists
            let branches_output = Command::new("git")
                .current_dir(&temp_dir)
                .args(["branch", "--list", "master", "main"])
                .output()?;
            let branches = String::from_utf8_lossy(&branches_output.stdout);
            if branches.contains("master") {
                "master".to_string()
            } else if branches.contains("main") {
                "main".to_string()
            } else {
                "master".to_string()
            }
        }
    } else {
        default_branch.to_string()
    };

    // Create session from detached HEAD
    let session = manager.create_session().await?;

    // Verify the session tracks the default branch as fallback
    let state = manager.get_session_state(&session.name)?;
    assert_eq!(state.original_branch, default_branch);

    // Clean up
    manager.cleanup_session(&session.name, false).await?;
    cleanup_worktree_dir(&manager);
    Ok(())
}

#[tokio::test]
async fn test_original_branch_deleted() -> anyhow::Result<()> {
    // Use TestGitRepo for isolation
    let repo = TestGitRepo::new()?;

    // Create initial commit on master
    std::fs::write(repo.path().join("README.md"), "# Test Repo")?;
    Command::new("git")
        .current_dir(repo.path())
        .args(["add", "."])
        .output()?;
    repo.commit("Initial commit")?;

    let subprocess = SubprocessManager::production();
    let manager = WorktreeManager::new(repo.path().to_path_buf(), subprocess)?;

    // Create a feature branch
    repo.create_branch("feature/temp-branch")?;

    // Create session from the feature branch
    let session = manager.create_session().await?;

    // Verify original branch is tracked
    let state = manager.get_session_state(&session.name)?;
    assert_eq!(state.original_branch, "feature/temp-branch");

    // Switch back to master and delete the feature branch
    repo.checkout("master")?;
    Command::new("git")
        .current_dir(repo.path())
        .args(["branch", "-D", "feature/temp-branch"])
        .output()?;

    // Get merge target should fall back to default branch
    let merge_target = manager.get_merge_target(&session.name).await?;

    // The default branch should be master or main
    let default_branch_output = Command::new("git")
        .current_dir(repo.path())
        .args(["symbolic-ref", "refs/remotes/origin/HEAD"])
        .output();

    let expected_branch = if let Ok(output) = default_branch_output {
        let symbolic_ref = String::from_utf8_lossy(&output.stdout);
        symbolic_ref
            .trim()
            .strip_prefix("refs/remotes/origin/")
            .unwrap_or("master")
            .to_string()
    } else {
        // Check which branch exists
        let branches_output = Command::new("git")
            .current_dir(repo.path())
            .args(["branch", "--list", "master", "main"])
            .output()?;
        let branches = String::from_utf8_lossy(&branches_output.stdout);
        if branches.contains("master") {
            "master".to_string()
        } else {
            "main".to_string()
        }
    };

    assert_eq!(merge_target, expected_branch);

    // Clean up
    manager.cleanup_session(&session.name, false).await?;
    cleanup_worktree_dir(&manager);
    Ok(())
}