loopflow 0.12.28

Run steps and flows with coding agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::engine::git::{
    current_branch, get_default_branch, is_clean, land as git_land, LandStrategy,
};
use crate::engine::worktrees::{main_repo_root, worktree_path};

use crate::engine::command::run_command;
use crate::ops::commit::{commit_workflow, CommitOptions};
use crate::ops::error::{OpsError, OpsResult};
use crate::ops::pr::{
    generate_pr_copy, normalize_task_pr_copy, read_cached_pr_copy, PrCopy, PrInfo,
    TaskPrCopyLifecycle,
};

use crate::ops::progress::Progress;

#[derive(Debug, Clone)]
pub struct LandOptions {
    pub strict: bool,
    pub local: bool,
    pub create_pr: bool,
    pub complete: bool,
    pub next_slug: Option<String>,
    pub worktree: Option<String>,
    pub commit_message: Option<String>,
    pub pr_title: Option<String>,
    pub pr_body: Option<String>,
    pub agent: Option<String>,
}

/// How a prepared PR is handed off once it is synced, scratch-cleared, and
/// marked ready.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Finalize {
    /// Arm GitHub auto-merge so the PR merges itself once checks pass. `arm`
    /// returns here; `land` continues into the watched lifecycle.
    AutoMerge,
    /// Assign the PR to the current user and leave it for a required, manual
    /// merge click. Used by `submit` — nothing merges without that one click.
    UserMerge,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Integration {
    Required,
    Completed,
}

