cflx 0.6.45

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
use std::ffi::OsStr;
use std::path::{Path, PathBuf};

use tokio::process::Command;
use tracing::{debug, info, warn};

use crate::ai_command_runner::{AiCommandRunner, OutputLine};
use crate::config::OrchestratorConfig;
use crate::error::{OrchestratorError, Result};
use crate::vcs::git::commands as git_commands;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RejectionReviewVerdict {
    Confirm,
    Resume,
    Block,
}

fn rejected_file_path(workspace_path: &Path, change_id: &str) -> PathBuf {
    workspace_path
        .join("openspec")
        .join("changes")
        .join(change_id)
        .join("REJECTED.md")
}

#[allow(dead_code)]
pub fn has_rejection_proposal(workspace_path: &Path, change_id: &str) -> bool {
    rejected_file_path(workspace_path, change_id).is_file()
}

fn resolve_rejection_review_command(template: &str, prompt: &str, change_id: &str) -> String {
    let command = OrchestratorConfig::expand_change_id(template, change_id);
    OrchestratorConfig::expand_prompt(&command, prompt)
}

fn rejection_review_prompt(change_id: &str) -> String {
    format!(
        "load skills: cflx-rejecting\n\nRejecting review id:{}\n\nchange_id: {}\nproposal_path: openspec/changes/{}/proposal.md\ntasks_path: openspec/changes/{}/tasks.md\nrejected_path: openspec/changes/{}/REJECTED.md",
        change_id, change_id, change_id, change_id, change_id
    )
}

fn parse_rejection_review_output(output: &str) -> Option<RejectionReviewVerdict> {
    let mut in_code_block = false;

    for line in output.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with("```") {
            in_code_block = !in_code_block;
            continue;
        }
        if in_code_block {
            continue;
        }

        if trimmed == "REJECTION_REVIEW: CONFIRM" {
            return Some(RejectionReviewVerdict::Confirm);
        }
        if trimmed == "REJECTION_REVIEW: RESUME" {
            return Some(RejectionReviewVerdict::Resume);
        }
        if trimmed == "REJECTION_REVIEW: BLOCK" {
            return Some(RejectionReviewVerdict::Block);
        }
    }

    None
}

fn append_recovery_task_section(existing: &str, change_id: &str) -> String {
    let heading = "## Rejecting Recovery Tasks";
    let task = format!(
        "- [ ] Capture unresolved blocker details in tasks.md (do not recreate REJECTED.md) and implement a non-rejection recovery path before rerunning apply for {}",
        change_id
    );

    if existing.contains(heading) {
        if existing.contains(&task) {
            return existing.to_string();
        }
        return format!("{}\n{}\n", existing.trim_end(), task);
    }

    format!("{}\n\n{}\n\n{}\n", existing.trim_end(), heading, task)
}

pub async fn run_rejection_review(
    change_id: &str,
    workspace_path: &Path,
    config: &OrchestratorConfig,
    ai_runner: &AiCommandRunner,
) -> Result<RejectionReviewVerdict> {
    let command_template = config.get_acceptance_command()?;
    let prompt = rejection_review_prompt(change_id);
    let command = resolve_rejection_review_command(command_template, &prompt, change_id);

    info!(
        change_id = %change_id,
        workspace = %workspace_path.display(),
        "Starting dedicated rejecting review"
    );

    let (mut child, mut output_rx) = ai_runner
        .execute_streaming_with_retry(
            &command,
            Some(workspace_path),
            Some("rejecting"),
            Some(change_id),
        )
        .await?;

    let mut stdout = String::new();
    while let Some(line) = output_rx.recv().await {
        match line {
            OutputLine::Stdout(s) => {
                stdout.push_str(&s);
                stdout.push('\n');
            }
            OutputLine::Stderr(_) => {}
        }
    }

    let status = child.wait().await.map_err(|e| {
        OrchestratorError::AgentCommand(format!(
            "Failed to wait for rejecting review command for change '{}': {}",
            change_id, e
        ))
    })?;

    if !status.success() {
        return Err(OrchestratorError::AgentCommand(format!(
            "Rejecting review command failed with exit code {:?} for change '{}'",
            status.code(),
            change_id
        )));
    }

    parse_rejection_review_output(&stdout).ok_or_else(|| {
        OrchestratorError::AgentCommand(format!(
            "Rejecting review output missing required marker for '{}' (expected exactly one of REJECTION_REVIEW: CONFIRM|RESUME|BLOCK)",
            change_id
        ))
    })
}

