cflx 0.6.82

Conflux – a spec-driven parallel coding orchestrator that runs AI agents on git worktrees
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
//! Shared archive operations for CLI and TUI modes.
//!
//! Provides a unified archive implementation that both modes can use,
//! eliminating code duplication and ensuring consistent behavior.
//!
//! Note: These functions are infrastructure for future CLI/TUI integration.
//! They will be used as the refactoring continues.

#![allow(dead_code)]

use crate::agent::AgentRunner;
use crate::ai_command_runner::AiCommandRunner;
use crate::config::StallDetectionConfig;
use crate::error::{OrchestratorError, Result};
use crate::execution::archive::ArchiveVerificationResult;
use crate::history::OutputCollector;
use crate::hooks::{HookContext, HookRunner, HookType};
use crate::openspec::Change;
use crate::vcs::git::commands as git_commands;
use std::path::Path;
use tracing::info;

use super::output::OutputHandler;

/// Result of an archive operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ArchiveResult {
    /// Archive completed successfully.
    Success,
    /// Archive stalled due to repeated empty WIP commits.
    Stalled { error: String },
    /// Archive command failed.
    Failed { error: String },
    /// Archive was cancelled (e.g., by user or timeout).
    Cancelled,
}

impl ArchiveResult {
    /// Returns true if the archive succeeded.
    pub fn is_success(&self) -> bool {
        matches!(self, ArchiveResult::Success)
    }
}

/// Context for archive operations.
#[derive(Debug, Clone)]
pub struct ArchiveContext {
    /// Number of changes already processed.
    pub changes_processed: usize,
    /// Total number of changes in the run.
    pub total_changes: usize,
    /// Remaining changes to process.
    pub remaining_changes: usize,
    /// How many times this change was applied.
    pub apply_count: u32,
}

impl ArchiveContext {
    /// Create a new ArchiveContext.
    pub fn new(
        changes_processed: usize,
        total_changes: usize,
        remaining_changes: usize,
        apply_count: u32,
    ) -> Self {
        Self {
            changes_processed,
            total_changes,
            remaining_changes,
            apply_count,
        }
    }
}