/// Prepare one PR: commit, sync onto main, clear scratch, mark it ready, and
/// finalize per `finalize`. `arm` requests auto-merge; `submit` assigns the PR
/// for the reviewer to merge. Neither rotates the worktree. Returns the resulting PR,
/// or `None` for a local merge or direct Task completion over an already-merged
/// PR.
fn prepare_pr(
    repo: &Path,
    options: &LandOptions,
    finalize: Finalize,
    integration: Integration,
    progress: &impl Progress,
) -> OpsResult<Option<PrInfo>> {
    if options.complete && options.next_slug.is_some() {
        return Err(OpsError::Message(
            "--complete and --next cannot be used together".to_string(),
        ));
    }
    if options.local && (options.complete || options.next_slug.is_some()) {
        return Err(OpsError::Message(
            "Task disposition flags require a pull request merge and cannot be used with --local"
                .to_string(),
        ));
    }
    let (repo_root, main_repo) = resolve_repos(repo, options.worktree.as_deref())?;
    crate::ops::pr::reject_control_plane_pr(&repo_root)?;
    if options.complete && (!options.strict || is_clean(&repo_root)?) {
        if let Some(issue) = crate::ops::task::find_discardable_task_successor(&repo_root)? {
            // Rotation left one unpublished branch at its recorded base after
            // earlier Task work merged. The explicit `--complete` instruction
            // settles the Task without manufacturing an empty GitHub PR.
            clear_scratch(&repo_root, progress)?;
            crate::ops::task::task_complete(
                &repo_root,
                &issue,
                "Completed over its merged pull request".to_string(),
            )?;
            progress.status("Completed Task over its merged pull request.");
            return Ok(None);
        }
    }
    if !options.local && !crate::ops::pr::gh_available() {
        return Err(OpsError::Message("gh CLI not found".to_string()));
    }
    let task_context = if options.local {
        None
    } else {
        crate::ops::task::task_pr_context(&repo_root)?
    };
    let copy_lifecycle = if options.complete {
        TaskPrCopyLifecycle::Completes
    } else {
        TaskPrCopyLifecycle::Continues {
            next_slug: options.next_slug.clone(),
        }
    };
    let feature_branch = current_branch(&repo_root)?
        .ok_or_else(|| OpsError::Message("not on a branch".to_string()))?;
    // Prove the Task PR range before preparing the exact local tree. Submit and
    // land make no remote mutation until the owned integration pushes once.
    crate::ops::task::verify_task_pr_range(&repo_root)?;
    {
        let _mutation = crate::ops::task::lock_task_pr_mutation(&repo_root)?;
        if matches!(finalize, Finalize::AutoMerge) && matches!(integration, Integration::Required) {
            let after_merge = if options.complete {
                crate::work::task::AfterMerge::CompleteTask
            } else {
                crate::work::task::AfterMerge::ContinueTask
            };
            if let Some((number, head)) = crate::ops::task::matching_task_pr_merge_request(
                &repo_root,
                crate::work::task::PrMergeMode::Auto,
                after_merge,
                options.next_slug.as_deref(),
            )? {
                if let Some(pr) = crate::ops::pr::current_pr(&repo_root)? {
                    if pr.number == u64::from(number)
                        && pr.head_sha.as_deref() == Some(head.as_str())
                        && crate::ops::pr::auto_merge_enabled(&repo_root, pr.number)?
                    {
                        progress.status("Pull request is already armed for this exact head");
                        return Ok(Some(pr));
                    }
                }
            } else if task_context.is_none()
                && !options.local
                && !options.complete
                && options.next_slug.is_none()
                && is_clean(&repo_root)?
            {
                let head = crate::engine::git::rev_parse(&repo_root, "HEAD")?;
                if let Some(pr) = crate::ops::pr::current_pr(&repo_root)? {
                    if pr.head_sha.as_deref() == Some(head.as_str())
                        && crate::ops::pr::auto_merge_enabled(&repo_root, pr.number)?
                    {
                        update_pr_message(
                            &repo_root,
                            options.pr_title.as_deref(),
                            options.pr_body.as_deref(),
                        )?;
                        progress.status("Pull request is already armed for this exact head");
                        return Ok(Some(pr));
                    }
                }
            }
        }
        let cleared_task_request =
            crate::ops::task::clear_task_pr_merge_before_head_mutation(&repo_root, true)?;
        if !options.local && !cleared_task_request {
            // Wave and other non-Task PRs have no durable Task request to
            // revoke, but GitHub may still have this branch in its merge queue.
            // Dequeue it before sync/push; otherwise GitHub rejects the head
            // update and the repair cannot publish.
            if let Some(pr) = crate::ops::pr::current_pr(&repo_root)? {
                let number = u32::try_from(pr.number).map_err(|_| {
                    OpsError::Message(format!(
                        "pull request #{} exceeds supported range",
                        pr.number
                    ))
                })?;
                crate::ops::pr::disable_auto_merge(&repo_root, number)?;
            }
        }
    }
    match integration {
        Integration::Required => prepare_land(&repo_root, options, progress)?,
        Integration::Completed if !is_clean(&repo_root)? => {
            return Err(OpsError::Message(
                "recovered integration left uncommitted changes; refusing to mutate the verified head before PR finalization"
                    .to_string(),
            ));
        }
        Integration::Completed => {}
    }
    // Refuse an already-empty Task before scratch cleanup can manufacture a
    // bookkeeping-only `.gitkeep` commit or any GitHub command observes it.
    crate::ops::task::require_task_pr_range_nonempty(&repo_root)?;
    let pr_exists = if options.local {
        false
    } else {
        crate::ops::pr::pr_exists_for_current_branch(&repo_root)?
    };
    if !options.local && !pr_exists && !options.create_pr {
        return Err(OpsError::Message(format!(
            "no open PR found for branch '{feature_branch}'; run lf pr open or use --create-pr"
        )));
    }
    let copy_head = crate::engine::git::rev_parse(&repo_root, "HEAD")?;
    let copy_state = read_worktree_state(&repo_root)?;
    let copy = normalize_task_pr_copy(
        resolve_pr_copy(&repo_root, &copy_head, options, progress)?,
        task_context.as_ref(),
        &copy_lifecycle,
    )?;
    let current_head = crate::engine::git::rev_parse(&repo_root, "HEAD")?;
    if current_head != copy_head || read_worktree_state(&repo_root)? != copy_state {
        return Err(OpsError::Message(
            "PR copy generation changed the worktree; refusing to integrate or finalize unreviewed provider mutations"
                .to_string(),
        ));
    }
    if matches!(integration, Integration::Required) {
        clear_scratch(&repo_root, progress)?;
    }
    crate::ops::task::require_task_pr_range_nonempty(&repo_root)?;
    let main_branch = match integration {
        Integration::Required => sync_land(&repo_root, &main_repo, progress)?,
        Integration::Completed => accept_completed_integration(&repo_root, &main_repo)?,
    };
    // Sync may advance the fork point. Re-run the authoritative proof to heal
    // the recorded base and refuse an empty range before any `gh pr` side effect.
    crate::ops::task::require_task_pr_range_nonempty(&repo_root)?;
    if pr_exists {
        crate::ops::pr::retarget_open_pr(&repo_root, &main_branch)?;
    }
    if options.local {
        finalize_local(&repo_root, &main_branch, &feature_branch, progress)?;
        return Ok(None);
    }

    // Keep the publication read, exact-head request, remote finalization, and
    // any failure rollback atomic with respect to other Loopflow PR commands
    // and pushes in this worktree.
    let _mutation = crate::ops::task::lock_task_pr_mutation(&repo_root)?;
    crate::ops::task::request_task_pr_publication(&repo_root, &copy.title, &copy.body)?;
    let created_pr = ensure_pr(
        &repo_root,
        pr_exists,
        &feature_branch,
        options.create_pr,
        &main_branch,
        &copy,
    )?;
    let pr = match created_pr {
        Some(pr) => Some(pr),
        None => crate::ops::pr::current_pr(&repo_root)?,
    };
    crate::ops::task::attach_task_github_pr(&repo_root, pr.as_ref())?;
    crate::ops::task::request_task_pr_merge(
        &repo_root,
        match finalize {
            Finalize::AutoMerge => crate::work::task::PrMergeMode::Auto,
            Finalize::UserMerge => crate::work::task::PrMergeMode::User,
        },
        pr.as_ref().and_then(|pr| pr.head_sha.as_deref()),
        if options.complete {
            crate::work::task::AfterMerge::CompleteTask
        } else {
            crate::work::task::AfterMerge::ContinueTask
        },
        options.next_slug.as_deref(),
    )?;
    if let Err(finalize_error) = finalize_remote(
        &repo_root,
        &copy,
        finalize,
        pr.as_ref().map(|pr| pr.number),
        pr.as_ref().and_then(|pr| pr.head_sha.as_deref()),
        progress,
    ) {
        // The durable request is written before its remote executor. If any
        // later step fails, revoke a possibly-armed Auto request and clear the
        // local request so status never claims GitHub owns settlement when this
        // command did not complete. A failed revocation leaves the durable
        // request intact and reports both failures rather than guessing.
        if let Err(clear_error) =
            crate::ops::task::clear_task_pr_merge_before_head_mutation(&repo_root, true)
        {
            return Err(OpsError::Message(format!(
                "{finalize_error}; failed to reconcile the durable merge request: {clear_error}"
            )));
        }
        return Err(finalize_error);
    }
    Ok(pr)
}

