cruise 0.1.82

YAML-driven coding agent workflow orchestrator
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
use crate::error::{CruiseError, Result};
use crate::session::{SessionManager, SessionState};
use crate::worktree_pr::gh_output_line;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PublishedIssue {
    pub url: String,
    pub repo: String,
}

/// Parse a `git remote` origin URL into a GitHub `owner/repo` slug.
///
/// Supports HTTPS URLs (`https://github.com/owner/repo[.git]`), SSH URLs
/// (`ssh://git@github.com/owner/repo[.git]`), and the scp-like syntax
/// (`git@github.com:owner/repo[.git]`). Returns `None` for non-GitHub hosts
/// or input that doesn't match any of these forms.
#[must_use]
pub fn parse_github_repo_from_origin(origin_url: &str) -> Option<String> {
    let trimmed = origin_url.trim();
    let without_suffix = trimmed.strip_suffix(".git").unwrap_or(trimmed);

    let (host, path) = if let Some((_scheme, remainder)) = without_suffix.split_once("://") {
        let after_user = remainder
            .rsplit_once('@')
            .map_or(remainder, |(_, host_and_path)| host_and_path);
        after_user.split_once('/')?
    } else {
        let (user_and_host, path) = without_suffix.split_once(':')?;
        let host = user_and_host
            .rsplit_once('@')
            .map_or(user_and_host, |(_, host)| host);
        (host, path)
    };

    if host != "github.com" {
        return None;
    }

    let mut segments = path.trim_matches('/').split('/');
    let owner = segments.next().filter(|s| !s.is_empty())?;
    let repo = segments.next().filter(|s| !s.is_empty())?;
    if segments.next().is_some() {
        return None;
    }
    Some(format!("{owner}/{repo}"))
}

/// Resolve the `owner/repo` slug for `session`: its recorded `repo` field if
/// set, otherwise the `origin` remote of its `base_dir` git checkout.
fn resolve_repo(session: &SessionState) -> Result<String> {
    if let Some(repo) = &session.repo {
        return Ok(repo.clone());
    }

    let output = std::process::Command::new("git")
        .args(["remote", "get-url", "origin"])
        .current_dir(&session.base_dir)
        .output()
        .map_err(|e| CruiseError::Other(format!("failed to run git remote get-url origin: {e}")))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(CruiseError::Other(format!(
            "failed to determine GitHub repository: git remote get-url origin failed: {}",
            stderr.trim()
        )));
    }

    let origin_url = String::from_utf8_lossy(&output.stdout).trim().to_string();
    parse_github_repo_from_origin(&origin_url).ok_or_else(|| {
        CruiseError::Other(format!(
            "could not determine GitHub repository from origin URL: {origin_url}"
        ))
    })
}

