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
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
//! Unit tests for enhanced progress tracking

use super::progress::*;
use crate::cook::execution::errors::MapReduceResult;
use chrono::Utc;
use std::time::Duration;
use tokio::time::sleep;

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

    #[tokio::test]
    async fn test_new_tracker_initialization() {
        let tracker = EnhancedProgressTracker::new("test-job-123".to_string(), 100);

        assert_eq!(tracker.job_id, "test-job-123");
        assert_eq!(tracker.total_items, 100);

        let metrics = tracker.metrics.read().await;
        assert_eq!(metrics.pending_items, 100);
        assert_eq!(metrics.completed_items, 0);
        assert_eq!(metrics.failed_items, 0);
        assert_eq!(metrics.active_agents, 0);
    }

    #[tokio::test]
    async fn test_update_agent_progress() {
        let tracker = EnhancedProgressTracker::new("test-job".to_string(), 10);

        let progress = AgentProgress {
            agent_id: "agent-1".to_string(),
            item_id: "item-1".to_string(),
            state: AgentState::Running {
                step: "Processing".to_string(),
                progress: 50.0,
            },
            current_step: "Step 2 of 4".to_string(),
            steps_completed: 2,
            total_steps: 4,
            progress_percentage: 50.0,
            started_at: Utc::now(),
            last_update: Utc::now(),
            estimated_completion: Some(Utc::now() + chrono::Duration::seconds(60)),
            error_count: 0,
            retry_count: 0,
        };

        tracker
            .update_agent_progress("agent-1", progress.clone())
            .await
            .unwrap();

        let agents = tracker.agents.read().await;
        assert_eq!(agents.len(), 1);
        assert!(agents.contains_key("agent-1"));

        let stored_progress = &agents["agent-1"];
        assert_eq!(stored_progress.agent_id, "agent-1");
        assert_eq!(stored_progress.progress_percentage, 50.0);
    }

    #[tokio::test]
    async fn test_mark_item_completed() {
        let tracker = EnhancedProgressTracker::new("test-job".to_string(), 10);

        // First add an agent
        let progress = AgentProgress {
            agent_id: "agent-1".to_string(),
            item_id: "item-1".to_string(),
            state: AgentState::Running {
                step: "Processing".to_string(),
                progress: 90.0,
            },
            current_step: "Final step".to_string(),
            steps_completed: 3,
            total_steps: 4,
            progress_percentage: 90.0,
            started_at: Utc::now(),
            last_update: Utc::now(),
            estimated_completion: None,
            error_count: 0,
            retry_count: 0,
        };

        tracker
            .update_agent_progress("agent-1", progress)
            .await
            .unwrap();
        tracker.mark_item_completed("agent-1").await.unwrap();

        let agents = tracker.agents.read().await;
        assert!(matches!(agents["agent-1"].state, AgentState::Completed));

        let metrics = tracker.metrics.read().await;
        assert_eq!(metrics.completed_items, 1);
        assert_eq!(metrics.pending_items, 9);
    }

    #[tokio::test]
    async fn test_mark_item_failed() {
        let tracker = EnhancedProgressTracker::new("test-job".to_string(), 10);

        // First add an agent
        let progress = AgentProgress {
            agent_id: "agent-1".to_string(),
            item_id: "item-1".to_string(),
            state: AgentState::Running {
                step: "Processing".to_string(),
                progress: 50.0,
            },
            current_step: "Step 2".to_string(),
            steps_completed: 2,
            total_steps: 4,
            progress_percentage: 50.0,
            started_at: Utc::now(),
            last_update: Utc::now(),
            estimated_completion: None,
            error_count: 1,
            retry_count: 0,
        };

        tracker
            .update_agent_progress("agent-1", progress)
            .await
            .unwrap();
        tracker
            .mark_item_failed("agent-1", "Test error".to_string())
            .await
            .unwrap();

        let agents = tracker.agents.read().await;
        assert!(matches!(
            &agents["agent-1"].state,
            AgentState::Failed { error } if error == "Test error"
        ));

        let metrics = tracker.metrics.read().await;
        assert_eq!(metrics.failed_items, 1);
        assert_eq!(metrics.pending_items, 9);
    }

    #[tokio::test]
    async fn test_overall_progress_calculation() {
        let tracker = EnhancedProgressTracker::new("test-job".to_string(), 10);

        // Mark some items as completed
        for i in 0..3 {
            let agent_id = format!("agent-{}", i);
            let progress = AgentProgress {
                agent_id: agent_id.clone(),
                item_id: format!("item-{}", i),
                state: AgentState::Completed,
                current_step: "Done".to_string(),
                steps_completed: 4,
                total_steps: 4,
                progress_percentage: 100.0,
                started_at: Utc::now(),
                last_update: Utc::now(),
                estimated_completion: None,
                error_count: 0,
                retry_count: 0,
            };
            tracker
                .update_agent_progress(&agent_id, progress)
                .await
                .unwrap();
            tracker.mark_item_completed(&agent_id).await.unwrap();
        }

        // Mark one as failed
        let progress = AgentProgress {
            agent_id: "agent-fail".to_string(),
            item_id: "item-fail".to_string(),
            state: AgentState::Failed {
                error: "Error".to_string(),
            },
            current_step: "Failed".to_string(),
            steps_completed: 1,
            total_steps: 4,
            progress_percentage: 25.0,
            started_at: Utc::now(),
            last_update: Utc::now(),
            estimated_completion: None,
            error_count: 1,
            retry_count: 0,
        };
        tracker
            .update_agent_progress("agent-fail", progress)
            .await
            .unwrap();
        tracker
            .mark_item_failed("agent-fail", "Error".to_string())
            .await
            .unwrap();

        let overall_progress = tracker.get_overall_progress().await;
        assert_eq!(overall_progress, 40.0); // 4 out of 10 items processed
    }

    #[tokio::test]
    async fn test_export_json_format() {
        let tracker = EnhancedProgressTracker::new("test-job".to_string(), 5);

        // Add some test data
        let progress = AgentProgress {
            agent_id: "agent-1".to_string(),
            item_id: "item-1".to_string(),
            state: AgentState::Completed,
            current_step: "Done".to_string(),
            steps_completed: 4,
            total_steps: 4,
            progress_percentage: 100.0,
            started_at: Utc::now(),
            last_update: Utc::now(),
            estimated_completion: None,
            error_count: 0,
            retry_count: 0,
        };
        tracker
            .update_agent_progress("agent-1", progress)
            .await
            .unwrap();
        tracker.mark_item_completed("agent-1").await.unwrap();

        let exported = tracker.export_progress(ExportFormat::Json).await.unwrap();
        let json_str = String::from_utf8(exported).unwrap();

        // Parse and validate JSON
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        assert_eq!(parsed["job_id"], "test-job");
        assert_eq!(parsed["metrics"]["completed_items"], 1);
    }

    #[tokio::test]
    async fn test_export_csv_format() {
        let tracker = EnhancedProgressTracker::new("test-job".to_string(), 5);

        let exported = tracker.export_progress(ExportFormat::Csv).await.unwrap();
        let csv_str = String::from_utf8(exported).unwrap();

        // Verify CSV headers
        assert!(csv_str.contains("timestamp,job_id,completed_items"));
        assert!(csv_str.contains("test-job"));
    }

    #[tokio::test]
    async fn test_export_html_format() {
        let tracker = EnhancedProgressTracker::new("test-job".to_string(), 5);

        let exported = tracker.export_progress(ExportFormat::Html).await.unwrap();
        let html_str = String::from_utf8(exported).unwrap();

        // Verify HTML content
        assert!(html_str.contains("<!DOCTYPE html>"));
        assert!(html_str.contains("test-job"));
        assert!(html_str.contains("MapReduce Job Progress Report"));
    }

    #[tokio::test]
    async fn test_create_snapshot() {
        let tracker = EnhancedProgressTracker::new("test-job".to_string(), 10);

        // Add some agents
        for i in 0..3 {
            let progress = AgentProgress {
                agent_id: format!("agent-{}", i),
                item_id: format!("item-{}", i),
                state: if i == 0 {
                    AgentState::Completed
                } else {
                    AgentState::Running {
                        step: "Processing".to_string(),
                        progress: 50.0,
                    }
                },
                current_step: format!("Step {}", i),
                steps_completed: i,
                total_steps: 4,
                progress_percentage: (i as f32) * 25.0,
                started_at: Utc::now(),
                last_update: Utc::now(),
                estimated_completion: None,
                error_count: 0,
                retry_count: 0,
            };
            tracker
                .update_agent_progress(&format!("agent-{}", i), progress)
                .await
                .unwrap();
        }

        let snapshot = tracker.create_snapshot().await;

        assert_eq!(snapshot.job_id, "test-job");
        assert_eq!(snapshot.agent_states.len(), 3);
        assert!(snapshot.agent_states.contains_key("agent-0"));
        assert!(matches!(
            snapshot.agent_states["agent-0"],
            AgentState::Completed
        ));
    }

    #[tokio::test]
    async fn test_metrics_recalculation() {
        let tracker = EnhancedProgressTracker::new("test-job".to_string(), 100);

        // Add active agents
        for i in 0..5 {
            let progress = AgentProgress {
                agent_id: format!("agent-{}", i),
                item_id: format!("item-{}", i),
                state: AgentState::Running {
                    step: "Processing".to_string(),
                    progress: 50.0,
                },
                current_step: "Working".to_string(),
                steps_completed: 2,
                total_steps: 4,
                progress_percentage: 50.0,
                started_at: Utc::now(),
                last_update: Utc::now(),
                estimated_completion: None,
                error_count: 0,
                retry_count: 0,
            };
            tracker
                .update_agent_progress(&format!("agent-{}", i), progress)
                .await
                .unwrap();
        }

        // Mark some as completed
        for i in 0..3 {
            tracker
                .mark_item_completed(&format!("agent-{}", i))
                .await
                .unwrap();
        }

        // Wait a bit for throughput calculation
        sleep(Duration::from_millis(100)).await;

        let metrics = tracker.metrics.read().await;
        assert_eq!(metrics.completed_items, 3);
        assert!(metrics.throughput_average > 0.0);
        assert_eq!(metrics.success_rate, 100.0);
        assert!(metrics.estimated_completion.is_some());
    }

    #[tokio::test]
    async fn test_agent_state_transitions() {
        let tracker = EnhancedProgressTracker::new("test-job".to_string(), 10);

        let agent_id = "agent-1";

        // Start as queued
        tracker
            .update_agent_state(agent_id, AgentState::Queued)
            .await
            .unwrap();
        {
            let agents = tracker.agents.read().await;
            assert!(
                matches!(agents.get(agent_id), Some(agent) if matches!(agent.state, AgentState::Queued))
            );
        }

        // Move to initializing
        tracker
            .update_agent_state(agent_id, AgentState::Initializing)
            .await
            .unwrap();
        {
            let agents = tracker.agents.read().await;
            assert!(
                matches!(agents.get(agent_id), Some(agent) if matches!(agent.state, AgentState::Initializing))
            );
        }

        // Move to running
        tracker
            .update_agent_state(
                agent_id,
                AgentState::Running {
                    step: "Processing".to_string(),
                    progress: 25.0,
                },
            )
            .await
            .unwrap();
        {
            let agents = tracker.agents.read().await;
            assert!(matches!(
                agents.get(agent_id),
                Some(agent) if matches!(agent.state, AgentState::Running { .. })
            ));
        }

        // Move to retrying
        tracker
            .update_agent_state(agent_id, AgentState::Retrying { attempt: 1 })
            .await
            .unwrap();
        {
            let agents = tracker.agents.read().await;
            assert!(matches!(
                agents.get(agent_id),
                Some(agent) if matches!(agent.state, AgentState::Retrying { attempt: 1 })
            ));
        }

        // Move to dead-lettered
        tracker
            .update_agent_state(agent_id, AgentState::DeadLettered)
            .await
            .unwrap();
        {
            let agents = tracker.agents.read().await;
            assert!(matches!(
                agents.get(agent_id),
                Some(agent) if matches!(agent.state, AgentState::DeadLettered)
            ));
        }
    }
}