/// Prepare a PR and request exact-head auto-merge, then return without watching.
pub fn arm(
    repo: &Path,
    options: &LandOptions,
    progress: &impl Progress,
) -> OpsResult<Option<PrInfo>> {
    prepare_pr(
        repo,
        options,
        Finalize::AutoMerge,
        Integration::Required,
        progress,
    )
}

/// Continue land after owned recovery already verified and pushed integration.
pub(crate) fn finish_arm_after_sync(
    repo: &Path,
    options: &LandOptions,
    progress: &impl Progress,
) -> OpsResult<Option<PrInfo>> {
    prepare_pr(
        repo,
        options,
        Finalize::AutoMerge,
        Integration::Completed,
        progress,
    )
}

/// Prepare a PR to land without arming auto-merge: commit, sync onto main,
/// clear scratch, mark the PR ready, and assign it to the current user. Nothing
/// merges until that user clicks merge on GitHub — that one click is the
/// required gate. Like `arm`, this never rotates the worktree.
pub fn submit(
    repo: &Path,
    options: &LandOptions,
    progress: &impl Progress,
) -> OpsResult<Option<PrInfo>> {
    prepare_pr(
        repo,
        options,
        Finalize::UserMerge,
        Integration::Required,
        progress,
    )
}

pub(crate) fn finish_submit_after_sync(
    repo: &Path,
    options: &LandOptions,
    progress: &impl Progress,
) -> OpsResult<Option<PrInfo>> {
    prepare_pr(
        repo,
        options,
        Finalize::UserMerge,
        Integration::Completed,
        progress,
    )
}

