rslph 0.1.1

CLI tool for LLM-powered autonomous task execution
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
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
//! Main build command handler.
//!
//! Orchestrates the build loop with state machine, iteration execution,
//! and termination handling.

use std::path::PathBuf;
use std::sync::Arc;
use tokio_util::sync::CancellationToken;

use crate::config::Config;
use crate::error::RslphError;
use crate::progress::ProgressFile;
use crate::prompts::PromptMode;

use super::iteration::run_single_iteration;
use super::state::{BuildContext, BuildState, DoneReason, IterationResult};
use super::tokens::TokenUsage;

/// Callback type for reporting build iteration progress.
/// Parameters: (current_iteration, max_iterations)
pub type ProgressCallback = Arc<dyn Fn(u32, u32) + Send + Sync>;

/// Run the build command.
///
/// Executes the build loop on a progress file, spawning fresh Claude
/// subprocesses for each iteration until completion or max iterations.
///
/// # Arguments
///
/// * `progress_path` - Path to the progress.md file
/// * `once` - If true, run only one iteration
/// * `dry_run` - If true, preview what would be done without executing
/// * `no_tui` - If true, disable TUI and use headless output
/// * `mode` - The prompt mode to use for this build
/// * `config` - Application configuration
/// * `cancel_token` - Token for graceful cancellation
/// * `progress_callback` - Optional callback for iteration progress updates
///
/// # Returns
///
/// * `Ok(TokenUsage)` - Build completed with token usage
/// * `Err(e)` - Build failed with error
#[allow(clippy::too_many_arguments)]
pub async fn run_build_command(
    progress_path: PathBuf,
    once: bool,
    dry_run: bool,
    no_tui: bool,
    mode: PromptMode,
    config: &Config,
    cancel_token: CancellationToken,
    progress_callback: Option<ProgressCallback>,
) -> color_eyre::Result<TokenUsage> {
    // Load initial progress file
    let progress = ProgressFile::load(&progress_path)?;

    // Determine if TUI should be used
    let use_tui = config.tui_enabled && !no_tui && !dry_run;

    if !use_tui {
        println!("Build started: {}", progress_path.display());
        println!(
            "Tasks: {}/{} complete",
            progress.completed_tasks(),
            progress.total_tasks()
        );
    }

    // Create build context
    let mut ctx = BuildContext::new(
        progress_path.clone(),
        progress,
        config.clone(),
        mode,
        cancel_token.clone(),
        once,
        dry_run,
    );

    // Dry-run mode: preview and exit
    if dry_run {
        return run_dry_run(&ctx);
    }

    // TUI mode: run with interactive terminal UI
    // Note: Full subprocess integration requires refactoring iteration.rs to use channels.
    // For now, TUI runs with initial state and headless build runs in parallel.
    if use_tui {
        return run_build_with_tui(
            progress_path,
            ctx.progress.clone(),
            mode,
            config,
            cancel_token,
        )
        .await;
    }

    // Main iteration loop with state machine
    let mut state = BuildState::Starting;

    loop {
        state = match state {
            BuildState::Starting => {
                ctx.current_iteration = 1;
                ctx.iteration_start = Some(std::time::Instant::now());
                ctx.log("\n--- Iteration 1 ---");
                // Invoke progress callback at iteration start
                if let Some(ref cb) = progress_callback {
                    cb(1, ctx.max_iterations);
                }
                BuildState::Running { iteration: 1 }
            }

            BuildState::Running { iteration } => {
                match run_single_iteration(&mut ctx).await {
                    Ok(IterationResult::Continue { tasks_completed }) => {
                        // Reset timeout retry count on success
                        ctx.timeout_retry_count = 0;
                        BuildState::IterationComplete {
                            iteration,
                            tasks_completed,
                        }
                    }
                    Ok(IterationResult::Done(reason)) => BuildState::Done { reason },
                    Ok(IterationResult::Timeout) => {
                        // Handle timeout with retry
                        ctx.timeout_retry_count += 1;
                        if ctx.timeout_retry_count >= ctx.config.timeout_retries {
                            ctx.log(&format!(
                                "[BUILD] Iteration {} timed out {} times, failing",
                                iteration, ctx.timeout_retry_count
                            ));
                            BuildState::Failed {
                                error: format!(
                                    "Iteration timed out {} times (max retries: {})",
                                    ctx.timeout_retry_count, ctx.config.timeout_retries
                                ),
                            }
                        } else {
                            ctx.log(&format!(
                                "[BUILD] Iteration {} timed out, retry {}/{}",
                                iteration, ctx.timeout_retry_count, ctx.config.timeout_retries
                            ));
                            // Reset iteration start time for retry
                            ctx.iteration_start = Some(std::time::Instant::now());
                            BuildState::Running { iteration }
                        }
                    }
                    Err(RslphError::Cancelled) => BuildState::Done {
                        reason: DoneReason::UserCancelled,
                    },
                    Err(e) => BuildState::Failed {
                        error: e.to_string(),
                    },
                }
            }

            BuildState::IterationComplete {
                iteration,
                tasks_completed,
            } => {
                // Log iteration result
                let duration = ctx.iteration_start.map(|s| s.elapsed()).unwrap_or_default();
                ctx.log(&format!(
                    "[BUILD] Iteration {} complete: {} task(s) completed in {:.1}s",
                    iteration,
                    tasks_completed,
                    duration.as_secs_f64()
                ));
                ctx.log(&format!(
                    "[BUILD] Progress: {}/{} tasks",
                    ctx.progress.completed_tasks(),
                    ctx.progress.total_tasks()
                ));

                // Log to progress file
                log_iteration(&mut ctx, iteration, tasks_completed)?;

                // Check termination conditions in priority order
                if ctx.once_mode {
                    BuildState::Done {
                        reason: DoneReason::SingleIterationComplete,
                    }
                } else if iteration >= ctx.max_iterations {
                    ctx.log(&format!(
                        "[BUILD] Max iterations ({}) reached",
                        ctx.max_iterations
                    ));
                    BuildState::Done {
                        reason: DoneReason::MaxIterationsReached,
                    }
                } else {
                    // Check for cancellation before next iteration
                    if cancel_token.is_cancelled() {
                        BuildState::Done {
                            reason: DoneReason::UserCancelled,
                        }
                    } else {
                        ctx.current_iteration = iteration + 1;
                        ctx.iteration_start = Some(std::time::Instant::now());
                        ctx.log(&format!("\n--- Iteration {} ---", iteration + 1));
                        // Invoke progress callback at iteration start
                        if let Some(ref cb) = progress_callback {
                            cb(iteration + 1, ctx.max_iterations);
                        }
                        BuildState::Running {
                            iteration: iteration + 1,
                        }
                    }
                }
            }

            BuildState::Done { reason } => {
                print_completion_message(&reason, &ctx);
                return Ok(ctx.total_tokens.clone());
            }

            BuildState::Failed { error } => {
                return Err(color_eyre::eyre::eyre!("Build failed: {}", error));
            }
        };

        // Check for cancellation between state transitions
        if cancel_token.is_cancelled() && !matches!(state, BuildState::Done { .. }) {
            state = BuildState::Done {
                reason: DoneReason::UserCancelled,
            };
        }
    }
}