/// Archive a completed change.
///
/// This function handles:
/// - Running pre-archive hooks (on_change_complete, pre_archive)
/// - Executing the archive command
/// - Verifying the archive was successful
/// - Running post-archive hooks (post_archive)
/// - Cleaning up apply history
///
/// # Arguments
/// * `change` - The change to archive
/// * `agent` - The agent runner for executing commands
/// * `ai_runner` - The AI command runner for shared stagger state
/// * `hooks` - The hook runner for executing hooks
/// * `context` - Context information for hooks
/// * `output` - Output handler for logging
/// * `base_path` - Optional base path for archive verification
/// * `stall_config` - Stall detection configuration for empty WIP commits
///
/// # Returns
/// Same as `archive_change_streaming`
#[allow(clippy::too_many_arguments)] // Infrastructure function, parameters needed for refactoring
pub async fn archive_change<O>(
    change: &Change,
    agent: &mut AgentRunner,
    ai_runner: &crate::ai_command_runner::AiCommandRunner,
    hooks: &HookRunner,
    context: &ArchiveContext,
    output: &O,
    base_path: Option<&Path>,
    stall_config: &StallDetectionConfig,
) -> Result<ArchiveResult>
where
    O: OutputHandler,
{
    info!("Archiving change: {}", change.id);

    // Build hook context
    let hook_ctx = HookContext::new(
        context.changes_processed,
        context.total_changes,
        context.remaining_changes,
        false,
    )
    .with_change(&change.id, change.completed_tasks, change.total_tasks)
    .with_apply_count(context.apply_count);

    // Run pre-archive hooks
    run_pre_archive_hooks(hooks, &hook_ctx, output).await?;

    output.on_info(&format!("Archiving: {}", change.id));

    use crate::execution::archive::{
        build_archive_error_message, extract_archive_runtime_blocker, verify_archive_completion,
        ARCHIVE_COMMAND_MAX_RETRIES,
    };

    let max_attempts = ARCHIVE_COMMAND_MAX_RETRIES.saturating_add(1);
    let mut attempt: u32 = 0;
    let repo_root = base_path.unwrap_or_else(|| Path::new("."));
    let is_git_repo = match git_commands::check_git_repo(repo_root).await {
        Ok(is_repo) => is_repo,
        Err(e) => {
            output.on_warn(&format!("Failed to check Git repository status: {}", e));
            false
        }
    };
    let mut empty_commit_streak = 0u32;

    loop {
        attempt += 1;

        // Record start time for this attempt
        let start = std::time::Instant::now();

        // Execute archive command via AiCommandRunner (with shared stagger state)
        let (status, stdout_tail, stderr_tail) =
            agent.run_archive_with_runner(&change.id, ai_runner).await?;

        if !status.success() {
            let error_msg = format!("Archive command failed with exit code: {:?}", status.code());

            // Record failed attempt
            agent.record_archive_attempt(
                &change.id,
                &status,
                start,
                Some(error_msg.clone()),
                stdout_tail.clone(),
                stderr_tail.clone(),
            );

            // Run on_error hook
            let error_ctx = hook_ctx.clone().with_error(&error_msg);
            let _ = hooks.run_hook(HookType::OnError, &error_ctx).await;

            output.on_error(&error_msg);
            return Ok(ArchiveResult::Failed { error: error_msg });
        }

        // Handle WIP commit creation and stall detection
        if let Some(stall_message) = handle_archive_wip_and_stall(
            is_git_repo,
            repo_root,
            &change.id,
            attempt,
            &mut empty_commit_streak,
            stall_config,
            output,
        )
        .await?
        {
            return Ok(ArchiveResult::Stalled {
                error: stall_message,
            });
        }

        // Verify archive was successful
        let verification_status = verify_archive_completion(&change.id, base_path);
        if verification_status.is_success() {
            // Record successful attempt
            agent.record_archive_attempt(
                &change.id,
                &status,
                start,
                None,
                stdout_tail.clone(),
                stderr_tail.clone(),
            );
            break;
        }

        // Verification failed - record with reason
        let verification_reason = match verification_status {
            ArchiveVerificationResult::NotArchived { ref change_id } => {
                format!("Change still exists at openspec/changes/{}", change_id)
            }
            _ => "Archive verification failed".to_string(),
        };
        agent.record_archive_attempt(
            &change.id,
            &status,
            start,
            Some(verification_reason.clone()),
            stdout_tail.clone(),
            stderr_tail.clone(),
        );

        if attempt <= ARCHIVE_COMMAND_MAX_RETRIES {
            output.on_warn(&format!(
                "Archive verification failed for {} (attempt {}/{}): {}; retrying archive command",
                change.id, attempt, max_attempts, verification_reason
            ));
            continue;
        }

        let runtime_blocker =
            extract_archive_runtime_blocker(stdout_tail.as_deref(), stderr_tail.as_deref());
        let error_msg = build_archive_error_message(&change.id, None, runtime_blocker.as_deref());
        output.on_error(&error_msg);
        return Ok(ArchiveResult::Failed { error: error_msg });
    }

    if is_git_repo {
        if let Err(e) = git_commands::squash_archive_wip_commits(repo_root, &change.id).await {
            output.on_warn(&format!(
                "Failed to squash WIP(archive) commits for {}: {}",
                change.id, e
            ));
        }
    }

    // Clear apply and archive history
    clear_archive_history(agent, &change.id);

    // Run post_archive hook
    run_post_archive_hook(hooks, context, change, output).await?;

    info!("Successfully archived: {}", change.id);
    output.on_success(&format!("Archived: {}", change.id));

    Ok(ArchiveResult::Success)
}

/// Helper: Run pre-archive hooks and initial setup.
///
/// Runs on_change_complete and pre_archive hooks.
async fn run_pre_archive_hooks<O>(
    hooks: &HookRunner,
    hook_ctx: &HookContext,
    output: &O,
) -> Result<()>
where
    O: OutputHandler,
{
    // Run on_change_complete hook
    if let Err(e) = hooks.run_hook(HookType::OnChangeComplete, hook_ctx).await {
        output.on_warn(&format!("on_change_complete hook failed: {}", e));
        return Err(e);
    }

    // Run pre_archive hook
    if let Err(e) = hooks.run_hook(HookType::PreArchive, hook_ctx).await {
        output.on_warn(&format!("pre_archive hook failed: {}", e));
        return Err(e);
    }

    Ok(())
}