fn resolve_pr_copy(
    repo_root: &Path,
    head: &str,
    options: &LandOptions,
    progress: &impl Progress,
) -> OpsResult<PrCopy> {
    if options.local || options.pr_title.is_some() {
        return Ok(PrCopy {
            title: options.pr_title.clone().unwrap_or_default(),
            body: options.pr_body.clone().unwrap_or_default(),
        });
    }

    let mut copy = match read_cached_pr_copy(repo_root, progress)? {
        Some(copy) => {
            progress.status("Using cached PR copy from scratch/");
            copy
        }
        None => match crate::ops::pr::published_pr_copy(repo_root, head)? {
            Some(copy) => {
                progress.status("Keeping published PR copy for this head");
                copy
            }
            None => generate_pr_copy(repo_root, progress, options.agent.as_deref())?,
        },
    };
    if let Some(body) = &options.pr_body {
        copy.body = body.clone();
    }
    Ok(copy)
}

fn prepare_land(
    repo_root: &Path,
    options: &LandOptions,
    progress: &impl Progress,
) -> OpsResult<()> {
    if options.strict && !is_clean(repo_root)? {
        return Err(OpsError::Message(
            "uncommitted changes; commit, stash, or rerun without --strict".to_string(),
        ));
    }

    if !options.strict {
        let message = options
            .commit_message
            .clone()
            .unwrap_or_else(|| "lf land: stage uncommitted changes".to_string());
        let commit_options = CommitOptions {
            add: true,
            push: false,
            create_draft_pr: false,
            message: Some(message),
            agent: options.agent.clone(),
            ..CommitOptions::for_task("land")
        };
        let _ = commit_workflow(repo_root, &commit_options, progress)?;
    }

    Ok(())
}

fn sync_land(repo_root: &Path, main_repo: &Path, progress: &impl Progress) -> OpsResult<String> {
    let main_branch = get_default_branch(main_repo)?;
    let onto = format!("origin/{main_branch}");
    // Use the recorded parent base when integrating a squash-landed stack.
    let stacked = crate::ops::task::stack_for_landing(repo_root)?;
    let verification = crate::ops::sync::sync_for_delivery(
        repo_root,
        &crate::ops::sync::SyncOptions {
            onto: onto.clone(),
            push: true,
            fork_base: stacked.as_ref().map(|stacked| stacked.fork_base.clone()),
        },
        progress,
    )?;
    if let Some(stacked) = stacked {
        // Record the immutable target proven by the integration owner. Another
        // worktree may fetch and move origin/main after our pinned fetch.
        crate::ops::task::record_stack_sync(&stacked, &verification.target_sha, true)?;
    }
    Ok(main_branch)
}

fn accept_completed_integration(repo_root: &Path, main_repo: &Path) -> OpsResult<String> {
    let main_branch = get_default_branch(main_repo)?;
    if let Some(stacked) = crate::ops::task::stack_for_landing(repo_root)? {
        // The merge's second parent is the immutable integration target.
        let new_base = crate::engine::git::rev_parse(repo_root, "HEAD^2")?;
        crate::ops::task::record_stack_sync(&stacked, &new_base, true)?;
    }
    Ok(main_branch)
}