/// Preview what the build would do without executing (LOOP-07).
///
/// Shows comprehensive information about:
/// - Progress file status and task counts
/// - Next task that would be executed
/// - Configuration settings (max iterations, once mode)
/// - Build prompt source and validation
/// - Recent attempts summary
fn run_dry_run(ctx: &BuildContext) -> color_eyre::Result<TokenUsage> {
    use crate::prompts::get_build_prompt;

    println!("\n=== DRY RUN MODE ===\n");

    // Progress file info
    println!("Progress file: {}", ctx.progress_path.display());
    println!("Project: {}", ctx.progress.name);
    println!();

    // Current status
    println!("Status: {}", ctx.progress.status);
    if ctx.progress.is_done() {
        println!("  -> RALPH_DONE detected, build would exit immediately");
    }
    println!();

    // Task summary
    let total = ctx.progress.total_tasks();
    let completed = ctx.progress.completed_tasks();
    let remaining = total - completed;
    println!(
        "Tasks: {}/{} complete ({} remaining)",
        completed, total, remaining
    );

    if remaining == 0 && total > 0 {
        println!("  -> All tasks complete, build would exit immediately");
    }
    println!();

    // Next task to execute
    if let Some((phase, task)) = ctx.progress.next_task() {
        println!("Next task to execute:");
        println!("  Phase: {}", phase);
        println!("  Task:  {}", task.description);
    } else {
        println!("No pending tasks found.");
    }
    println!();

    // Configuration
    println!("Configuration:");
    println!("  Max iterations: {}", ctx.max_iterations);
    println!("  Once mode: {}", ctx.once_mode);
    println!("  Recent attempts depth: {}", ctx.config.recent_threads);
    println!();

    // Prompt info
    let prompt_source = if let Some(ref path) = ctx.config.build_prompt {
        format!("custom ({})", path.display())
    } else {
        "default (embedded)".to_string()
    };
    println!("Build prompt: {}", prompt_source);

    // Validate prompt is loadable
    match get_build_prompt(&ctx.config) {
        Ok(prompt) => println!("  Prompt length: {} chars", prompt.len()),
        Err(e) => println!("  WARNING: Failed to load prompt: {}", e),
    }
    println!();

    // Recent attempts summary
    if !ctx.progress.recent_attempts.is_empty() {
        println!("Recent attempts ({}):", ctx.progress.recent_attempts.len());
        for attempt in ctx.progress.recent_attempts.iter().rev().take(3) {
            println!(
                "  Iteration {}: {} -> {}",
                attempt.iteration, attempt.tried, attempt.result
            );
        }
    }

    println!("\n=== END DRY RUN ===");
    println!("\nTo execute, run without --dry-run flag.");

    Ok(TokenUsage::default())
}