#[cfg(test)]
mod cli_progress_viewer_tests {
    use super::*;
    use std::sync::Arc;

    #[tokio::test]
    async fn test_cli_viewer_initialization() {
        let tracker = Arc::new(EnhancedProgressTracker::new("test-job".to_string(), 10));
        let _viewer = CLIProgressViewer::new(tracker.clone());

        // Viewer initialized correctly with expected interval
    }

    #[tokio::test]
    async fn test_progress_bar_creation() {
        let tracker = Arc::new(EnhancedProgressTracker::new("test-job".to_string(), 10));
        let viewer = CLIProgressViewer::new(tracker);

        // Test various percentages
        let bar_0 = viewer.create_progress_bar(0.0);
        assert_eq!(bar_0, "â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘");

        let bar_50 = viewer.create_progress_bar(50.0);
        assert_eq!(bar_50, "██████████░░░░░░░░░░");

        let bar_100 = viewer.create_progress_bar(100.0);
        assert_eq!(bar_100, "████████████████████");
    }

    #[test]
    fn test_format_duration() {
        use crate::cook::execution::progress::format_duration;
        assert_eq!(format_duration(Duration::from_secs(30)), "30s");
        assert_eq!(format_duration(Duration::from_secs(90)), "1m 30s");
        assert_eq!(format_duration(Duration::from_secs(3665)), "1h 1m 5s");
        assert_eq!(format_duration(Duration::from_secs(7322)), "2h 2m 2s");
    }