fn finalize_local(
    repo_root: &Path,
    main_branch: &str,
    feature_branch: &str,
    progress: &impl Progress,
) -> OpsResult<()> {
    progress.status("Merging locally...");
    let _ = git_land(repo_root, LandStrategy::LocalMerge, main_branch)?;
    delete_remote_branch(repo_root, feature_branch)?;
    Ok(())
}

fn ensure_pr(
    repo_root: &Path,
    pr_exists: bool,
    feature_branch: &str,
    create_pr: bool,
    base_branch: &str,
    copy: &PrCopy,
) -> OpsResult<Option<PrInfo>> {
    if !crate::ops::pr::gh_available() {
        return Err(OpsError::Message("gh CLI not found".to_string()));
    }

    if !pr_exists {
        if create_pr {
            return crate::ops::pr::create_pr_from_pushed_branch(
                repo_root,
                &copy.title,
                &copy.body,
                base_branch,
            )
            .map(Some);
        } else {
            return Err(OpsError::Message(format!(
                "no open PR found for branch '{feature_branch}'; run lf pr open or use --create-pr"
            )));
        }
    }

    Ok(None)
}

fn finalize_remote(
    repo_root: &Path,
    copy: &PrCopy,
    finalize: Finalize,
    number: Option<u64>,
    head_sha: Option<&str>,
    progress: &impl Progress,
) -> OpsResult<()> {
    progress.status("Updating PR...");
    update_pr_message(repo_root, Some(&copy.title), Some(&copy.body))?;
    mark_ready(repo_root)?;

    match finalize {
        Finalize::AutoMerge => {
            let number = number.ok_or_else(|| {
                OpsError::Message(
                    "GitHub did not report the current PR number; refusing to arm auto-merge"
                        .to_string(),
                )
            })?;
            let head_sha = head_sha.ok_or_else(|| {
                OpsError::Message(
                    "GitHub did not report the current PR head; refusing to arm unpinned auto-merge"
                        .to_string(),
                )
            })?;
            progress.status("Enabling auto-merge...");
            crate::ops::pr::enable_auto_merge(repo_root, number, Some(copy), head_sha)?;
        }
        Finalize::UserMerge => {
            progress.status("Assigning PR for you to merge...");
            assign_to_me(repo_root)?;
        }
    }

    if let Some(url) = current_pr_url(repo_root)? {
        progress.status(&format!("\n{url}\n"));
    }

    Ok(())
}

/// Assign the open PR to the authenticated user. Nothing merges until they
/// explicitly click merge.
fn assign_to_me(repo: &Path) -> OpsResult<()> {
    let mut cmd = Command::new("gh");
    cmd.arg("pr")
        .arg("edit")
        .arg("--add-assignee")
        .arg("@me")
        .current_dir(repo);
    if let Err(err) = run_command(&mut cmd) {
        return Err(OpsError::CommandFailed {
            command: err.command_line(),
            stderr: err.stderr,
        });
    }
    Ok(())
}

fn resolve_repos(repo: &Path, worktree: Option<&str>) -> OpsResult<(PathBuf, PathBuf)> {
    let main_repo = main_repo_root(repo).unwrap_or_else(|_| repo.to_path_buf());
    let repo_root = if let Some(worktree) = worktree {
        let candidate = Path::new(worktree);
        if candidate.exists() {
            candidate.to_path_buf()
        } else {
            let path = worktree_path(&main_repo, worktree);
            if path.exists() {
                path
            } else {
                return Err(OpsError::Message(format!(
                    "worktree not found: {}",
                    worktree
                )));
            }
        }
    } else {
        repo.to_path_buf()
    };

    Ok((repo_root, main_repo))
}