/// Run build with TUI mode enabled.
///
/// Initializes the TUI and runs the build loop concurrently with visual feedback.
/// The build loop runs in the background and sends events to the TUI via channels.
async fn run_build_with_tui(
    progress_path: PathBuf,
    progress: ProgressFile,
    mode: PromptMode,
    config: &Config,
    cancel_token: CancellationToken,
) -> color_eyre::Result<TokenUsage> {
    use crate::tui::{run_tui, App, SubprocessEvent};

    // Initialize app state from progress
    let mut app = App::new(config.max_iterations, "Claude", progress.name.clone());
    app.current_task = progress.completed_tasks() as u32;
    app.total_tasks = progress.total_tasks() as u32;
    app.log_path = Some(progress_path.clone());
    app.current_iteration = 0;
    app.viewing_iteration = 0;

    // Get recent message count from config
    let recent_count = config.tui_recent_messages;

    // Start TUI and get subprocess event sender
    // Pass a clone of cancel_token so TUI can cancel the build on quit
    let subprocess_tx = run_tui(app, recent_count, cancel_token.clone()).await?;

    // Create build context with TUI sender for log routing
    let mut ctx = BuildContext::with_tui(
        progress_path.clone(),
        progress,
        config.clone(),
        mode,
        cancel_token.clone(),
        false, // once_mode - TUI always runs full loop
        false, // dry_run - already handled before this function
        Some(subprocess_tx.clone()),
    );

    // Create a channel for build loop to send updates to TUI
    // The subprocess_tx is an UnboundedSender<SubprocessEvent>
    let tui_tx = subprocess_tx.clone();

    // Run build loop, forwarding events to TUI
    let mut state = BuildState::Starting;
    let result = loop {
        state = match state {
            BuildState::Starting => {
                ctx.current_iteration = 1;
                ctx.iteration_start = Some(std::time::Instant::now());

                // Send iteration start to TUI to sync iteration number
                let _ = tui_tx.send(SubprocessEvent::IterationStart { iteration: 1 });
                let _ = tui_tx.send(SubprocessEvent::Log("--- Iteration 1 ---".to_string()));

                BuildState::Running { iteration: 1 }
            }

            BuildState::Running { iteration } => {
                match run_single_iteration(&mut ctx).await {
                    Ok(IterationResult::Continue { tasks_completed }) => {
                        // Reset timeout retry count on success
                        ctx.timeout_retry_count = 0;
                        BuildState::IterationComplete {
                            iteration,
                            tasks_completed,
                        }
                    }
                    Ok(IterationResult::Done(reason)) => BuildState::Done { reason },
                    Ok(IterationResult::Timeout) => {
                        // Handle timeout with retry
                        ctx.timeout_retry_count += 1;
                        if ctx.timeout_retry_count >= ctx.config.timeout_retries {
                            let _ = tui_tx.send(SubprocessEvent::Log(format!(
                                "Iteration {} timed out {} times, failing",
                                iteration, ctx.timeout_retry_count
                            )));
                            BuildState::Failed {
                                error: format!(
                                    "Iteration timed out {} times (max retries: {})",
                                    ctx.timeout_retry_count, ctx.config.timeout_retries
                                ),
                            }
                        } else {
                            let _ = tui_tx.send(SubprocessEvent::Log(format!(
                                "Iteration {} timed out, retry {}/{}",
                                iteration, ctx.timeout_retry_count, ctx.config.timeout_retries
                            )));
                            // Reset iteration start time for retry
                            ctx.iteration_start = Some(std::time::Instant::now());
                            BuildState::Running { iteration }
                        }
                    }
                    Err(RslphError::Cancelled) => BuildState::Done {
                        reason: DoneReason::UserCancelled,
                    },
                    Err(e) => BuildState::Failed {
                        error: e.to_string(),
                    },
                }
            }

            BuildState::IterationComplete {
                iteration,
                tasks_completed,
            } => {
                // Log iteration result
                let duration = ctx.iteration_start.map(|s| s.elapsed()).unwrap_or_default();

                // Send iteration complete to TUI
                let _ = tui_tx.send(SubprocessEvent::IterationDone {
                    tasks_done: tasks_completed,
                });

                let _ = tui_tx.send(SubprocessEvent::Log(format!(
                    "Iteration {} complete: {} task(s) in {:.1}s",
                    iteration,
                    tasks_completed,
                    duration.as_secs_f64()
                )));

                // Log to progress file
                log_iteration(&mut ctx, iteration, tasks_completed)?;

                // Check termination conditions
                if iteration >= ctx.max_iterations {
                    let _ = tui_tx.send(SubprocessEvent::Log(format!(
                        "Max iterations ({}) reached",
                        ctx.max_iterations
                    )));
                    BuildState::Done {
                        reason: DoneReason::MaxIterationsReached,
                    }
                } else if cancel_token.is_cancelled() {
                    BuildState::Done {
                        reason: DoneReason::UserCancelled,
                    }
                } else {
                    ctx.current_iteration = iteration + 1;
                    ctx.iteration_start = Some(std::time::Instant::now());

                    let _ = tui_tx.send(SubprocessEvent::IterationStart {
                        iteration: iteration + 1,
                    });
                    let _ = tui_tx.send(SubprocessEvent::Log(format!(
                        "--- Iteration {} ---",
                        iteration + 1
                    )));

                    BuildState::Running {
                        iteration: iteration + 1,
                    }
                }
            }

            BuildState::Done { reason } => {
                let _ = tui_tx.send(SubprocessEvent::Log(format!("Build complete: {}", reason)));
                break Ok(ctx.total_tokens.clone());
            }

            BuildState::Failed { error } => {
                let _ = tui_tx.send(SubprocessEvent::Log(format!("Build failed: {}", error)));
                break Err(color_eyre::eyre::eyre!("Build failed: {}", error));
            }
        };

        // Check for cancellation between state transitions
        if cancel_token.is_cancelled() && !matches!(state, BuildState::Done { .. }) {
            state = BuildState::Done {
                reason: DoneReason::UserCancelled,
            };
        }

        // Small yield to let TUI render
        tokio::task::yield_now().await;
    };

    result
}