async fn clear_rejected_proposal_marker(change_id: &str, workspace_path: &Path) -> Result<PathBuf> {
    let rejected_path = rejected_file_path(workspace_path, change_id);
    if rejected_path.exists() {
        tokio::fs::remove_file(&rejected_path).await?;
    }
    Ok(rejected_path)
}

fn active_tasks_path(workspace_path: &Path, change_id: &str) -> PathBuf {
    workspace_path
        .join("openspec")
        .join("changes")
        .join(change_id)
        .join("tasks.md")
}

fn is_archive_dir_for_change(entry: &Path, change_id: &str) -> bool {
    entry
        .file_name()
        .and_then(OsStr::to_str)
        .map(|name| name == change_id || name.ends_with(&format!("-{}", change_id)))
        .unwrap_or(false)
}

/// Resolve canonical tasks.md for rejecting recovery writes.
///
/// Precedence is intentionally workspace-local and deterministic:
/// 1. active change directory (`openspec/changes/<change_id>/tasks.md`)
/// 2. archived change directory under workspace (`openspec/changes/archive/.../tasks.md`)
///
/// Unlike `task_parser::parse_progress_with_fallback`, this write path does not
/// use base-tree fallback because rejecting recovery must mutate the currently
/// resumed workspace context only.
async fn resolve_recovery_tasks_path(change_id: &str, workspace_path: &Path) -> Result<PathBuf> {
    let active = active_tasks_path(workspace_path, change_id);
    if tokio::fs::metadata(&active).await.is_ok() {
        debug!(
            change_id = %change_id,
            tasks_path = %active.display(),
            "Resolved rejecting recovery tasks path to active change directory"
        );
        return Ok(active);
    }

    let archive_root = workspace_path
        .join("openspec")
        .join("changes")
        .join("archive");
    let mut explored = vec![
        active.display().to_string(),
        archive_root.display().to_string(),
    ];

    let mut archived_candidates: Vec<PathBuf> = Vec::new();
    if let Ok(mut entries) = tokio::fs::read_dir(&archive_root).await {
        while let Ok(Some(entry)) = entries.next_entry().await {
            let path = entry.path();
            let is_dir = entry
                .file_type()
                .await
                .map(|ft| ft.is_dir())
                .unwrap_or(false);
            if !is_dir || !is_archive_dir_for_change(&path, change_id) {
                continue;
            }
            let tasks_path = path.join("tasks.md");
            explored.push(tasks_path.display().to_string());
            if tokio::fs::metadata(&tasks_path).await.is_ok() {
                archived_candidates.push(tasks_path);
            }
        }
    }

    archived_candidates.sort();
    if let Some(selected) = archived_candidates.into_iter().next() {
        debug!(
            change_id = %change_id,
            tasks_path = %selected.display(),
            "Resolved rejecting recovery tasks path to archived change directory"
        );
        return Ok(selected);
    }

    Err(OrchestratorError::AgentCommand(format!(
        "Failed to resolve canonical tasks.md for rejecting recovery '{}'. Explored paths: {}",
        change_id,
        explored.join(", ")
    )))
}

async fn append_recovery_task(change_id: &str, workspace_path: &Path) -> Result<PathBuf> {
    let tasks_path = resolve_recovery_tasks_path(change_id, workspace_path).await?;
    let current = tokio::fs::read_to_string(&tasks_path).await.map_err(|e| {
        OrchestratorError::AgentCommand(format!(
            "Failed to read tasks.md while updating rejecting recovery section for '{}' at '{}': {}",
            change_id,
            tasks_path.display(),
            e
        ))
    })?;
    let updated = append_recovery_task_section(&current, change_id);
    tokio::fs::write(&tasks_path, updated).await.map_err(|e| {
        OrchestratorError::AgentCommand(format!(
            "Failed to update tasks.md while updating rejecting recovery section for '{}' at '{}': {}",
            change_id,
            tasks_path.display(),
            e
        ))
    })?;

    Ok(tasks_path)
}