/// Helper: Execute archive command with streaming output.
///
/// Streams command output and collects it for history recording.
/// Returns the exit status and output collector.
async fn execute_archive_command_streaming<O, F>(
    agent: &mut AgentRunner,
    ai_runner: &AiCommandRunner,
    change_id: &str,
    attempt: u32,
    output: &O,
    cancel_check: F,
) -> Result<(
    std::process::ExitStatus,
    OutputCollector,
    std::time::Instant,
)>
where
    O: OutputHandler,
    F: Fn() -> bool,
{
    use crate::agent::OutputLine;

    // Execute archive command with streaming
    let (mut child, mut output_rx, start, _archive_command) = agent
        .run_archive_streaming_with_runner(change_id, ai_runner, None)
        .await?;

    // Create output collector for history
    let mut output_collector = OutputCollector::new();

    // Stream output
    loop {
        if cancel_check() {
            let _ = child.terminate();
            let _ = child.kill().await;
            output.on_warn("Process killed due to cancellation");
            return Err(OrchestratorError::AgentCommand(
                "Archive command cancelled".to_string(),
            ));
        }

        match output_rx.try_recv() {
            Ok(OutputLine::Stdout(s)) => {
                output_collector.add_stdout(&s);
                output.on_stdout(&s);
            }
            Ok(OutputLine::Stderr(s)) => {
                output_collector.add_stderr(&s);
                output.on_agent_stderr(&s);
            }
            Err(tokio::sync::mpsc::error::TryRecvError::Empty) => {
                // No data available, check if process is done
                tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
            }
            Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => break,
        }
    }

    // Wait for child process to complete
    let status = child.wait().await.map_err(|e| {
        OrchestratorError::AgentCommand(format!(
            "Failed to wait for archive command for change '{}' (attempt {}): {}",
            change_id, attempt, e
        ))
    })?;

    Ok((status, output_collector, start))
}

/// Helper: Handle WIP commit creation and stall detection.
///
/// Creates a WIP commit for the archive attempt and checks for stall conditions.
/// Returns Ok(Some(error)) if stalled, Ok(None) if continuing, Err on failure.
async fn handle_archive_wip_and_stall<O>(
    is_git_repo: bool,
    repo_root: &Path,
    change_id: &str,
    attempt: u32,
    empty_commit_streak: &mut u32,
    stall_config: &StallDetectionConfig,
    output: &O,
) -> Result<Option<String>>
where
    O: OutputHandler,
{
    if !is_git_repo {
        return Ok(None);
    }

    if let Err(e) = git_commands::create_archive_wip_commit(repo_root, change_id, attempt).await {
        output.on_warn(&format!(
            "Failed to create WIP(archive) commit for {} (attempt {}): {}",
            change_id, attempt, e
        ));
        return Ok(None);
    }

    if !stall_config.enabled {
        return Ok(None);
    }

    match git_commands::is_head_empty_commit(repo_root).await {
        Ok(is_empty) => {
            if is_empty {
                *empty_commit_streak = empty_commit_streak.saturating_add(1);
            } else {
                *empty_commit_streak = 0;
            }
            if *empty_commit_streak >= stall_config.threshold {
                let message = format!(
                    "Stall detected for {} after {} empty WIP commits (archive)",
                    change_id, *empty_commit_streak
                );
                output.on_warn(&format!(
                    "{} (threshold {})",
                    message, stall_config.threshold
                ));
                return Ok(Some(message));
            }
        }
        Err(e) => {
            output.on_warn(&format!(
                "Failed to check WIP(archive) commit for {} (attempt {}): {}",
                change_id, attempt, e
            ));
        }
    }

    Ok(None)
}