/// Print completion message based on done reason.
fn print_completion_message(reason: &DoneReason, ctx: &BuildContext) {
    println!("\n=== BUILD COMPLETE ===");
    println!("Reason: {}", reason);
    println!(
        "Final progress: {}/{} tasks",
        ctx.progress.completed_tasks(),
        ctx.progress.total_tasks()
    );

    match reason {
        DoneReason::AllTasksComplete | DoneReason::RalphDoneMarker => {
            println!("All tasks completed successfully!");
        }
        DoneReason::MaxIterationsReached => {
            let remaining = ctx.progress.total_tasks() - ctx.progress.completed_tasks();
            println!(
                "Stopped after {} iterations. {} task(s) remaining.",
                ctx.max_iterations, remaining
            );
        }
        DoneReason::UserCancelled => {
            println!("Build cancelled by user.");
        }
        DoneReason::SingleIterationComplete => {
            println!("Single iteration completed (--once mode).");
        }
    }
}

/// Log iteration to progress file.
fn log_iteration(
    ctx: &mut BuildContext,
    iteration: u32,
    tasks_completed: u32,
) -> Result<(), RslphError> {
    let now = chrono::Utc::now();
    let started = now.format("%Y-%m-%d %H:%M").to_string();

    let duration = ctx
        .iteration_start
        .map(|s| {
            let elapsed = s.elapsed();
            format!("{}m {}s", elapsed.as_secs() / 60, elapsed.as_secs() % 60)
        })
        .unwrap_or_else(|| "~".to_string());

    let notes = if tasks_completed == 0 {
        "No tasks completed".to_string()
    } else {
        format!("{} task(s) completed", tasks_completed)
    };

    ctx.progress
        .log_iteration(iteration, &started, &duration, tasks_completed, &notes);

    ctx.progress.write(&ctx.progress_path)?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::prompts::PromptMode;
    use std::time::Duration;
    use tempfile::TempDir;

    fn create_test_progress_file(dir: &TempDir) -> PathBuf {
        use crate::progress::{Task, TaskPhase};

        let progress = ProgressFile {
            name: "Test Plan".to_string(),
            status: "In Progress".to_string(),
            analysis: "Test analysis".to_string(),
            tasks: vec![TaskPhase {
                name: "Phase 1".to_string(),
                tasks: vec![Task {
                    description: "Task 1".to_string(),
                    completed: false,
                }],
            }],
            testing_strategy: "Unit tests".to_string(),
            completed_this_iteration: vec![],
            recent_attempts: vec![],
            iteration_log: vec![],
        };

        let path = dir.path().join("progress.md");
        progress.write(&path).expect("write progress");
        path
    }

    #[tokio::test]
    async fn test_build_command_with_echo_mock() {
        // This test uses echo as a mock for Claude.
        // Echo outputs garbage but ProgressFile::parse is lenient.
        let dir = TempDir::new().expect("temp dir");
        let progress_path = create_test_progress_file(&dir);

        let config = Config {
            claude_path: "/bin/echo".to_string(),
            ..Default::default()
        };

        let token = CancellationToken::new();

        // Run with --once to avoid infinite loop
        let result = run_build_command(
            progress_path,
            true, // once
            false,
            true, // no_tui
            PromptMode::Basic,
            &config,
            token,
            None,
        )
        .await;

        // Echo outputs garbage, but we complete one iteration
        assert!(result.is_ok(), "Should complete: {:?}", result);
    }

    #[tokio::test]
    async fn test_build_command_dry_run() {
        let dir = TempDir::new().expect("temp dir");
        let progress_path = create_test_progress_file(&dir);

        let config = Config::default();
        let token = CancellationToken::new();

        let result = run_build_command(
            progress_path,
            false,
            true, // dry_run
            true, // no_tui
            PromptMode::Basic,
            &config,
            token,
            None,
        )
        .await;

        assert!(result.is_ok(), "Dry run should succeed");
    }

    #[tokio::test]
    async fn test_build_command_timeout() {
        let dir = TempDir::new().expect("temp dir");
        let progress_path = create_test_progress_file(&dir);

        // Create a script that sleeps longer than timeout
        let script = "#!/bin/sh\nsleep 60\n";
        let script_path = dir.path().join("slow_script.sh");
        std::fs::write(&script_path, script).expect("write script");

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755))
                .expect("set permissions");
        }

        let config = Config {
            claude_path: script_path.to_string_lossy().to_string(),
            max_iterations: 1, // Limit iterations
            ..Default::default()
        };

        let token = CancellationToken::new();

        // The iteration will timeout (default 10 min is too long for test)
        // So we use cancellation to stop early
        let token_clone = token.clone();
        tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(100)).await;
            token_clone.cancel();
        });

        let result = run_build_command(
            progress_path,
            true, // once mode to limit iterations
            false,
            true, // no_tui
            PromptMode::Basic,
            &config,
            token,
            None,
        )
        .await;

        // Should complete (possibly with cancellation)
        // The key is it doesn't hang
        assert!(result.is_ok(), "Should handle timeout/cancel: {:?}", result);
    }

    #[tokio::test]
    async fn test_build_command_cancellation() {
        let dir = TempDir::new().expect("temp dir");
        let progress_path = create_test_progress_file(&dir);

        // Create a script that sleeps
        let script = "#!/bin/sh\nsleep 60\n";
        let script_path = dir.path().join("slow_script.sh");
        std::fs::write(&script_path, script).expect("write script");

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755))
                .expect("set permissions");
        }

        let config = Config {
            claude_path: script_path.to_string_lossy().to_string(),
            ..Default::default()
        };

        let token = CancellationToken::new();
        let token_clone = token.clone();

        // Cancel after 50ms
        tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(50)).await;
            token_clone.cancel();
        });

        let result = run_build_command(
            progress_path,
            false,
            false,
            true,
            PromptMode::Basic,
            &config,
            token,
            None,
        )
        .await;

        // Should complete with user cancelled status
        assert!(result.is_ok(), "Should handle cancellation: {:?}", result);
    }

    #[tokio::test]
    async fn test_build_command_nonexistent_progress() {
        let config = Config::default();
        let token = CancellationToken::new();

        let result = run_build_command(
            PathBuf::from("/nonexistent/progress.md"),
            false,
            false,
            true, // no_tui
            PromptMode::Basic,
            &config,
            token,
            None,
        )
        .await;

        assert!(result.is_err(), "Should fail on missing file");
    }

    #[tokio::test]
    async fn test_dry_run_does_not_modify_progress() {
        use crate::progress::{Task, TaskPhase};

        let dir = TempDir::new().expect("temp dir");
        let progress_path = dir.path().join("progress.md");

        let progress = ProgressFile {
            name: "Test".to_string(),
            status: "In Progress".to_string(),
            tasks: vec![TaskPhase {
                name: "Phase 1".to_string(),
                tasks: vec![
                    Task {
                        description: "Task 1".to_string(),
                        completed: false,
                    },
                    Task {
                        description: "Task 2".to_string(),
                        completed: false,
                    },
                ],
            }],
            ..Default::default()
        };
        progress.write(&progress_path).expect("write");

        // Read original content
        let original_content = std::fs::read_to_string(&progress_path).expect("read original");

        let config = Config::default();
        let token = CancellationToken::new();

        // Run dry-run
        let result = run_build_command(
            progress_path.clone(),
            false,
            true, // dry_run
            true, // no_tui
            PromptMode::Basic,
            &config,
            token,
            None,
        )
        .await;

        assert!(result.is_ok(), "Dry run should succeed");

        // Verify file unchanged
        let final_content = std::fs::read_to_string(&progress_path).expect("read final");
        assert_eq!(
            original_content, final_content,
            "Progress file should not be modified in dry-run mode"
        );
    }

    #[tokio::test]
    async fn test_dry_run_shows_once_mode_true() {
        use crate::progress::{Task, TaskPhase};

        let dir = TempDir::new().expect("temp dir");
        let progress_path = dir.path().join("progress.md");

        let progress = ProgressFile {
            name: "Test".to_string(),
            status: "In Progress".to_string(),
            tasks: vec![TaskPhase {
                name: "Phase 1".to_string(),
                tasks: vec![Task {
                    description: "Task 1".to_string(),
                    completed: false,
                }],
            }],
            ..Default::default()
        };
        progress.write(&progress_path).expect("write");

        let config = Config::default();
        let token = CancellationToken::new();

        // When both once and dry_run are true, dry_run takes precedence
        let result = run_build_command(
            progress_path,
            true, // once mode
            true, // dry_run
            true, // no_tui
            PromptMode::Basic,
            &config,
            token,
            None,
        )
        .await;

        assert!(result.is_ok(), "Dry run with once mode should succeed");
    }

    #[test]
    fn test_dry_run_function_directly() {
        use crate::progress::{Attempt, Task, TaskPhase};

        let dir = TempDir::new().expect("temp dir");
        let progress_path = dir.path().join("progress.md");

        let progress = ProgressFile {
            name: "Test Plan".to_string(),
            status: "In Progress".to_string(),
            tasks: vec![TaskPhase {
                name: "Phase 1".to_string(),
                tasks: vec![
                    Task {
                        description: "Completed task".to_string(),
                        completed: true,
                    },
                    Task {
                        description: "Pending task".to_string(),
                        completed: false,
                    },
                ],
            }],
            recent_attempts: vec![Attempt {
                iteration: 1,
                tried: "First try".to_string(),
                result: "Success".to_string(),
                next: None,
            }],
            ..Default::default()
        };

        let config = Config::default();
        let token = CancellationToken::new();

        let ctx = BuildContext::new(
            progress_path,
            progress,
            config,
            PromptMode::Basic,
            token,
            true, // once_mode
            true, // dry_run
        );

        // Verify dry run function succeeds
        let result = run_dry_run(&ctx);
        assert!(result.is_ok(), "Dry run function should succeed");
    }

    #[tokio::test]
    async fn test_once_mode_stops_after_one_iteration() {
        use crate::progress::{Task, TaskPhase};

        let dir = TempDir::new().expect("temp dir");

        // Create progress file with multiple incomplete tasks
        let progress = ProgressFile {
            name: "Test".to_string(),
            status: "In Progress".to_string(),
            analysis: "Test analysis.".to_string(),
            tasks: vec![TaskPhase {
                name: "Phase 1".to_string(),
                tasks: vec![
                    Task {
                        description: "Task 1".to_string(),
                        completed: false,
                    },
                    Task {
                        description: "Task 2".to_string(),
                        completed: false,
                    },
                    Task {
                        description: "Task 3".to_string(),
                        completed: false,
                    },
                ],
            }],
            testing_strategy: "Test with cargo test.".to_string(),
            ..Default::default()
        };

        let progress_path = dir.path().join("progress.md");
        progress.write(&progress_path).expect("write progress");

        // Use echo mock that outputs the progress unchanged
        let config = Config {
            claude_path: "/bin/echo".to_string(),
            ..Default::default()
        };

        let token = CancellationToken::new();

        // Run with once=true
        let result = run_build_command(
            progress_path.clone(),
            true,  // once mode
            false, // not dry-run
            true,  // no_tui
            PromptMode::Basic,
            &config,
            token,
            None,
        )
        .await;

        assert!(result.is_ok(), "Once mode should complete successfully");

        // The key assertion is that the command completes successfully (doesn't loop forever).
        // Echo corrupts the file, but once mode ensures we exit after one iteration.
    }

    #[test]
    fn test_once_mode_triggers_correct_done_reason() {
        // This tests the state machine logic directly
        use crate::progress::{Task, TaskPhase};

        let progress = ProgressFile {
            name: "Test".to_string(),
            status: "In Progress".to_string(),
            tasks: vec![TaskPhase {
                name: "Phase 1".to_string(),
                tasks: vec![Task {
                    description: "Task 1".to_string(),
                    completed: false,
                }],
            }],
            ..Default::default()
        };

        let dir = TempDir::new().expect("temp dir");
        let progress_path = dir.path().join("progress.md");
        let config = Config::default();
        let token = CancellationToken::new();

        let ctx = BuildContext::new(
            progress_path,
            progress,
            config,
            PromptMode::Basic,
            token,
            true, // once_mode - this is what we're testing
            false,
        );

        // Verify once_mode is set correctly
        assert!(ctx.once_mode, "Once mode should be set");
    }

    #[tokio::test]
    async fn test_ralph_done_stops_immediately() {
        use crate::progress::{Task, TaskPhase};

        let dir = TempDir::new().expect("temp dir");
        let progress_path = dir.path().join("progress.md");

        // Create progress file with RALPH_DONE in status
        let progress = ProgressFile {
            name: "Test".to_string(),
            status: "RALPH_DONE - All tasks complete".to_string(),
            tasks: vec![TaskPhase {
                name: "Phase 1".to_string(),
                tasks: vec![Task {
                    description: "Task 1".to_string(),
                    completed: true,
                }],
            }],
            ..Default::default()
        };
        progress.write(&progress_path).expect("write");

        // Use a slow script as mock - if RALPH_DONE works, it won't be called
        let script = "#!/bin/sh\nsleep 60\n";
        let script_path = dir.path().join("slow_script.sh");
        std::fs::write(&script_path, script).expect("write script");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755))
                .expect("set permissions");
        }

        let config = Config {
            claude_path: script_path.to_string_lossy().to_string(),
            ..Default::default()
        };

        let token = CancellationToken::new();

        // If RALPH_DONE is detected, this should return immediately
        // without spawning the slow script
        let start = std::time::Instant::now();
        let result = run_build_command(
            progress_path,
            false,
            false,
            true, // no_tui
            PromptMode::Basic,
            &config,
            token,
            None,
        )
        .await;

        let elapsed = start.elapsed();

        assert!(result.is_ok(), "Should succeed with RALPH_DONE");
        assert!(
            elapsed.as_secs() < 5,
            "Should return immediately, not wait for slow script"
        );
    }

    #[tokio::test]
    async fn test_all_tasks_complete_stops_immediately() {
        use crate::progress::{Task, TaskPhase};

        let dir = TempDir::new().expect("temp dir");
        let progress_path = dir.path().join("progress.md");

        // Create progress file with all tasks marked complete
        let progress = ProgressFile {
            name: "Test".to_string(),
            status: "In Progress".to_string(),
            tasks: vec![TaskPhase {
                name: "Phase 1".to_string(),
                tasks: vec![
                    Task {
                        description: "Task 1".to_string(),
                        completed: true,
                    },
                    Task {
                        description: "Task 2".to_string(),
                        completed: true,
                    },
                ],
            }],
            ..Default::default()
        };
        progress.write(&progress_path).expect("write");

        // Use a slow script as mock
        let script = "#!/bin/sh\nsleep 60\n";
        let script_path = dir.path().join("slow_script.sh");
        std::fs::write(&script_path, script).expect("write script");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755))
                .expect("set permissions");
        }

        let config = Config {
            claude_path: script_path.to_string_lossy().to_string(),
            ..Default::default()
        };

        let token = CancellationToken::new();

        let start = std::time::Instant::now();
        let result = run_build_command(
            progress_path,
            false,
            false,
            true, // no_tui
            PromptMode::Basic,
            &config,
            token,
            None,
        )
        .await;

        let elapsed = start.elapsed();

        assert!(result.is_ok(), "Should succeed when all tasks complete");
        assert!(
            elapsed.as_secs() < 5,
            "Should return immediately when all tasks complete"
        );
    }

    #[tokio::test]
    async fn test_max_iterations_enforced() {
        use crate::progress::{Task, TaskPhase};

        let dir = TempDir::new().expect("temp dir");
        let progress_path = dir.path().join("progress.md");

        // Create progress file with incomplete tasks
        let progress = ProgressFile {
            name: "Test".to_string(),
            status: "In Progress".to_string(),
            analysis: "Test analysis.".to_string(),
            tasks: vec![TaskPhase {
                name: "Phase 1".to_string(),
                tasks: vec![
                    Task {
                        description: "Task 1".to_string(),
                        completed: false,
                    },
                    Task {
                        description: "Task 2".to_string(),
                        completed: false,
                    },
                ],
            }],
            testing_strategy: "Test with cargo test.".to_string(),
            ..Default::default()
        };
        progress.write(&progress_path).expect("write");

        // Use echo mock - outputs garbage but loop will run max_iterations times
        let config = Config {
            claude_path: "/bin/echo".to_string(),
            max_iterations: 2, // Only run 2 iterations
            ..Default::default()
        };

        let token = CancellationToken::new();

        let result = run_build_command(
            progress_path.clone(),
            false,
            false,
            true, // no_tui
            PromptMode::Basic,
            &config,
            token,
            None,
        )
        .await;

        assert!(result.is_ok(), "Should complete after max iterations");

        // The iteration log is stored in the progress file.
        // Echo mock outputs empty content, so each iteration overwrites the file.
        // The last iteration's log_iteration call adds an entry.
        // With max_iterations=2, we expect at least the last iteration to be logged.
        let updated = ProgressFile::load(&progress_path).expect("read back");
        assert!(
            !updated.iteration_log.is_empty(),
            "Should have at least 1 iteration logged: {:?}",
            updated.iteration_log
        );
        // The key assertion is that we ran exactly 2 iterations (test completed)
    }

    #[tokio::test]
    async fn test_resume_from_partial_progress() {
        use crate::progress::{Attempt, IterationEntry, Task, TaskPhase};

        let dir = TempDir::new().expect("temp dir");

        // Create progress file simulating prior interruption
        // 2 tasks complete, 2 remaining, iteration log shows 2 prior runs
        let progress = ProgressFile {
            name: "Resume Test".to_string(),
            status: "In Progress".to_string(),
            analysis: "Testing resume capability.".to_string(),
            tasks: vec![TaskPhase {
                name: "Phase 1".to_string(),
                tasks: vec![
                    Task {
                        description: "Task 1 - already done".to_string(),
                        completed: true,
                    },
                    Task {
                        description: "Task 2 - already done".to_string(),
                        completed: true,
                    },
                    Task {
                        description: "Task 3 - next to execute".to_string(),
                        completed: false,
                    },
                    Task {
                        description: "Task 4 - waiting".to_string(),
                        completed: false,
                    },
                ],
            }],
            testing_strategy: "Test with cargo test.".to_string(),
            completed_this_iteration: vec![],
            recent_attempts: vec![
                Attempt {
                    iteration: 1,
                    tried: "Task 1".to_string(),
                    result: "Completed".to_string(),
                    next: Some("Continue".to_string()),
                },
                Attempt {
                    iteration: 2,
                    tried: "Task 2".to_string(),
                    result: "Completed".to_string(),
                    next: Some("Continue".to_string()),
                },
            ],
            iteration_log: vec![
                IterationEntry {
                    iteration: 1,
                    started: "2024-01-01 10:00".to_string(),
                    duration: "2m 30s".to_string(),
                    tasks_completed: 1,
                    notes: "Task 1".to_string(),
                },
                IterationEntry {
                    iteration: 2,
                    started: "2024-01-01 10:03".to_string(),
                    duration: "3m 15s".to_string(),
                    tasks_completed: 1,
                    notes: "Task 2".to_string(),
                },
            ],
        };

        let progress_path = dir.path().join("progress.md");
        progress.write(&progress_path).expect("write progress");

        // Run build with once mode using echo mock
        let config = Config {
            claude_path: "/bin/echo".to_string(),
            max_iterations: 1, // Will run 1 iteration
            ..Default::default()
        };

        let token = CancellationToken::new();

        // The key test for LOOP-02 (resume) is that the build:
        // 1. Starts correctly with 2/4 tasks already complete
        // 2. Doesn't fail or panic when resuming
        // 3. Runs an iteration (even if echo corrupts the file)

        let result = run_build_command(
            progress_path.clone(),
            true, // once mode to limit execution
            false,
            true, // no_tui
            PromptMode::Basic,
            &config,
            token,
            None,
        )
        .await;

        assert!(result.is_ok(), "Resume should succeed: {:?}", result);

        // Verify the build ran by checking that an iteration was logged.
        // Note: echo mock outputs empty content, so it overwrites prior iteration log.
        // The new iteration gets logged after the overwrite.
        let updated = ProgressFile::load(&progress_path).expect("read back");
        assert!(
            !updated.iteration_log.is_empty(),
            "Should have iteration logged after resume: {:?}",
            updated.iteration_log
        );
    }
}