    #[test]
    fn test_is_job_complete_when_no_pending_and_no_active() {
        let metrics = ProgressMetrics {
            pending_items: 0,
            active_agents: 0,
            completed_items: 10,
            failed_items: 2,
            throughput_current: 0.0,
            throughput_average: 5.0,
            success_rate: 83.3,
            average_duration_ms: 1000,
            estimated_completion: None,
            memory_usage_mb: 100,
            cpu_usage_percent: 10.0,
        };

        assert!(CLIProgressViewer::is_job_complete(&metrics));
    }

    #[test]
    fn test_is_job_complete_when_pending_items_remain() {
        let metrics = ProgressMetrics {
            pending_items: 5,
            active_agents: 0,
            completed_items: 10,
            failed_items: 2,
            throughput_current: 0.0,
            throughput_average: 5.0,
            success_rate: 66.7,
            average_duration_ms: 1000,
            estimated_completion: None,
            memory_usage_mb: 100,
            cpu_usage_percent: 10.0,
        };

        assert!(!CLIProgressViewer::is_job_complete(&metrics));
    }

    #[test]
    fn test_is_job_complete_when_active_agents_exist() {
        let metrics = ProgressMetrics {
            pending_items: 0,
            active_agents: 3,
            completed_items: 10,
            failed_items: 2,
            throughput_current: 2.0,
            throughput_average: 5.0,
            success_rate: 83.3,
            average_duration_ms: 1000,
            estimated_completion: None,
            memory_usage_mb: 100,
            cpu_usage_percent: 50.0,
        };

        assert!(!CLIProgressViewer::is_job_complete(&metrics));
    }