/// Helper: Verify archive completion and record history.
///
/// Verifies that the archive completed successfully and records the attempt in history.
/// Returns true if archive succeeded, false if it needs to be retried.
#[allow(clippy::too_many_arguments)]
fn verify_and_record_archive<O>(
    agent: &mut AgentRunner,
    change_id: &str,
    status: &std::process::ExitStatus,
    start: std::time::Instant,
    output_collector: &OutputCollector,
    base_path: Option<&Path>,
    attempt: u32,
    max_attempts: u32,
    output: &O,
) -> bool
where
    O: OutputHandler,
{
    use crate::execution::archive::{verify_archive_completion, ArchiveVerificationResult};

    // Verify archive was successful
    let verification_status = verify_archive_completion(change_id, base_path);
    if verification_status.is_success() {
        // Record successful archive attempt
        agent.record_archive_attempt(
            change_id,
            status,
            start,
            None,
            output_collector.stdout_tail(),
            output_collector.stderr_tail(),
        );
        return true;
    }

    // Verification failed - record with reason
    let verification_reason = match verification_status {
        ArchiveVerificationResult::NotArchived { ref change_id } => {
            format!("Change still exists at openspec/changes/{}", change_id)
        }
        _ => "Archive verification failed".to_string(),
    };
    agent.record_archive_attempt(
        change_id,
        status,
        start,
        Some(verification_reason.clone()),
        output_collector.stdout_tail(),
        output_collector.stderr_tail(),
    );

    if attempt < max_attempts {
        output.on_warn(&format!(
            "Archive verification failed for {} (attempt {}/{}): {}; retrying archive command",
            change_id, attempt, max_attempts, verification_reason
        ));
    }

    false
}

/// Helper: Clear history after successful archive.
///
/// Clears apply and archive history for the archived change.
fn clear_archive_history(agent: &mut AgentRunner, change_id: &str) {
    agent.clear_apply_history(change_id);
    agent.clear_archive_history(change_id);
}

/// Helper: Run post-archive hook.
///
/// Runs the post_archive hook with updated context.
async fn run_post_archive_hook<O>(
    hooks: &HookRunner,
    context: &ArchiveContext,
    change: &Change,
    output: &O,
) -> Result<()>
where
    O: OutputHandler,
{
    let post_ctx = HookContext::new(
        context.changes_processed + 1,
        context.total_changes,
        context.remaining_changes.saturating_sub(1),
        false,
    )
    .with_change(&change.id, change.completed_tasks, change.total_tasks)
    .with_apply_count(context.apply_count);

    if let Err(e) = hooks.run_hook(HookType::PostArchive, &post_ctx).await {
        output.on_warn(&format!("post_archive hook failed: {}", e));
        return Err(e);
    }

    Ok(())
}