/// Clear `scratch/` down to `.gitkeep` and commit it.
///
/// This step is what greens the `scratch-clear` required check, which is why
/// that check is a *land-time precondition* and no repair turn can act on it —
/// see [`crate::work::task::CiCheck::land_time_precondition`], which keeps the landing
/// supervisor from launching `ci-fix` against work only this function can do.
fn clear_scratch(repo: &Path, progress: &impl Progress) -> OpsResult<()> {
    let scratch = repo.join("scratch");
    let gitkeep = scratch.join(".gitkeep");

    // Ensure scratch/ always exists.
    if !scratch.exists() {
        std::fs::create_dir_all(&scratch)?;
    }

    let mut removed = false;
    for entry in std::fs::read_dir(&scratch)? {
        let entry = entry?;
        let path = entry.path();
        // Preserve .gitkeep so the directory survives git operations.
        if path == gitkeep {
            continue;
        }
        if path.is_dir() {
            std::fs::remove_dir_all(&path)?;
        } else {
            std::fs::remove_file(&path)?;
        }
        removed = true;
    }

    // Ensure .gitkeep exists so scratch/ is tracked even when empty.
    if !gitkeep.exists() {
        std::fs::write(&gitkeep, "")?;
        removed = true; // needs staging
    }

    if !removed {
        return Ok(());
    }

    progress.status("Clearing scratch/...");
    crate::engine::git::stage_all(repo)?;
    if has_staged_changes(repo)? {
        crate::engine::git::commit(repo, "lf land: clear scratch/")?;
    }

    Ok(())
}

fn has_staged_changes(repo: &Path) -> OpsResult<bool> {
    let status = Command::new("git")
        .arg("diff")
        .arg("--cached")
        .arg("--quiet")
        .current_dir(repo)
        .status()?;
    Ok(!status.success())
}

fn read_worktree_state(repo: &Path) -> OpsResult<String> {
    let output = Command::new("git")
        .args(["status", "--porcelain=v1"])
        .current_dir(repo)
        .output()?;
    if !output.status.success() {
        return Err(OpsError::CommandFailed {
            command: "git status --porcelain=v1".to_string(),
            stderr: String::from_utf8_lossy(&output.stderr).trim().to_string(),
        });
    }
    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

fn update_pr_message(repo: &Path, title: Option<&str>, body: Option<&str>) -> OpsResult<()> {
    if title.is_none() && body.is_none() {
        return Ok(());
    }
    let mut cmd = Command::new("gh");
    cmd.args(["pr", "edit"]).current_dir(repo);
    if let Some(title) = title {
        cmd.args(["--title", title]);
    }
    if let Some(body) = body {
        cmd.args(["--body", body]);
    }
    if let Err(err) = run_command(&mut cmd) {
        return Err(OpsError::CommandFailed {
            command: err.command_line(),
            stderr: err.stderr,
        });
    }
    Ok(())
}

pub fn mark_ready(repo: &Path) -> OpsResult<()> {
    let mut cmd = Command::new("gh");
    cmd.arg("pr").arg("ready").current_dir(repo);
    if let Err(err) = run_command(&mut cmd) {
        return Err(OpsError::CommandFailed {
            command: err.command_line(),
            stderr: err.stderr,
        });
    }
    Ok(())
}

fn delete_remote_branch(repo: &Path, branch: &str) -> OpsResult<()> {
    let mut cmd = Command::new("git");
    cmd.args(["push", "origin", "--delete", branch])
        .current_dir(repo);
    if let Err(err) = run_command(&mut cmd) {
        return Err(OpsError::CommandFailed {
            command: err.command_line(),
            stderr: err.stderr,
        });
    }
    Ok(())
}

fn current_pr_url(repo: &Path) -> OpsResult<Option<String>> {
    let mut cmd = Command::new("gh");
    cmd.arg("pr")
        .arg("view")
        .arg("--json")
        .arg("url")
        .arg("-q")
        .arg(".url")
        .current_dir(repo);
    let output = match run_command(&mut cmd) {
        Ok(output) => output,
        Err(_) => return Ok(None),
    };
    let url = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if url.is_empty() {
        Ok(None)
    } else {
        Ok(Some(url))
    }
}