    #[test]
    fn test_is_job_complete_when_both_pending_and_active() {
        let metrics = ProgressMetrics {
            pending_items: 5,
            active_agents: 3,
            completed_items: 10,
            failed_items: 2,
            throughput_current: 2.0,
            throughput_average: 5.0,
            success_rate: 50.0,
            average_duration_ms: 1000,
            estimated_completion: None,
            memory_usage_mb: 100,
            cpu_usage_percent: 75.0,
        };

        assert!(!CLIProgressViewer::is_job_complete(&metrics));
    }

    #[tokio::test]
    async fn test_should_use_cached_render_when_should_not_sample() {
        let sampler = ProgressSampler::new(Duration::from_secs(1));
        // Immediately after creation, should not sample (cache is fresh)
        let result = CLIProgressViewer::should_use_cached_render(&sampler).await;
        assert!(result);
    }

    #[tokio::test]
    async fn test_should_use_cached_render_when_should_sample() {
        let sampler = ProgressSampler::new(Duration::from_millis(10));
        // Wait for sample rate to expire
        sleep(Duration::from_millis(20)).await;
        let result = CLIProgressViewer::should_use_cached_render(&sampler).await;
        assert!(!result);
    }

    #[tokio::test]
    async fn test_determine_render_strategy_no_sampler() {
        let strategy = CLIProgressViewer::determine_render_strategy(None).await;
        assert_eq!(strategy, RenderStrategy::Full);
    }

    #[tokio::test]
    async fn test_determine_render_strategy_sampler_should_sample() {
        let sampler = ProgressSampler::new(Duration::from_millis(10));
        // Wait for sample rate to expire so it should sample
        sleep(Duration::from_millis(20)).await;
        let strategy = CLIProgressViewer::determine_render_strategy(Some(&sampler)).await;
        assert_eq!(strategy, RenderStrategy::Full);
    }