/// Publish a session's generated plan as a GitHub issue, then delete the
/// local session.
///
/// The target repository comes from `session.repo` if set, otherwise from
/// the `origin` remote of `session.base_dir`. The issue body is always the
/// generated plan, unchanged. When `trigger_cruise` is `true`, a separate
/// `@cruise run` comment is posted on the created issue after it's created,
/// so the `@cruise` GitHub Action picks it up.
///
/// If a previous call already created the issue but failed on the follow-up
/// comment, `session.published_issue_url` carries the created issue's URL;
/// this call reuses it instead of running `gh issue create` again, so retries
/// never create a duplicate issue.
///
/// # Errors
///
/// Returns an error if the repository cannot be determined, the generated
/// plan is missing or empty, `gh issue create` fails, or (when
/// `trigger_cruise` is `true`) the follow-up `gh issue comment` fails. The
/// session is left in place whenever publishing fails; if the issue was
/// already created but the comment failed, the error message includes the
/// issue URL and the session's `published_issue_url` is set so a retry posts
/// the comment without recreating the issue.
pub fn publish_plan_issue_and_delete(
    manager: &SessionManager,
    mut session: SessionState,
    trigger_cruise: bool,
) -> Result<PublishedIssue> {
    let repo = resolve_repo(&session)?;

    let url = if let Some(existing_url) = session.published_issue_url.clone() {
        existing_url
    } else {
        let plan_path = session.plan_path(&manager.sessions_dir());
        let plan_content = std::fs::read_to_string(&plan_path).map_err(|e| {
            CruiseError::Other(format!(
                "failed to read generated plan at {}: {e}",
                plan_path.display()
            ))
        })?;
        if plan_content.trim().is_empty() {
            return Err(CruiseError::Other(format!(
                "no generated plan found for session {}",
                session.id
            )));
        }

        let body_path = manager
            .sessions_dir()
            .join(&session.id)
            .join("issue-body.md");
        std::fs::write(&body_path, &plan_content)?;

        let output = std::process::Command::new("gh")
            .arg("issue")
            .arg("create")
            .arg("--repo")
            .arg(&repo)
            .arg("--title")
            .arg(session.title_or_input())
            .arg("--body-file")
            .arg(&body_path)
            .output()
            .map_err(|e| CruiseError::Other(format!("failed to run gh issue create: {e}")))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(CruiseError::Other(format!(
                "gh issue create failed: {}",
                stderr.trim()
            )));
        }

        let url = gh_output_line(&output.stdout).ok_or_else(|| {
            CruiseError::Other("gh issue create succeeded but printed no URL".to_string())
        })?;

        session.published_issue_url = Some(url.clone());
        manager.save(&session)?;
        url
    };

    if trigger_cruise {
        let comment_output = std::process::Command::new("gh")
            .arg("issue")
            .arg("comment")
            .arg(&url)
            .arg("--body")
            .arg("@cruise run")
            .output()
            .map_err(|e| CruiseError::Other(format!("failed to run gh issue comment: {e}")))?;

        if !comment_output.status.success() {
            let stderr = String::from_utf8_lossy(&comment_output.stderr);
            return Err(CruiseError::Other(format!(
                "issue {url} was created, but posting the `@cruise run` comment failed: {}. \
                 Post the comment manually, or retry publishing -- the existing issue will be reused, not duplicated.",
                stderr.trim()
            )));
        }
    }

    if session.repo.is_some() {
        crate::repo_clone::cleanup_session_workspace(manager, &session);
    } else if let Some(ctx) = session.worktree_context()
        && let Err(e) = crate::worktree::cleanup_worktree(&ctx)
    {
        eprintln!("warning: failed to remove worktree for {}: {e}", session.id);
    }
    manager.delete(&session.id)?;

    Ok(PublishedIssue { url, repo })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::session::{SessionPhase, SessionState};
    use std::fs;
    use std::path::Path;
    use tempfile::TempDir;

    #[test]
    fn parse_github_repo_from_origin_https() {
        assert_eq!(
            parse_github_repo_from_origin("https://github.com/owner/repo.git").as_deref(),
            Some("owner/repo")
        );
        assert_eq!(
            parse_github_repo_from_origin("https://github.com/owner/repo").as_deref(),
            Some("owner/repo")
        );
    }

    #[test]
    fn parse_github_repo_from_origin_ssh_scp() {
        assert_eq!(
            parse_github_repo_from_origin("git@github.com:owner/repo.git").as_deref(),
            Some("owner/repo")
        );
    }

    #[test]
    fn parse_github_repo_from_origin_ssh_url() {
        assert_eq!(
            parse_github_repo_from_origin("ssh://git@github.com/owner/repo.git").as_deref(),
            Some("owner/repo")
        );
    }

    #[test]
    fn parse_github_repo_from_origin_rejects_non_github_urls() {
        assert_eq!(
            parse_github_repo_from_origin("https://example.com/owner/repo"),
            None
        );
        assert_eq!(
            parse_github_repo_from_origin("git@example.com:owner/repo.git"),
            None
        );
        assert_eq!(parse_github_repo_from_origin("not a url"), None);
    }

    #[test]
    fn publish_plan_issue_uses_session_repo_and_deletes_session() {
        let _lock = crate::test_support::lock_process();
        let temp = TempDir::new().unwrap_or_else(|e| panic!("{e}"));
        let manager = SessionManager::new(temp.path().join("data"));
        let mut session = make_awaiting_session("sess-repo", temp.path());
        session.repo = Some("owner/repo".to_string());
        manager.create(&session).unwrap_or_else(|e| panic!("{e}"));
        fs::write(
            session.plan_path(&manager.sessions_dir()),
            "# Build the feature\n",
        )
        .unwrap_or_else(|e| panic!("{e}"));

        let bin_dir = temp.path().join("bin");
        let gh_log = temp.path().join("gh.log");
        install_issue_gh(&bin_dir, &gh_log, temp.path().join("body.md"), true, true);
        let _path = crate::test_support::prepend_to_path(&bin_dir);

        let published = publish_plan_issue_and_delete(&manager, session.clone(), false)
            .unwrap_or_else(|e| panic!("{e}"));

        assert_eq!(published.repo, "owner/repo");
        assert_eq!(published.url, "https://github.com/owner/repo/issues/123");
        assert!(
            fs::read_to_string(&gh_log)
                .unwrap_or_else(|e| panic!("{e}"))
                .contains("issue create --repo owner/repo")
        );
        assert!(!manager.sessions_dir().join(&session.id).exists());
    }

    #[test]
    fn publish_plan_issue_body_is_plan_content_verbatim_regardless_of_trigger_cruise() {
        // trigger_cruise only controls whether a follow-up comment is posted
        // (see the dedicated posts_run_comment / does_not_post_comment tests
        // below); the issue body itself is always plan.md, unchanged.
        let _lock = crate::test_support::lock_process();
        for trigger_cruise in [false, true] {
            let temp = TempDir::new().unwrap_or_else(|e| panic!("{e}"));
            let manager = SessionManager::new(temp.path().join("data"));
            let mut session = make_awaiting_session("sess-body-verbatim", temp.path());
            session.repo = Some("owner/repo".to_string());
            manager.create(&session).unwrap_or_else(|e| panic!("{e}"));
            fs::write(
                session.plan_path(&manager.sessions_dir()),
                "# Build the feature\nDetails\n",
            )
            .unwrap_or_else(|e| panic!("{e}"));

            let bin_dir = temp.path().join("bin");
            let gh_log = temp.path().join("gh.log");
            let captured_body = temp.path().join("captured-body.md");
            install_issue_gh(&bin_dir, &gh_log, captured_body.clone(), true, true);
            let _path = crate::test_support::prepend_to_path(&bin_dir);

            publish_plan_issue_and_delete(&manager, session, trigger_cruise)
                .unwrap_or_else(|e| panic!("{e}"));

            let body = fs::read_to_string(captured_body).unwrap_or_else(|e| panic!("{e}"));
            assert_eq!(body, "# Build the feature\nDetails\n");
        }
    }

    #[test]
    fn publish_plan_issue_trigger_cruise_true_posts_run_comment() {
        // Given: a session ready to publish
        let _lock = crate::test_support::lock_process();
        let temp = TempDir::new().unwrap_or_else(|e| panic!("{e}"));
        let manager = SessionManager::new(temp.path().join("data"));
        let mut session = make_awaiting_session("sess-trigger-comment", temp.path());
        session.repo = Some("owner/repo".to_string());
        manager.create(&session).unwrap_or_else(|e| panic!("{e}"));
        fs::write(
            session.plan_path(&manager.sessions_dir()),
            "# Build the feature\n",
        )
        .unwrap_or_else(|e| panic!("{e}"));

        let bin_dir = temp.path().join("bin");
        let gh_log = temp.path().join("gh.log");
        install_issue_gh(&bin_dir, &gh_log, temp.path().join("body.md"), true, true);
        let _path = crate::test_support::prepend_to_path(&bin_dir);

        // When: trigger_cruise = true
        let published = publish_plan_issue_and_delete(&manager, session, true)
            .unwrap_or_else(|e| panic!("{e}"));

        // Then: a separate `gh issue comment <url> --body "@cruise run"` call was made
        let log = fs::read_to_string(&gh_log).unwrap_or_else(|e| panic!("{e}"));
        assert!(
            log.contains("issue comment") && log.contains(&published.url),
            "expected gh issue comment on the created issue: {log}"
        );
        assert!(
            log.contains("@cruise run"),
            "comment body should be exactly '@cruise run': {log}"
        );
    }

    #[test]
    fn publish_plan_issue_trigger_cruise_false_does_not_post_comment() {
        // Given: a session ready to publish
        let _lock = crate::test_support::lock_process();
        let temp = TempDir::new().unwrap_or_else(|e| panic!("{e}"));
        let manager = SessionManager::new(temp.path().join("data"));
        let mut session = make_awaiting_session("sess-no-comment", temp.path());
        session.repo = Some("owner/repo".to_string());
        manager.create(&session).unwrap_or_else(|e| panic!("{e}"));
        fs::write(
            session.plan_path(&manager.sessions_dir()),
            "# Build the feature\n",
        )
        .unwrap_or_else(|e| panic!("{e}"));

        let bin_dir = temp.path().join("bin");
        let gh_log = temp.path().join("gh.log");
        install_issue_gh(&bin_dir, &gh_log, temp.path().join("body.md"), true, true);
        let _path = crate::test_support::prepend_to_path(&bin_dir);

        // When: trigger_cruise = false
        publish_plan_issue_and_delete(&manager, session, false).unwrap_or_else(|e| panic!("{e}"));

        // Then: no comment call was made
        let log = fs::read_to_string(&gh_log).unwrap_or_else(|e| panic!("{e}"));
        assert!(
            !log.contains("issue comment"),
            "should not comment when trigger_cruise is false: {log}"
        );
    }

    #[test]
    fn publish_plan_issue_comment_failure_keeps_session_and_reports_issue_url() {
        // Given: `gh issue create` succeeds but the follow-up `gh issue comment` fails
        let _lock = crate::test_support::lock_process();
        let temp = TempDir::new().unwrap_or_else(|e| panic!("{e}"));
        let manager = SessionManager::new(temp.path().join("data"));
        let mut session = make_awaiting_session("sess-comment-fail", temp.path());
        session.repo = Some("owner/repo".to_string());
        manager.create(&session).unwrap_or_else(|e| panic!("{e}"));
        fs::write(
            session.plan_path(&manager.sessions_dir()),
            "# Build the feature\n",
        )
        .unwrap_or_else(|e| panic!("{e}"));

        let bin_dir = temp.path().join("bin");
        let gh_log = temp.path().join("gh.log");
        install_issue_gh(&bin_dir, &gh_log, temp.path().join("body.md"), true, false);
        let _path = crate::test_support::prepend_to_path(&bin_dir);

        // When
        let err = crate::test_support::err_string(publish_plan_issue_and_delete(
            &manager,
            session.clone(),
            true,
        ));

        // Then: the issue was already created, so its URL is surfaced for a manual retry
        assert!(
            err.contains("https://github.com/owner/repo/issues/123"),
            "error should include the created issue URL: {err}"
        );
        // And: the local session is left in place (not rolled back, not deleted)
        assert!(manager.sessions_dir().join(&session.id).exists());
        // And: the created issue URL is persisted so a retry does not recreate it
        let reloaded = manager.load(&session.id).unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(
            reloaded.published_issue_url.as_deref(),
            Some("https://github.com/owner/repo/issues/123")
        );
    }

    #[test]
    fn publish_plan_issue_retry_after_comment_failure_does_not_duplicate_issue() {
        // Given: a first attempt that created the issue but failed to post the comment
        let _lock = crate::test_support::lock_process();
        let temp = TempDir::new().unwrap_or_else(|e| panic!("{e}"));
        let manager = SessionManager::new(temp.path().join("data"));
        let mut session = make_awaiting_session("sess-retry", temp.path());
        session.repo = Some("owner/repo".to_string());
        manager.create(&session).unwrap_or_else(|e| panic!("{e}"));
        fs::write(
            session.plan_path(&manager.sessions_dir()),
            "# Build the feature\n",
        )
        .unwrap_or_else(|e| panic!("{e}"));

        let bin_dir = temp.path().join("bin");
        let gh_log = temp.path().join("gh.log");
        install_issue_gh(&bin_dir, &gh_log, temp.path().join("body.md"), true, false);
        let _path = crate::test_support::prepend_to_path(&bin_dir);

        crate::test_support::err_string(publish_plan_issue_and_delete(
            &manager,
            session.clone(),
            true,
        ));
        let after_first_attempt = manager.load(&session.id).unwrap_or_else(|e| panic!("{e}"));

        // When: retrying with a `gh` that would fail this test if `issue create`
        // ran again (only `issue comment` is wired to succeed)
        install_issue_gh(&bin_dir, &gh_log, temp.path().join("body.md"), false, true);
        let published = publish_plan_issue_and_delete(&manager, after_first_attempt, true)
            .unwrap_or_else(|e| panic!("{e}"));

        // Then: the same issue URL is reused, no second `issue create` call happened,
        // and the session is now deleted
        assert_eq!(published.url, "https://github.com/owner/repo/issues/123");
        let log = fs::read_to_string(&gh_log).unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(
            log.matches("issue create").count(),
            1,
            "issue create should only run once across the retry: {log}"
        );
        assert!(!manager.sessions_dir().join(&session.id).exists());
    }

    #[test]
    fn publish_plan_issue_from_planned_session_succeeds_and_deletes_session() {
        // Given: a session already approved into "Planned" phase
        let _lock = crate::test_support::lock_process();
        let temp = TempDir::new().unwrap_or_else(|e| panic!("{e}"));
        let manager = SessionManager::new(temp.path().join("data"));
        let mut session = make_awaiting_session("sess-planned", temp.path());
        session.phase = SessionPhase::Planned;
        session.repo = Some("owner/repo".to_string());
        manager.create(&session).unwrap_or_else(|e| panic!("{e}"));
        fs::write(
            session.plan_path(&manager.sessions_dir()),
            "# Build the feature\n",
        )
        .unwrap_or_else(|e| panic!("{e}"));

        let bin_dir = temp.path().join("bin");
        let gh_log = temp.path().join("gh.log");
        install_issue_gh(&bin_dir, &gh_log, temp.path().join("body.md"), true, true);
        let _path = crate::test_support::prepend_to_path(&bin_dir);

        // When
        let published = publish_plan_issue_and_delete(&manager, session.clone(), true)
            .unwrap_or_else(|e| panic!("{e}"));

        // Then
        assert_eq!(published.repo, "owner/repo");
        assert!(!manager.sessions_dir().join(&session.id).exists());
    }

    #[test]
    fn publish_plan_issue_does_not_delete_session_when_gh_fails() {
        let _lock = crate::test_support::lock_process();
        let temp = TempDir::new().unwrap_or_else(|e| panic!("{e}"));
        let manager = SessionManager::new(temp.path().join("data"));
        let mut session = make_awaiting_session("sess-fail", temp.path());
        session.repo = Some("owner/repo".to_string());
        manager.create(&session).unwrap_or_else(|e| panic!("{e}"));
        fs::write(
            session.plan_path(&manager.sessions_dir()),
            "# Build the feature\n",
        )
        .unwrap_or_else(|e| panic!("{e}"));

        let bin_dir = temp.path().join("bin");
        install_issue_gh(
            &bin_dir,
            temp.path().join("gh.log"),
            temp.path().join("body.md"),
            false,
            true,
        );
        let _path = crate::test_support::prepend_to_path(&bin_dir);

        let err = crate::test_support::err_string(publish_plan_issue_and_delete(
            &manager,
            session.clone(),
            false,
        ));

        assert!(err.contains("gh issue create"));
        assert!(manager.sessions_dir().join(&session.id).exists());
    }

    #[test]
    fn publish_plan_issue_errors_when_plan_missing_or_empty() {
        let temp = TempDir::new().unwrap_or_else(|e| panic!("{e}"));
        let manager = SessionManager::new(temp.path().join("data"));
        let mut session = make_awaiting_session("sess-empty", temp.path());
        session.repo = Some("owner/repo".to_string());
        manager.create(&session).unwrap_or_else(|e| panic!("{e}"));
        fs::write(session.plan_path(&manager.sessions_dir()), "   \n")
            .unwrap_or_else(|e| panic!("{e}"));

        let err = crate::test_support::err_string(publish_plan_issue_and_delete(
            &manager,
            session.clone(),
            false,
        ));

        assert!(err.contains("generated plan"));
        assert!(manager.sessions_dir().join(&session.id).exists());
    }

    #[test]
    fn publish_plan_issue_infers_repo_from_local_origin() {
        let _lock = crate::test_support::lock_process();
        let temp = TempDir::new().unwrap_or_else(|e| panic!("{e}"));
        let repo_dir = temp.path().join("repo");
        fs::create_dir_all(&repo_dir).unwrap_or_else(|e| panic!("{e}"));
        crate::test_support::init_git_repo(&repo_dir);
        crate::test_support::run_git_ok(
            &repo_dir,
            &["remote", "add", "origin", "git@github.com:owner/repo.git"],
        );

        let manager = SessionManager::new(temp.path().join("data"));
        let session = make_awaiting_session("sess-origin", &repo_dir);
        manager.create(&session).unwrap_or_else(|e| panic!("{e}"));
        fs::write(
            session.plan_path(&manager.sessions_dir()),
            "# Build the feature\n",
        )
        .unwrap_or_else(|e| panic!("{e}"));

        let bin_dir = temp.path().join("bin");
        let gh_log = temp.path().join("gh.log");
        install_issue_gh(&bin_dir, &gh_log, temp.path().join("body.md"), true, true);
        let _path = crate::test_support::prepend_to_path(&bin_dir);

        let published = publish_plan_issue_and_delete(&manager, session.clone(), false)
            .unwrap_or_else(|e| panic!("{e}"));

        assert_eq!(published.repo, "owner/repo");
        assert!(
            fs::read_to_string(&gh_log)
                .unwrap_or_else(|e| panic!("{e}"))
                .contains("issue create --repo owner/repo")
        );
        assert!(!manager.sessions_dir().join(&session.id).exists());
    }

    fn make_awaiting_session(id: &str, base_dir: &Path) -> SessionState {
        let mut session = SessionState::new(
            id.to_string(),
            base_dir.to_path_buf(),
            "cruise.yaml".to_string(),
            "test task".to_string(),
        );
        session.phase = SessionPhase::AwaitingApproval;
        session
    }

    /// Installs a fake `gh` on `PATH` that logs every invocation to `log_path`
    /// and handles two subcommands:
    /// - `gh issue create ... --body-file <path>`: copies the body to
    ///   `captured_body`, prints the fixed issue URL, and exits according to
    ///   `create_succeeds`.
    /// - `gh issue comment <url> --body "..."`: exits according to
    ///   `comment_succeeds`, without touching `captured_body`.
    #[cfg(unix)]
    fn install_issue_gh(
        bin_dir: impl AsRef<Path>,
        log_path: impl AsRef<Path>,
        captured_body: impl AsRef<Path>,
        create_succeeds: bool,
        comment_succeeds: bool,
    ) {
        use std::os::unix::fs::PermissionsExt;

        fs::create_dir_all(bin_dir.as_ref()).unwrap_or_else(|e| panic!("{e}"));
        let script_path = bin_dir.as_ref().join("gh");
        let create_exit_code = i32::from(!create_succeeds);
        let comment_exit_code = i32::from(!comment_succeeds);
        let stdout = if create_succeeds {
            "https://github.com/owner/repo/issues/123"
        } else {
            ""
        };
        let script = format!(
            "#!/bin/sh\n\
printf '%s\\n' \"$*\" >> '{log}'\n\
if [ \"$1\" = 'issue' ] && [ \"$2\" = 'comment' ]; then\n\
  exit {comment_exit_code}\n\
fi\n\
body_file=''\n\
prev=''\n\
for arg in \"$@\"; do\n\
  if [ \"$prev\" = '--body-file' ]; then body_file=\"$arg\"; fi\n\
  prev=\"$arg\"\n\
done\n\
if [ -n \"$body_file\" ]; then cp \"$body_file\" '{body}'; fi\n\
printf '%s\\n' '{stdout}'\n\
exit {create_exit_code}\n",
            log = log_path.as_ref().display(),
            body = captured_body.as_ref().display(),
            stdout = stdout,
            create_exit_code = create_exit_code,
            comment_exit_code = comment_exit_code,
        );
        fs::write(&script_path, script).unwrap_or_else(|e| panic!("{e}"));
        let mut permissions = fs::metadata(&script_path)
            .unwrap_or_else(|e| panic!("{e}"))
            .permissions();
        permissions.set_mode(0o755);
        fs::set_permissions(script_path, permissions).unwrap_or_else(|e| panic!("{e}"));
    }
}