pub async fn handle_resume_apply_from_rejecting(
    change_id: &str,
    workspace_path: &Path,
) -> Result<()> {
    let rejected_path = clear_rejected_proposal_marker(change_id, workspace_path).await?;
    let tasks_path = append_recovery_task(change_id, workspace_path).await?;

    info!(
        change_id = %change_id,
        rejected_path = %rejected_path.display(),
        tasks_path = %tasks_path.display(),
        "Resumed apply from rejecting review"
    );

    Ok(())
}

pub async fn handle_blocked_from_rejecting(change_id: &str, workspace_path: &Path) -> Result<()> {
    let rejected_path = clear_rejected_proposal_marker(change_id, workspace_path).await?;
    let tasks_path = append_recovery_task(change_id, workspace_path).await?;

    info!(
        change_id = %change_id,
        rejected_path = %rejected_path.display(),
        tasks_path = %tasks_path.display(),
        "Rejecting review returned BLOCK; workspace remains blocked"
    );

    Ok(())
}

fn rejected_markdown(change_id: &str, reason: &str) -> String {
    format!(
        "# REJECTED\n\n- change_id: {}\n- reason: {}\n",
        change_id, reason
    )
}

fn extract_rejected_reason(content: &str) -> Option<String> {
    content
        .lines()
        .map(str::trim)
        .find_map(|line| line.strip_prefix("- reason:").map(str::trim))
        .filter(|reason| !reason.is_empty())
        .map(ToString::to_string)
}

async fn resolve_rejection_reason(
    workspace_path: &Path,
    change_id: &str,
    fallback_reason: &str,
) -> String {
    let rejected_path = rejected_file_path(workspace_path, change_id);

    match tokio::fs::read_to_string(&rejected_path).await {
        Ok(content) => {
            if let Some(reason) = extract_rejected_reason(&content) {
                info!(
                    change_id = %change_id,
                    rejected_path = %rejected_path.display(),
                    "Using reason extracted from existing apply-generated REJECTED.md proposal"
                );
                reason
            } else {
                fallback_reason.to_string()
            }
        }
        Err(_) => fallback_reason.to_string(),
    }
}

async fn cleanup_worktree(repo_root: &Path, worktree_path: &Path) {
    let worktree_path_str = worktree_path.to_string_lossy();
    match git_commands::worktree_remove(repo_root, &worktree_path_str).await {
        Ok(()) => {
            info!(
                worktree = %worktree_path.display(),
                repo_root = %repo_root.display(),
                "Removed rejected worktree"
            );
        }
        Err(e) => {
            warn!(
                error = %e,
                worktree = %worktree_path.display(),
                repo_root = %repo_root.display(),
                "Failed to remove rejected worktree (may already be removed)"
            );
        }
    }
}