    #[tokio::test]
    async fn test_determine_render_strategy_sampler_use_cache_no_data() {
        let sampler = ProgressSampler::new(Duration::from_secs(10));
        // Cache is fresh, should use cached but no data yet
        let strategy = CLIProgressViewer::determine_render_strategy(Some(&sampler)).await;
        assert_eq!(strategy, RenderStrategy::Skip);
    }

    #[tokio::test]
    async fn test_determine_render_strategy_sampler_use_cache_with_data() {
        use std::sync::Arc;

        let tracker = Arc::new(EnhancedProgressTracker::new("test-job".to_string(), 10));
        let sampler = ProgressSampler::new(Duration::from_secs(10));

        // Populate cache with data
        let snapshot = tracker.create_snapshot().await;
        let metrics = tracker.metrics.read().await;
        sampler.update_cache(snapshot, metrics.clone()).await;

        // Cache is fresh and has data, should use cached
        let strategy = CLIProgressViewer::determine_render_strategy(Some(&sampler)).await;
        match strategy {
            RenderStrategy::Cached(cached_metrics) => {
                assert_eq!(cached_metrics.pending_items, 10);
                assert_eq!(cached_metrics.completed_items, 0);
            }
            _ => panic!("Expected Cached strategy, got {:?}", strategy),
        }
    }

    #[tokio::test]
    async fn test_determine_render_strategy_all_combinations() {
        use std::sync::Arc;

        // Test 1: No sampler -> Always Full
        let strategy = CLIProgressViewer::determine_render_strategy(None).await;
        assert_eq!(strategy, RenderStrategy::Full);

        // Test 2: Sampler with expired cache (should sample) -> Full
        let sampler_expired = ProgressSampler::new(Duration::from_millis(10));
        sleep(Duration::from_millis(20)).await;
        let strategy = CLIProgressViewer::determine_render_strategy(Some(&sampler_expired)).await;
        assert_eq!(strategy, RenderStrategy::Full);

        // Test 3: Sampler with fresh cache but no data -> Skip
        let sampler_fresh = ProgressSampler::new(Duration::from_secs(10));
        let strategy = CLIProgressViewer::determine_render_strategy(Some(&sampler_fresh)).await;
        assert_eq!(strategy, RenderStrategy::Skip);

        // Test 4: Sampler with fresh cache and data -> Cached
        let tracker = Arc::new(EnhancedProgressTracker::new("test-job".to_string(), 5));
        let sampler_with_data = ProgressSampler::new(Duration::from_secs(10));
        let snapshot = tracker.create_snapshot().await;
        let metrics = tracker.metrics.read().await;
        sampler_with_data
            .update_cache(snapshot, metrics.clone())
            .await;

        let strategy = CLIProgressViewer::determine_render_strategy(Some(&sampler_with_data)).await;
        assert!(matches!(strategy, RenderStrategy::Cached(_)));
    }

    #[test]
    fn test_is_job_complete_edge_case_zero_items() {
        let metrics = ProgressMetrics {
            pending_items: 0,
            active_agents: 0,
            completed_items: 0,
            failed_items: 0,
            throughput_current: 0.0,
            throughput_average: 0.0,
            success_rate: 0.0,
            average_duration_ms: 0,
            estimated_completion: None,
            memory_usage_mb: 0,
            cpu_usage_percent: 0.0,
        };

        assert!(CLIProgressViewer::is_job_complete(&metrics));
    }

    #[test]
    fn test_is_job_complete_edge_case_large_numbers() {
        let metrics = ProgressMetrics {
            pending_items: 1000,
            active_agents: 50,
            completed_items: 10000,
            failed_items: 500,
            throughput_current: 100.0,
            throughput_average: 95.5,
            success_rate: 95.0,
            average_duration_ms: 5000,
            estimated_completion: None,
            memory_usage_mb: 5000,
            cpu_usage_percent: 95.0,
        };

        assert!(!CLIProgressViewer::is_job_complete(&metrics));
    }

    #[test]
    fn test_is_job_complete_only_failed_items() {
        let metrics = ProgressMetrics {
            pending_items: 0,
            active_agents: 0,
            completed_items: 0,
            failed_items: 100,
            throughput_current: 0.0,
            throughput_average: 10.0,
            success_rate: 0.0,
            average_duration_ms: 1000,
            estimated_completion: None,
            memory_usage_mb: 100,
            cpu_usage_percent: 5.0,
        };

        // Job is complete even if all items failed
        assert!(CLIProgressViewer::is_job_complete(&metrics));
    }