/// Archive a change with streaming output.
///
/// Similar to `archive_change` but uses streaming output for real-time feedback.
/// This is primarily used by TUI mode.
///
/// # Arguments
/// * `change` - The change to archive
/// * `agent` - The agent runner for executing commands
/// * `hooks` - The hook runner for executing hooks
/// * `context` - Context information for hooks
/// * `output` - Output handler for streaming command output
/// * `cancel_check` - Function to check if operation should be cancelled
/// * `base_path` - Optional base path for archive verification
/// * `stall_config` - Stall detection configuration for empty WIP commits
///
/// # Returns
/// Same as `archive_change`
#[allow(clippy::too_many_arguments)]
pub async fn archive_change_streaming<O, F>(
    change: &Change,
    agent: &mut AgentRunner,
    ai_runner: &AiCommandRunner,
    hooks: &HookRunner,
    context: &ArchiveContext,
    output: &O,
    cancel_check: F,
    base_path: Option<&Path>,
    stall_config: &StallDetectionConfig,
) -> Result<ArchiveResult>
where
    O: OutputHandler,
    F: Fn() -> bool,
{
    info!("Archiving change (streaming): {}", change.id);

    // Build hook context
    let hook_ctx = HookContext::new(
        context.changes_processed,
        context.total_changes,
        context.remaining_changes,
        false,
    )
    .with_change(&change.id, change.completed_tasks, change.total_tasks)
    .with_apply_count(context.apply_count);

    // Run pre-archive hooks
    run_pre_archive_hooks(hooks, &hook_ctx, output).await?;

    output.on_info(&format!("Archiving: {}", change.id));

    use crate::execution::archive::{
        build_archive_error_message, extract_archive_runtime_blocker, ARCHIVE_COMMAND_MAX_RETRIES,
    };

    let max_attempts = ARCHIVE_COMMAND_MAX_RETRIES.saturating_add(1);
    let mut attempt: u32 = 0;
    let repo_root = base_path.unwrap_or_else(|| Path::new("."));
    let is_git_repo = match git_commands::check_git_repo(repo_root).await {
        Ok(is_repo) => is_repo,
        Err(e) => {
            output.on_warn(&format!("Failed to check Git repository status: {}", e));
            false
        }
    };
    let mut empty_commit_streak = 0u32;

    loop {
        attempt += 1;

        // Execute archive command with streaming
        let (status, output_collector, start) = match execute_archive_command_streaming(
            agent,
            ai_runner,
            &change.id,
            attempt,
            output,
            &cancel_check,
        )
        .await
        {
            Ok(result) => result,
            Err(e) => {
                // Cancellation or execution error
                if e.to_string().contains("cancelled") {
                    return Ok(ArchiveResult::Cancelled);
                }
                return Err(e);
            }
        };

        if !status.success() {
            let error_msg = format!(
                "Archive command failed for change '{}' (attempt {}) with exit code: {:?}",
                change.id,
                attempt,
                status.code()
            );

            // Record the failed attempt
            agent.record_archive_attempt(
                &change.id,
                &status,
                start,
                Some(error_msg.clone()),
                output_collector.stdout_tail(),
                output_collector.stderr_tail(),
            );

            // Run on_error hook
            let error_ctx = hook_ctx.clone().with_error(&error_msg);
            let _ = hooks.run_hook(HookType::OnError, &error_ctx).await;

            output.on_error(&error_msg);
            return Ok(ArchiveResult::Failed { error: error_msg });
        }

        // Handle WIP commit creation and stall detection
        if let Some(stall_message) = handle_archive_wip_and_stall(
            is_git_repo,
            repo_root,
            &change.id,
            attempt,
            &mut empty_commit_streak,
            stall_config,
            output,
        )
        .await?
        {
            return Ok(ArchiveResult::Stalled {
                error: stall_message,
            });
        }

        // Verify archive completion and record history
        if verify_and_record_archive(
            agent,
            &change.id,
            &status,
            start,
            &output_collector,
            base_path,
            attempt,
            max_attempts,
            output,
        ) {
            break;
        }

        if attempt > ARCHIVE_COMMAND_MAX_RETRIES {
            let runtime_blocker = extract_archive_runtime_blocker(
                output_collector.stdout_tail().as_deref(),
                output_collector.stderr_tail().as_deref(),
            );
            let error_msg =
                build_archive_error_message(&change.id, None, runtime_blocker.as_deref());
            output.on_error(&error_msg);
            return Ok(ArchiveResult::Failed { error: error_msg });
        }
    }

    if is_git_repo {
        if let Err(e) = git_commands::squash_archive_wip_commits(repo_root, &change.id).await {
            output.on_warn(&format!(
                "Failed to squash WIP(archive) commits for {}: {}",
                change.id, e
            ));
        }
    }

    // Clear apply and archive history
    clear_archive_history(agent, &change.id);

    // Run post_archive hook
    run_post_archive_hook(hooks, context, change, output).await?;

    info!("Successfully archived: {}", change.id);
    output.on_success(&format!("Archived: {}", change.id));

    Ok(ArchiveResult::Success)
}

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

    #[test]
    fn test_archive_result_is_success() {
        assert!(ArchiveResult::Success.is_success());
        assert!(!ArchiveResult::Stalled {
            error: "stalled".to_string()
        }
        .is_success());
        assert!(!ArchiveResult::Failed {
            error: "oops".to_string()
        }
        .is_success());
        assert!(!ArchiveResult::Cancelled.is_success());
    }

    #[test]
    fn test_archive_context_new() {
        let ctx = ArchiveContext::new(1, 5, 4, 2);
        assert_eq!(ctx.changes_processed, 1);
        assert_eq!(ctx.total_changes, 5);
        assert_eq!(ctx.remaining_changes, 4);
        assert_eq!(ctx.apply_count, 2);
    }

    #[test]
    fn test_verify_archive_path_structure() {
        // This test verifies the path structure is correct
        let change_id = "test-change";
        let change_path = Path::new("openspec/changes").join(change_id);
        let archive_path = Path::new("openspec/changes/archive").join(change_id);

        assert_eq!(
            change_path.to_str().unwrap(),
            "openspec/changes/test-change"
        );
        assert_eq!(
            archive_path.to_str().unwrap(),
            "openspec/changes/archive/test-change"
        );

        // Archive path should be under openspec/changes/archive, not openspec/archive
        assert!(archive_path.starts_with("openspec/changes/archive"));
    }

    #[cfg(unix)]
    #[test]
    fn test_archive_change_reports_runtime_blocker_when_archive_not_started() {
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();

        runtime.block_on(async {
            use crate::config::OrchestratorConfig;
            use crate::hooks::HookRunner;
            use crate::openspec::Change;
            use crate::orchestration::output::NullOutputHandler;
            use std::fs;
            use tempfile::TempDir;
            let temp_dir = TempDir::new().unwrap();

            let change_id = "blocked-change";
            let change_dir = temp_dir.path().join("openspec/changes").join(change_id);
            fs::create_dir_all(&change_dir).unwrap();

            let script_path = temp_dir.path().join("archive_blocked.sh");
            let script = r#"#!/bin/sh
printf 'ARCHIVE_READINESS_BLOCKER: missing accepted tasks\n'
exit 0
"#;
            fs::write(&script_path, script).unwrap();

            let config = OrchestratorConfig {
                archive_command: Some(format!("sh \"{}\" {change_id}", script_path.display())),
                // Keep regression test in default suite under 1s by removing queue staggering.
                command_queue_stagger_delay_ms: Some(0),
                ..Default::default()
            };

            let mut agent = AgentRunner::new(config.clone());
            let hooks = HookRunner::empty();
            let output = NullOutputHandler::new();
            let context = ArchiveContext::new(0, 1, 1, 0);
            let change = Change {
                id: change_id.to_string(),
                completed_tasks: 1,
                total_tasks: 1,
                last_modified: "".to_string(),
                dependencies: Vec::new(),
                metadata: crate::openspec::ProposalMetadata::default(),
            };

            use crate::ai_command_runner::{AiCommandRunner, SharedStaggerState};
            use crate::command_queue::CommandQueueConfig;
            use crate::config::defaults::*;
            use std::sync::Arc;
            use tokio::sync::Mutex;
            let queue_config = CommandQueueConfig {
                stagger_delay_ms: config
                    .command_queue_stagger_delay_ms
                    .unwrap_or(DEFAULT_STAGGER_DELAY_MS),
                max_retries: config
                    .command_queue_max_retries
                    .unwrap_or(DEFAULT_MAX_RETRIES),
                retry_delay_ms: config
                    .command_queue_retry_delay_ms
                    .unwrap_or(DEFAULT_RETRY_DELAY_MS),
                retry_error_patterns: config
                    .command_queue_retry_patterns
                    .clone()
                    .unwrap_or_else(default_retry_patterns),
                retry_if_duration_under_secs: config
                    .command_queue_retry_if_duration_under_secs
                    .unwrap_or(DEFAULT_RETRY_IF_DURATION_UNDER_SECS),
                inactivity_timeout_secs: config.get_command_inactivity_timeout_secs(),
                inactivity_kill_grace_secs: config.get_command_inactivity_kill_grace_secs(),
                inactivity_timeout_max_retries: config.get_command_inactivity_timeout_max_retries(),
                strict_process_cleanup: config.get_command_strict_process_cleanup(),
            };
            let shared_stagger_state: SharedStaggerState = Arc::new(Mutex::new(None));
            let ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state);

            let stall_config = OrchestratorConfig::default().get_stall_detection();
            let result = archive_change(
                &change,
                &mut agent,
                &ai_runner,
                &hooks,
                &context,
                &output,
                Some(temp_dir.path()),
                &stall_config,
            )
            .await
            .unwrap();

            match result {
                ArchiveResult::Failed { error } => {
                    assert!(error.contains("ARCHIVE_READINESS_BLOCKER"));
                    assert!(error.contains("missing accepted tasks"));
                }
                other => panic!("expected failure with blocker summary, got: {other:?}"),
            }

            assert!(change_dir.exists());
        });
    }

    #[cfg(feature = "heavy-tests")]
    #[cfg(unix)]
    #[tokio::test]
    async fn test_archive_change_retries_until_verified() {
        use crate::config::OrchestratorConfig;
        use crate::hooks::HookRunner;
        use crate::openspec::Change;
        use crate::orchestration::output::NullOutputHandler;
        use std::fs;
        use tempfile::TempDir;
        let temp_dir = TempDir::new().unwrap();

        let change_id = "retry-change";
        let change_dir = temp_dir.path().join("openspec/changes").join(change_id);
        let archive_dir = temp_dir.path().join("openspec/changes/archive");
        fs::create_dir_all(&change_dir).unwrap();
        fs::create_dir_all(&archive_dir).unwrap();

        let attempts_path = temp_dir.path().join("archive_attempts.txt");
        let script_path = temp_dir.path().join("archive.sh");
        let script = format!(
            r#"#!/bin/sh
attempts_file="{attempts}"
base_dir="{base_dir}"
count=0
if [ -f "$attempts_file" ]; then
  count=$(cat "$attempts_file")
fi
count=$((count+1))
echo "$count" > "$attempts_file"
if [ "$count" -lt 2 ]; then
  exit 0
fi
mkdir -p "$base_dir/openspec/changes/archive"
mv "$base_dir/openspec/changes/$1" "$base_dir/openspec/changes/archive/$1"
"#,
            attempts = attempts_path.display(),
            base_dir = temp_dir.path().display()
        );
        fs::write(&script_path, script).unwrap();

        let config = OrchestratorConfig {
            archive_command: Some(format!("sh \"{}\" {{change_id}}", script_path.display())),
            ..Default::default()
        };

        let mut agent = AgentRunner::new(config.clone());
        let hooks = HookRunner::empty();
        let output = NullOutputHandler::new();
        let context = ArchiveContext::new(0, 1, 1, 0);
        let change = Change {
            id: change_id.to_string(),
            completed_tasks: 1,
            total_tasks: 1,
            last_modified: "".to_string(),
            dependencies: Vec::new(),
            metadata: crate::openspec::ProposalMetadata::default(),
        };

        // Create AiCommandRunner for test
        use crate::ai_command_runner::{AiCommandRunner, SharedStaggerState};
        use crate::command_queue::CommandQueueConfig;
        use crate::config::defaults::*;
        use std::sync::Arc;
        use tokio::sync::Mutex;
        let queue_config = CommandQueueConfig {
            stagger_delay_ms: config
                .command_queue_stagger_delay_ms
                .unwrap_or(DEFAULT_STAGGER_DELAY_MS),
            max_retries: config
                .command_queue_max_retries
                .unwrap_or(DEFAULT_MAX_RETRIES),
            retry_delay_ms: config
                .command_queue_retry_delay_ms
                .unwrap_or(DEFAULT_RETRY_DELAY_MS),
            retry_error_patterns: config
                .command_queue_retry_patterns
                .clone()
                .unwrap_or_else(default_retry_patterns),
            retry_if_duration_under_secs: config
                .command_queue_retry_if_duration_under_secs
                .unwrap_or(DEFAULT_RETRY_IF_DURATION_UNDER_SECS),
            inactivity_timeout_secs: config.get_command_inactivity_timeout_secs(),
            inactivity_kill_grace_secs: config.get_command_inactivity_kill_grace_secs(),
            inactivity_timeout_max_retries: config.get_command_inactivity_timeout_max_retries(),
            strict_process_cleanup: config.get_command_strict_process_cleanup(),
        };
        let shared_stagger_state: SharedStaggerState = Arc::new(Mutex::new(None));
        let ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state);

        let stall_config = OrchestratorConfig::default().get_stall_detection();
        let result = archive_change(
            &change,
            &mut agent,
            &ai_runner,
            &hooks,
            &context,
            &output,
            Some(temp_dir.path()),
            &stall_config,
        )
        .await
        .unwrap();

        assert_eq!(result, ArchiveResult::Success);

        let attempts = fs::read_to_string(&attempts_path).unwrap();
        let attempt_count: u32 = attempts.trim().parse().unwrap();
        assert_eq!(attempt_count, 2);

        let archived_dir = temp_dir
            .path()
            .join("openspec/changes/archive")
            .join(change_id);
        assert!(!change_dir.exists());
        assert!(archived_dir.exists());
    }
}