/// Execute rejection flow for acceptance-gated changes.
///
/// Flow:
/// 1. checkout base branch
/// 2. write openspec/changes/<id>/REJECTED.md
/// 3. stage only openspec/changes/<id>/REJECTED.md
/// 4. commit on base branch
/// 5. cleanup rejected worktree
pub async fn execute_rejection_flow(
    change_id: &str,
    reason: &str,
    workspace_path: &Path,
    base_branch: &str,
    repo_root: &Path,
) -> Result<()> {
    info!(
        change_id = %change_id,
        workspace = %workspace_path.display(),
        repo_root = %repo_root.display(),
        base_branch = %base_branch,
        "Starting rejection flow"
    );

    let effective_reason = resolve_rejection_reason(workspace_path, change_id, reason).await;

    git_commands::checkout(repo_root, base_branch)
        .await
        .map_err(OrchestratorError::from_vcs_error)?;

    let rejected_path = rejected_file_path(repo_root, change_id);
    let rejected_parent = rejected_path.parent().ok_or_else(|| {
        OrchestratorError::AgentCommand(format!(
            "Invalid REJECTED.md path for change '{}'",
            change_id
        ))
    })?;

    tokio::fs::create_dir_all(rejected_parent).await?;
    tokio::fs::write(
        &rejected_path,
        rejected_markdown(change_id, &effective_reason),
    )
    .await?;

    let relative_rejected_path = format!("openspec/changes/{}/REJECTED.md", change_id);
    let add_output = Command::new("git")
        .args(["add", &relative_rejected_path])
        .current_dir(repo_root)
        .output()
        .await?;
    if !add_output.status.success() {
        return Err(OrchestratorError::AgentCommand(format!(
            "git add failed for '{}': {}",
            relative_rejected_path,
            String::from_utf8_lossy(&add_output.stderr).trim()
        )));
    }

    let staged_paths_output = Command::new("git")
        .args(["diff", "--cached", "--name-only"])
        .current_dir(repo_root)
        .output()
        .await?;
    if !staged_paths_output.status.success() {
        return Err(OrchestratorError::AgentCommand(format!(
            "git diff --cached --name-only failed for rejection '{}': {}",
            change_id,
            String::from_utf8_lossy(&staged_paths_output.stderr).trim()
        )));
    }

    let staged_paths_stdout = String::from_utf8_lossy(&staged_paths_output.stdout).into_owned();
    let staged_paths = staged_paths_stdout
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .map(ToString::to_string)
        .collect::<Vec<_>>();

    if staged_paths != vec![relative_rejected_path.clone()] {
        return Err(OrchestratorError::AgentCommand(format!(
            "rejection flow staged unexpected files for '{}': {:?}",
            change_id, staged_paths
        )));
    }

    let commit_message = format!("reject(openspec): {}", change_id);
    let commit_output = Command::new("git")
        .args([
            "commit",
            "-m",
            &commit_message,
            "--",
            &relative_rejected_path,
        ])
        .current_dir(repo_root)
        .output()
        .await?;
    if !commit_output.status.success() {
        return Err(OrchestratorError::AgentCommand(format!(
            "git commit failed for rejection '{}': {}",
            change_id,
            String::from_utf8_lossy(&commit_output.stderr).trim()
        )));
    }

    debug!(change_id = %change_id, "Committed REJECTED.md on base branch");

    cleanup_worktree(repo_root, workspace_path).await;

    info!(change_id = %change_id, "Rejection flow completed");
    Ok(())
}

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

    async fn init_git_repo(path: &Path) {
        let status = Command::new("git")
            .args(["init", "-b", "main"])
            .current_dir(path)
            .status()
            .await
            .expect("git init failed");
        assert!(status.success());

        let status = Command::new("git")
            .args(["config", "user.email", "test@example.com"])
            .current_dir(path)
            .status()
            .await
            .expect("git config email failed");
        assert!(status.success());

        let status = Command::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(path)
            .status()
            .await
            .expect("git config name failed");
        assert!(status.success());

        fs::write(path.join("README.md"), "# test\n").expect("write readme");
        let status = Command::new("git")
            .args(["add", "."])
            .current_dir(path)
            .status()
            .await
            .expect("git add failed");
        assert!(status.success());

        let status = Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(path)
            .status()
            .await
            .expect("git commit failed");
        assert!(status.success());
    }

    #[test]
    fn test_rejected_markdown_contains_reason() {
        let content = rejected_markdown("change-a", "spec mismatch");
        assert!(content.contains("change_id: change-a"));
        assert!(content.contains("reason: spec mismatch"));
    }

    #[test]
    fn test_extract_rejected_reason_parses_reason_line() {
        let content = "# REJECTED\n\n- change_id: change-a\n- reason: apply blocked handoff\n";
        let reason = extract_rejected_reason(content);
        assert_eq!(reason.as_deref(), Some("apply blocked handoff"));
    }

    #[test]
    fn test_extract_rejected_reason_returns_none_without_reason_line() {
        let content = "# REJECTED\n\n- change_id: change-a\n";
        let reason = extract_rejected_reason(content);
        assert!(reason.is_none());
    }

    #[test]
    fn test_rejected_file_path_layout() {
        let path = rejected_file_path(Path::new("/tmp/ws"), "change-a");
        assert!(path.ends_with("openspec/changes/change-a/REJECTED.md"));
    }

    #[test]
    fn test_has_rejection_proposal_detects_marker_file() {
        let temp_dir = tempfile::tempdir().unwrap();
        let change_dir = temp_dir.path().join("openspec/changes/change-a");
        std::fs::create_dir_all(&change_dir).unwrap();

        assert!(
            !has_rejection_proposal(temp_dir.path(), "change-a"),
            "proposal should be absent before REJECTED.md exists"
        );

        std::fs::write(change_dir.join("REJECTED.md"), "# REJECTED").unwrap();
        assert!(
            has_rejection_proposal(temp_dir.path(), "change-a"),
            "proposal should be detected after REJECTED.md is created"
        );
    }

    #[test]
    fn test_append_recovery_task_section_avoids_deleted_rejected_marker_reference() {
        let existing = "## Implementation Tasks\n\n- [ ] keep going\n";
        let updated = append_recovery_task_section(existing, "change-a");
        assert!(
            updated.contains("## Rejecting Recovery Tasks"),
            "recovery section should be appended"
        );
        assert!(
            updated.contains("do not recreate REJECTED.md"),
            "recovery task should explicitly avoid relying on deleted marker"
        );
        assert!(
            !updated.contains("Investigate blocker in openspec/changes/change-a/REJECTED.md"),
            "recovery task must not reference deleted worktree-local REJECTED.md"
        );
    }

    #[tokio::test]
    async fn test_resolve_recovery_tasks_path_prefers_active_tasks() {
        let temp_dir = tempfile::tempdir().expect("temp dir");
        let workspace = temp_dir.path();
        let change_id = "change-a";
        let active_dir = workspace.join("openspec").join("changes").join(change_id);
        fs::create_dir_all(&active_dir).expect("create active dir");
        fs::write(active_dir.join("tasks.md"), "## Implementation Tasks\n").expect("write tasks");

        let resolved = resolve_recovery_tasks_path(change_id, workspace)
            .await
            .expect("resolve path");

        assert_eq!(resolved, active_dir.join("tasks.md"));
    }

    #[tokio::test]
    async fn test_resolve_recovery_tasks_path_falls_back_to_archive_tasks() {
        let temp_dir = tempfile::tempdir().expect("temp dir");
        let workspace = temp_dir.path();
        let change_id = "change-a";
        let archive_dir = workspace
            .join("openspec")
            .join("changes")
            .join("archive")
            .join("2026-04-29-change-a");
        fs::create_dir_all(&archive_dir).expect("create archive dir");
        fs::write(archive_dir.join("tasks.md"), "## Implementation Tasks\n").expect("write tasks");

        let resolved = resolve_recovery_tasks_path(change_id, workspace)
            .await
            .expect("resolve path");

        assert_eq!(resolved, archive_dir.join("tasks.md"));
    }

    #[tokio::test]
    async fn test_resolve_recovery_tasks_path_reports_explored_paths_when_missing() {
        let temp_dir = tempfile::tempdir().expect("temp dir");
        let workspace = temp_dir.path();
        let change_id = "change-a";
        let archive_candidate = workspace
            .join("openspec")
            .join("changes")
            .join("archive")
            .join("2026-04-29-change-a");
        fs::create_dir_all(&archive_candidate).expect("create archive candidate");

        let err = resolve_recovery_tasks_path(change_id, workspace)
            .await
            .expect_err("expected path resolution failure");
        let message = err.to_string();

        assert!(message.contains("Explored paths:"));
        assert!(message.contains("openspec/changes/change-a/tasks.md"));
        assert!(message.contains("openspec/changes/archive/2026-04-29-change-a/tasks.md"));
    }

    #[tokio::test]
    async fn test_handle_resume_apply_from_rejecting_updates_archived_tasks_file() {
        let temp_dir = tempfile::tempdir().expect("temp dir");
        let workspace = temp_dir.path();
        let change_id = "change-a";
        let archive_dir = workspace
            .join("openspec")
            .join("changes")
            .join("archive")
            .join("2026-04-29-change-a");
        fs::create_dir_all(&archive_dir).expect("create archive dir");
        fs::write(
            archive_dir.join("tasks.md"),
            "## Implementation Tasks\n- [ ] keep\n",
        )
        .expect("write tasks");

        handle_resume_apply_from_rejecting(change_id, workspace)
            .await
            .expect("resume should succeed with archived tasks path");

        let updated = fs::read_to_string(archive_dir.join("tasks.md")).expect("read updated tasks");
        assert!(updated.contains("## Rejecting Recovery Tasks"));
    }

    #[tokio::test]
    async fn test_handle_blocked_from_rejecting_updates_archived_tasks_file() {
        let temp_dir = tempfile::tempdir().expect("temp dir");
        let workspace = temp_dir.path();
        let change_id = "change-a";
        let archive_dir = workspace
            .join("openspec")
            .join("changes")
            .join("archive")
            .join("2026-04-29-change-a");
        fs::create_dir_all(&archive_dir).expect("create archive dir");
        fs::write(
            archive_dir.join("tasks.md"),
            "## Implementation Tasks\n- [ ] keep\n",
        )
        .expect("write tasks");

        handle_blocked_from_rejecting(change_id, workspace)
            .await
            .expect("block should succeed with archived tasks path");

        let updated = fs::read_to_string(archive_dir.join("tasks.md")).expect("read updated tasks");
        assert!(updated.contains("## Rejecting Recovery Tasks"));
    }

    #[tokio::test]
    async fn test_execute_rejection_flow_creates_marker_commits_and_cleans_worktree() {
        let temp_dir = tempfile::tempdir().expect("temp dir");
        let repo_root = temp_dir.path();
        init_git_repo(repo_root).await;

        let change_id = "blocked-change";
        let change_dir = repo_root.join("openspec").join("changes").join(change_id);
        fs::create_dir_all(&change_dir).expect("create change dir");
        fs::write(change_dir.join("proposal.md"), "# proposal\n").expect("write proposal");
        fs::write(change_dir.join("tasks.md"), "- [ ] task\n").expect("write tasks");

        let current_branch = git_commands::get_current_branch(repo_root)
            .await
            .expect("current branch")
            .expect("branch name");

        let worktree_parent = repo_root.join(".worktrees");
        fs::create_dir_all(&worktree_parent).expect("create worktree parent");
        let worktree_path = worktree_parent.join(change_id);
        git_commands::worktree_add(
            repo_root,
            worktree_path.to_str().expect("worktree path"),
            &format!("wt/{}", change_id),
            &current_branch,
        )
        .await
        .expect("create worktree");

        let result = execute_rejection_flow(
            change_id,
            "Implementation blocker detected",
            &worktree_path,
            &current_branch,
            repo_root,
        )
        .await;

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

        let marker_path = change_dir.join("REJECTED.md");
        assert!(marker_path.exists(), "REJECTED.md must be created");
        let marker = fs::read_to_string(&marker_path).expect("read marker");
        assert!(marker.contains("change_id: blocked-change"));
        assert!(marker.contains("reason: Implementation blocker detected"));

        let head_message = Command::new("git")
            .args(["log", "-1", "--pretty=%s"])
            .current_dir(repo_root)
            .output()
            .await
            .expect("read commit message");
        assert!(head_message.status.success());
        let message = String::from_utf8_lossy(&head_message.stdout);
        assert!(message
            .trim()
            .starts_with("reject(openspec): blocked-change"));

        let committed_paths = Command::new("git")
            .args(["show", "--name-only", "--pretty=format:", "HEAD"])
            .current_dir(repo_root)
            .output()
            .await
            .expect("read committed paths");
        assert!(committed_paths.status.success());
        let committed_paths_stdout = String::from_utf8_lossy(&committed_paths.stdout).into_owned();
        let committed_paths = committed_paths_stdout
            .lines()
            .map(str::trim)
            .filter(|line| !line.is_empty())
            .map(ToString::to_string)
            .collect::<Vec<_>>();
        assert_eq!(
            committed_paths,
            vec!["openspec/changes/blocked-change/REJECTED.md".to_string()],
            "rejection commit must contain only REJECTED.md"
        );

        let list = git_commands::list_worktrees(repo_root)
            .await
            .expect("list worktrees after cleanup");
        assert!(
            !list
                .iter()
                .any(|(path, _, _, _, _)| path == &worktree_path.to_string_lossy()),
            "rejected worktree must be removed"
        );
    }
}