    #[tokio::test]
    async fn test_determine_render_strategy_sampler_transition() {
        use std::sync::Arc;

        // Test transition from Skip to Full when cache expires
        let tracker = Arc::new(EnhancedProgressTracker::new("test-job".to_string(), 5));
        let sampler = ProgressSampler::new(Duration::from_millis(50));

        // Initially fresh, should skip (no cache data yet)
        let strategy1 = CLIProgressViewer::determine_render_strategy(Some(&sampler)).await;
        assert_eq!(strategy1, RenderStrategy::Skip);

        // Add cache data
        let snapshot = tracker.create_snapshot().await;
        let metrics = tracker.metrics.read().await;
        sampler.update_cache(snapshot, metrics.clone()).await;

        // Should use cached now
        let strategy2 = CLIProgressViewer::determine_render_strategy(Some(&sampler)).await;
        assert!(matches!(strategy2, RenderStrategy::Cached(_)));

        // Wait for cache to expire
        sleep(Duration::from_millis(60)).await;

        // Should render full now
        let strategy3 = CLIProgressViewer::determine_render_strategy(Some(&sampler)).await;
        assert_eq!(strategy3, RenderStrategy::Full);
    }
}

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

    #[tokio::test]
    async fn test_web_server_initialization() {
        let mut tracker = EnhancedProgressTracker::new("test-job".to_string(), 10);

        // Start web server on a random port for testing
        let result = tracker.start_web_server(0).await;
        assert!(result.is_ok());
        assert!(tracker.web_server.is_some());
    }

    #[tokio::test]
    async fn test_dashboard_html_exists() {
        // Ensure the dashboard HTML is included
        let html = include_str!("progress_dashboard.html");
        assert!(html.contains("<!DOCTYPE html>"));
        assert!(html.contains("MapReduce Progress Dashboard"));
    }
}

#[cfg(test)]
mod progress_reporter_trait_tests {
    use super::*;
    use async_trait::async_trait;
    use chrono::DateTime;

    // Mock implementation for testing
    struct MockProgressReporter {
        progress: f32,
    }

    #[async_trait]
    impl ProgressReporter for MockProgressReporter {
        async fn update_agent_progress(
            &self,
            _agent_id: &str,
            _progress: AgentProgress,
        ) -> MapReduceResult<()> {
            Ok(())
        }

        async fn get_overall_progress(&self) -> MapReduceResult<f32> {
            Ok(self.progress)
        }

        async fn get_estimated_completion(&self) -> MapReduceResult<Option<DateTime<Utc>>> {
            Ok(Some(Utc::now() + chrono::Duration::seconds(60)))
        }

        async fn export_progress(&self, _format: ExportFormat) -> MapReduceResult<Vec<u8>> {
            Ok(vec![])
        }
    }

    #[tokio::test]
    async fn test_trait_implementation() {
        let reporter = MockProgressReporter { progress: 75.0 };

        let progress = reporter.get_overall_progress().await.unwrap();
        assert_eq!(progress, 75.0);

        let etc = reporter.get_estimated_completion().await.unwrap();
        assert!(etc.is_some());

        let export = reporter.export_progress(ExportFormat::Json).await.unwrap();
        assert_eq!(export.len(), 0);
    }

    #[tokio::test]
    async fn test_enhanced_tracker_implements_trait() {
        let tracker = EnhancedProgressTracker::new("test-job".to_string(), 10);

        // Use the trait methods
        let progress_reporter: &dyn ProgressReporter = &tracker;

        let progress = progress_reporter.get_overall_progress().await.unwrap();
        assert_eq!(progress, 0.0);

        let etc = progress_reporter.get_estimated_completion().await.unwrap();
        assert!(etc.is_none());
    }
}

#[cfg(test)]
mod integration_tests {
    use super::*;
    use std::sync::Arc;

    #[tokio::test]
    async fn test_complete_workflow_simulation() {
        let tracker = EnhancedProgressTracker::new("integration-test".to_string(), 20);

        // Simulate agents processing items
        for i in 0..10 {
            let agent_id = format!("agent-{}", i);

            // Queue state
            let progress = AgentProgress {
                agent_id: agent_id.clone(),
                item_id: format!("item-{}", i),
                state: AgentState::Queued,
                current_step: "Waiting".to_string(),
                steps_completed: 0,
                total_steps: 4,
                progress_percentage: 0.0,
                started_at: Utc::now(),
                last_update: Utc::now(),
                estimated_completion: None,
                error_count: 0,
                retry_count: 0,
            };
            tracker
                .update_agent_progress(&agent_id, progress)
                .await
                .unwrap();

            // Initialize
            tracker
                .update_agent_state(&agent_id, AgentState::Initializing)
                .await
                .unwrap();

            // Running through steps
            for step in 1..=4 {
                let progress = AgentProgress {
                    agent_id: agent_id.clone(),
                    item_id: format!("item-{}", i),
                    state: AgentState::Running {
                        step: format!("Step {}", step),
                        progress: (step as f32) * 25.0,
                    },
                    current_step: format!("Step {} of 4", step),
                    steps_completed: step,
                    total_steps: 4,
                    progress_percentage: (step as f32) * 25.0,
                    started_at: Utc::now(),
                    last_update: Utc::now(),
                    estimated_completion: Some(Utc::now() + chrono::Duration::seconds(60)),
                    error_count: 0,
                    retry_count: 0,
                };
                tracker
                    .update_agent_progress(&agent_id, progress)
                    .await
                    .unwrap();
            }

            // Complete or fail based on index
            if i % 5 == 0 && i > 0 {
                tracker
                    .mark_item_failed(&agent_id, format!("Error in item {}", i))
                    .await
                    .unwrap();
            } else {
                tracker.mark_item_completed(&agent_id).await.unwrap();
            }
        }

        // Verify final state
        let metrics = tracker.metrics.read().await;
        assert_eq!(metrics.completed_items, 9);
        assert_eq!(metrics.failed_items, 1);
        assert_eq!(metrics.pending_items, 10);

        let overall_progress = tracker.get_overall_progress().await;
        assert_eq!(overall_progress, 50.0); // 10 out of 20 items processed

        // Test snapshot
        let snapshot = tracker.create_snapshot().await;
        assert_eq!(snapshot.job_id, "integration-test");
        assert_eq!(snapshot.agent_states.len(), 10);

        // Test export
        let json_export = tracker.export_progress(ExportFormat::Json).await.unwrap();
        assert!(!json_export.is_empty());

        let csv_export = tracker.export_progress(ExportFormat::Csv).await.unwrap();
        assert!(!csv_export.is_empty());

        let html_export = tracker.export_progress(ExportFormat::Html).await.unwrap();
        assert!(!html_export.is_empty());
    }

    #[tokio::test]
    async fn test_concurrent_agent_updates() {
        let tracker = Arc::new(EnhancedProgressTracker::new(
            "concurrent-test".to_string(),
            100,
        ));

        // Spawn multiple tasks to update agents concurrently
        let mut handles = vec![];

        for i in 0..20 {
            let tracker_clone = tracker.clone();
            let handle = tokio::spawn(async move {
                let agent_id = format!("agent-{}", i);

                for step in 1..=5 {
                    let progress = AgentProgress {
                        agent_id: agent_id.clone(),
                        item_id: format!("item-{}", i),
                        state: AgentState::Running {
                            step: format!("Step {}", step),
                            progress: (step as f32) * 20.0,
                        },
                        current_step: format!("Processing step {}", step),
                        steps_completed: step,
                        total_steps: 5,
                        progress_percentage: (step as f32) * 20.0,
                        started_at: Utc::now(),
                        last_update: Utc::now(),
                        estimated_completion: None,
                        error_count: 0,
                        retry_count: 0,
                    };

                    tracker_clone
                        .update_agent_progress(&agent_id, progress)
                        .await
                        .unwrap();
                    sleep(Duration::from_millis(10)).await;
                }

                tracker_clone.mark_item_completed(&agent_id).await.unwrap();
            });

            handles.push(handle);
        }

        // Wait for all tasks to complete
        for handle in handles {
            handle.await.unwrap();
        }

        // Verify all updates were processed
        let agents = tracker.agents.read().await;
        assert_eq!(agents.len(), 20);

        let metrics = tracker.metrics.read().await;
        assert_eq!(metrics.completed_items, 20);
        assert_eq!(metrics.pending_items, 80);
    }
}