thirdshift 0.32.0

Turn a GitHub issue into a ready-for-review pull request, unattended
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
//! Deterministic facts about unfinished work, shared by every ending renderer.

use std::path::PathBuf;

use crate::harness::Harness;
use crate::harness::interpretation::SessionFailure;

// Shared by rendering and child Run accounting: one owner for the line protocol.
const STOPPED: &str = "Stopped at: ";
const PROGRESS: &str = "Progress: ";
const PRESERVED: &str = "Preserved: ";
const BEFORE_RETRYING: &str = "Before retrying: ";
const RECOVERY: &str = "Recovery: ";
const SECURITY_REVIEW: &str = "Security review will use ";
const LAUNCH: &str = "Run from the Launch directory ";
const CONTINUING: &str = "Continuing reuses ";
const RETRY: &str = "Retry starts work ";
const RETAINED_WORK: &str = "Retained work: ";
const LOCAL_WORK: &str = "work may exist only locally on ";

/// The lifecycle operation underway when a Run stopped.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Stage {
    Implementation,
    Tickets,
    SpecReview,
    SecurityReview,
    Push,
    PullRequest,
    Repair,
    Ci,
    SelfMerge,
    BaseFix,
}

impl Stage {
    /// The Command record stage this one reports in, as the Delivery's stage
    /// table records it; a Base fix wait has none of its own.
    pub fn recorded(self) -> Option<crate::logs::Stage> {
        use crate::logs::Stage as Recorded;
        match self {
            Self::Implementation => Some(Recorded::Implement),
            Self::Tickets => Some(Recorded::Tickets),
            Self::SpecReview => Some(Recorded::SpecReview),
            Self::SecurityReview => Some(Recorded::SecurityReview),
            Self::Push | Self::PullRequest => Some(Recorded::PullRequest),
            Self::Repair => Some(Recorded::Repair),
            Self::Ci => Some(Recorded::CiWatch),
            Self::SelfMerge => Some(Recorded::SelfMerge),
            Self::BaseFix => None,
        }
    }

    fn name(self) -> &'static str {
        match self {
            Self::Implementation => "Implementation",
            Self::Tickets => "Ticket execution",
            Self::SpecReview => "Spec review",
            Self::SecurityReview => "Security review",
            Self::Push => "Push",
            Self::PullRequest => "Pull request readiness",
            Self::Repair => "Repair",
            Self::Ci => "CI watching",
            Self::SelfMerge => "Self-merge",
            Self::BaseFix => "Base fix",
        }
    }
}

/// The preservation operation's result, never inferred from agent prose.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Preservation {
    Remote,
    Local,
    None,
}

/// Where a preserve attempt left the work. A push that fails is local, and
/// `report` receives the failed-ticket-run line.
pub fn preservation_of(
    result: Result<crate::worktree::Preserved, anyhow::Error>,
    report: impl FnOnce(String),
) -> Preservation {
    match result {
        Ok(crate::worktree::Preserved::Pushed) => Preservation::Remote,
        Ok(crate::worktree::Preserved::NoChanges) => Preservation::None,
        Err(problem) => {
            report(format!(
                "could not push the failed ticket run's work, so it may exist only locally: {problem:#}"
            ));
            Preservation::Local
        }
    }
}

/// Public command context, filled after Base branch and effective asks settle.
#[derive(Debug, PartialEq, Eq)]
pub struct Continuation {
    pub command: String,
    pub launch: PathBuf,
    pub base: String,
    pub branch: String,
}

/// Closed/total Tickets from the last lifecycle graph, as the Ticket board
/// reports them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TicketProgress {
    pub landed: usize,
    pub total: usize,
}

/// The facts each layer of a Failed run adds, from the Delivery up to the
/// Run's end; the rules for how each fact changes the lines live here.
#[derive(Debug, PartialEq, Eq)]
pub struct Recovery {
    stage: Stage,
    preservation: Preservation,
    worktree: Option<PathBuf>,
    /// Ticket progress, and whether the Spec review completed,
    /// independently of any later delivery failure.
    tickets: Option<(TicketProgress, bool)>,
    continuation: Option<Continuation>,
    security_review_harness: Option<Harness>,
    /// Factory-reported retention facts from child Runs, including their paths.
    local_child_work: Vec<String>,
    /// The Spec PR changed under the Spec run, so no command resumes it.
    spec_pr_changed: bool,
    fix_run: bool,
    /// The host ran out of disk space, which retrying needs freed first.
    out_of_disk: bool,
}

impl Recovery {
    pub fn new(stage: Stage, preservation: Preservation) -> Self {
        Self {
            stage,
            preservation,
            worktree: None,
            tickets: None,
            continuation: None,
            security_review_harness: None,
            local_child_work: Vec::new(),
            spec_pr_changed: false,
            fix_run: false,
            out_of_disk: false,
        }
    }

    /// The stage its `Stopped at:` line reports, which the Command record keeps.
    pub fn stage(&self) -> Stage {
        self.stage
    }

    /// Record `path` as the worktree that holds work preserved only locally.
    pub fn record_worktree(&mut self, path: PathBuf) {
        self.worktree = Some(path);
    }

    /// Add Ticket `progress`; the final review is complete only past the
    /// Ticket and Spec review stages, and only if `all_accounted`: every
    /// Ticket was accounted for.
    pub fn add_tickets(&mut self, progress: TicketProgress, all_accounted: bool) {
        let reviewed = !matches!(self.stage, Stage::Tickets | Stage::SpecReview) && all_accounted;
        self.tickets = Some((progress, reviewed));
    }

    /// Add the public command `context` that continues or retries the Run.
    /// A **Continuation**, whose Issue branch was already on origin,
    /// `on_origin`, keeps that work there even when nothing more was preserved.
    pub fn add_command_context(&mut self, context: Continuation, on_origin: bool) {
        if self.preservation == Preservation::None && on_origin {
            self.preservation = Preservation::Remote;
        }
        self.continuation = Some(context);
    }

    pub(crate) fn for_fix_run(&mut self) {
        self.fix_run = true;
    }

    /// Add child Runs' retained `work`, after any already added.
    pub fn add_child_work(&mut self, work: impl IntoIterator<Item = String>) {
        self.local_child_work.extend(work);
    }

    /// The Spec PR was closed, merged or retargeted under the Spec run: no
    /// Recovery command resumes its Spec branch.
    pub fn add_spec_pr_changed(&mut self) {
        self.spec_pr_changed = true;
    }

    /// The host ran out of disk space: free some before retrying.
    pub fn add_out_of_disk(&mut self) {
        self.out_of_disk = true;
    }

    /// The Security review's Harness when `security.harness` chose one
    /// different from the Run's; the Recovery command still names the Run's.
    pub fn add_security_review_harness(&mut self, harness: Harness) {
        self.security_review_harness = Some(harness);
    }

    /// Literal lines shared by terminal, Activity and Run notification output.
    pub fn lines(&self) -> Vec<String> {
        let mut lines = vec![format!("{STOPPED}{}", self.stage.name())];
        if let Some((TicketProgress { landed, total }, reviewed)) = self.tickets {
            let review = if reviewed { "complete" } else { "incomplete" };
            lines.push(format!(
                "{PROGRESS}{landed}/{total} Tickets landed; final review {review}"
            ));
        }
        if self.out_of_disk {
            lines.push(format!(
                "{BEFORE_RETRYING}{}",
                crate::failed_run::OUT_OF_DISK
            ));
        }
        let Some(context) = &self.continuation else {
            return lines;
        };
        lines.push(match self.preservation {
            Preservation::Remote => format!("{PRESERVED}remotely on {}", context.branch),
            Preservation::Local => format!(
                "{PRESERVED}{LOCAL_WORK}{} at {}; push was not confirmed",
                context.branch,
                self.worktree
                    .as_deref()
                    .unwrap_or(&context.launch)
                    .display()
            ),
            Preservation::None => format!("{PRESERVED}no work preserved"),
        });
        lines.extend(
            self.local_child_work
                .iter()
                .map(|line| format!("{RETAINED_WORK}{line}")),
        );
        if self.preservation == Preservation::Local || !self.local_child_work.is_empty() {
            lines.push(format!("{BEFORE_RETRYING}inspect and publish the retained work, reconcile with origin without forcing, then free the Issue branch and Worktree acquisition path. Do not discard local work."));
        }
        if self.spec_pr_changed {
            lines.push(format!("{BEFORE_RETRYING}the Spec PR changed under the Spec run, so no Recovery command resumes {} into {}. Decide the Spec's Base branch and Spec branch before starting it again.", context.branch, context.base));
            return lines;
        }
        lines.push(format!("{RECOVERY}{}", context.command));
        if self.fix_run {
            lines.push(format!("{LAUNCH}{} or another clone passing Origin match. The Fix run uses the pull request's Base branch {} and continues its Repair loop.", context.launch.display(), context.base));
            return lines;
        }
        if let Some(harness) = self.security_review_harness {
            lines.push(format!(
                "{SECURITY_REVIEW}{}, chosen by security.harness in the User config.",
                harness.name()
            ));
        }
        lines.push(format!(
            "{LAUNCH}{} with Base branch {} checked out (the command cannot encode the Base branch). Retry when the failure's cause is resolved.",
            context.launch.display(), context.base
        ));
        if self.preservation != Preservation::None {
            lines.push(format!("{CONTINUING}the preserved branch and PR and skips completed Tickets. This starts a new Continuation, not the interrupted agent conversation; review and merge/CI repairs may still be needed."));
        } else {
            lines.push(format!(
                "{RETRY}on the original Issue URL; there is no preserved work to continue."
            ));
        }
        lines
    }

    /// Read only factory-owned retention facts, including those passed through
    /// a Ticket from its Base fix. Agent output never enters this protocol.
    pub fn local_work(line: &str) -> Option<&str> {
        let line = line.strip_prefix(RETAINED_WORK).unwrap_or(line);
        line.strip_prefix(PRESERVED)
            .is_some_and(|value| value.starts_with(LOCAL_WORK))
            .then_some(line)
    }

    /// The Recovery comment for the issue a Run left `agent-failed`, for the
    /// Day shift reading GitHub: the cause, where it stopped, what was
    /// preserved and the machine, without local paths or the continue
    /// command. See [`comment`].
    pub fn comment(&self, cause: &str, pr_url: Option<&str>, machine: Option<&str>) -> String {
        let mut facts = vec![format!("{STOPPED}{}", self.stage.name())];
        if let Some((TicketProgress { landed, total }, reviewed)) = self.tickets {
            let review = if reviewed { "complete" } else { "incomplete" };
            facts.push(format!(
                "{PROGRESS}{landed}/{total} Tickets landed; final review {review}"
            ));
        }
        let branch = self.continuation.as_ref().map(|context| &context.branch);
        let on = machine.unwrap_or("the machine that ran it");
        let mut preserved = match (self.preservation, branch) {
            (Preservation::Remote, Some(branch)) => format!("Issue branch `{branch}` on origin"),
            (Preservation::Local, Some(branch)) => format!(
                "Issue branch `{branch}` may exist only locally on {on}; its push was not confirmed"
            ),
            (Preservation::None, Some(_)) | (_, None) => "no work".to_string(),
        };
        if let Some(pr_url) = pr_url {
            preserved += &format!(", with pull request {pr_url}");
        }
        if !self.local_child_work.is_empty() {
            preserved += &format!("; some child work may exist only locally on {on}");
        }
        facts.push(format!("{PRESERVED}{preserved}"));
        let retry = if self.spec_pr_changed {
            "The Spec PR changed under the Spec run: decide the Spec's Base branch and Spec branch \
             before putting `ready-for-agent` back to retry."
        } else {
            RETRY_BY_LABEL
        };
        render(cause, facts, machine, retry)
    }

    pub fn is_line(line: &str) -> bool {
        [
            STOPPED,
            PROGRESS,
            PRESERVED,
            BEFORE_RETRYING,
            RECOVERY,
            SECURITY_REVIEW,
            LAUNCH,
            CONTINUING,
            RETRY,
            RETAINED_WORK,
        ]
        .iter()
        .any(|prefix| line.starts_with(prefix))
    }
}

/// How the Day shift retries a failed Run from GitHub.
const RETRY_BY_LABEL: &str = "Put `ready-for-agent` back to retry.";

/// Where a Run that failed with no [`Recovery`] stopped: before its work began.
const BEFORE_WORK: &str = "Start, before any work began";

/// The Recovery comment for a Run that failed with `cause` on the Issue
/// branch `branch`, if known: [`Recovery::comment`] when it has a
/// `recovery`, else, since it stopped before its work began, one naming only
/// the Issue branch and its pull request `pr_url` as preserved, if there are
/// any.
pub fn comment(
    recovery: Option<&Recovery>,
    branch: Option<&str>,
    cause: &str,
    pr_url: Option<&str>,
    machine: Option<&str>,
) -> String {
    if let Some(recovery) = recovery {
        return recovery.comment(cause, pr_url, machine);
    }
    let preserved = match (branch, pr_url) {
        (Some(branch), Some(pr_url)) => {
            format!("Issue branch `{branch}`, with pull request {pr_url}")
        }
        (Some(branch), None) => format!("Issue branch `{branch}`, if it reached origin"),
        (None, Some(pr_url)) => format!("pull request {pr_url}"),
        (None, None) => "no work".to_string(),
    };
    let facts = vec![
        format!("{STOPPED}{BEFORE_WORK}"),
        format!("{PRESERVED}{preserved}"),
    ];
    render(cause, facts, machine, RETRY_BY_LABEL)
}

/// `error` as a Recovery comment's cause, built only from factory-owned
/// facts: a failed session's Harness diagnostic, and a Spec run's failed
/// Ticket's relayed cause, are left out, since a session's agent can write
/// them.
pub fn cause(error: &anyhow::Error) -> String {
    error
        .chain()
        .map(|layer| {
            if let Some(failure) = layer.downcast_ref::<SessionFailure>() {
                failure.without_diagnostic()
            } else if let Some(not_done) = layer.downcast_ref::<crate::spec_run::TicketsNotDone>() {
                not_done.in_public()
            } else {
                layer.to_string()
            }
        })
        .collect::<Vec<_>>()
        .join(": ")
}

/// The comment's text: the attribution line, `cause` with local paths taken
/// out, `facts` and the `machine`, then `retry`, how to retry.
fn render(cause: &str, facts: Vec<String>, machine: Option<&str>, retry: &str) -> String {
    let cause = without_local_paths(&cause.split_whitespace().collect::<Vec<_>>().join(" "));
    let mut text = format!(
        "{}\n\nthirdshift's Run on this issue failed, so it waits for the Day shift.\n\n\
         - Cause: {cause}\n",
        crate::github::GENERATED
    );
    for fact in facts {
        text += &format!("- {fact}\n");
    }
    text += &format!("- Machine: {}\n\n{retry}\n", machine.unwrap_or("unknown"));
    text
}

/// `text` with each absolute or home-relative local path in a word replaced
/// by `<local path>`: one opening the word, past any opening quote or
/// bracket, or following `=` or a `:` that does not start `://`, as in
/// `--git-dir=/home/u/x` or `path:/home/u/x`. The path runs to the word's
/// end, less closing punctuation, which is kept. A URL is not a local path.
fn without_local_paths(text: &str) -> String {
    text.split(' ')
        .map(|word| {
            let Some(start) = local_path_start(word) else {
                return word.to_string();
            };
            let rest = &word[start..];
            let path = rest.trim_end_matches([')', ']', '\'', '"', '`', ',', '.', ';', ':']);
            format!("{}<local path>{}", &word[..start], &rest[path.len()..])
        })
        .collect::<Vec<_>>()
        .join(" ")
}

/// Where the first local path in `word` starts, if it has one.
fn local_path_start(word: &str) -> Option<usize> {
    word.char_indices().find_map(|(at, _)| {
        let rest = &word[at..];
        if !(rest.starts_with('/') || rest.starts_with("~/")) {
            return None;
        }
        let before = word[..at].chars().next_back();
        let opens = match before {
            None => true,
            Some('(' | '[' | '\'' | '"' | '`' | '=') => true,
            Some(':') => !rest.starts_with("//"),
            Some(_) => false,
        };
        opens.then_some(at)
    })
}

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

    fn context() -> Continuation {
        Continuation {
            command: "thirdshift https://github.com/acme/widgets/issues/21".into(),
            launch: "/launch".into(),
            base: "main".into(),
            branch: "issue-21".into(),
        }
    }

    fn preserved(recovery: &Recovery) -> String {
        recovery
            .lines()
            .into_iter()
            .find(|line| line.starts_with(PRESERVED))
            .expect("no Preserved line")
    }

    fn has(recovery: &Recovery, prefix: &str) -> bool {
        recovery.lines().iter().any(|line| line.starts_with(prefix))
    }

    #[test]
    fn a_continuation_with_nothing_pushed_reads_preserved_remotely() {
        let mut recovery = Recovery::new(Stage::Implementation, Preservation::None);
        recovery.add_command_context(context(), true);
        assert_eq!(preserved(&recovery), "Preserved: remotely on issue-21");
        assert!(has(&recovery, CONTINUING));
        assert!(!has(&recovery, RETRY));
    }

    #[test]
    fn a_spec_pr_changed_under_the_spec_run_leaves_out_every_command_line() {
        let mut recovery = Recovery::new(Stage::Tickets, Preservation::Remote);
        recovery.add_command_context(context(), true);
        recovery.add_spec_pr_changed();
        assert_eq!(preserved(&recovery), "Preserved: remotely on issue-21");
        assert!(has(&recovery, BEFORE_RETRYING));
        for command in [RECOVERY, LAUNCH, CONTINUING, RETRY] {
            assert!(!has(&recovery, command), "{command}");
        }
    }

    #[test]
    fn a_fresh_run_with_nothing_pushed_reads_no_work_preserved() {
        let mut recovery = Recovery::new(Stage::Implementation, Preservation::None);
        recovery.add_command_context(context(), false);
        assert_eq!(preserved(&recovery), "Preserved: no work preserved");
        assert!(has(&recovery, RETRY));
        assert!(!has(&recovery, CONTINUING));
    }

    #[test]
    fn the_final_review_is_complete_only_past_the_spec_review_with_every_ticket_accounted() {
        let progress = TicketProgress {
            landed: 3,
            total: 3,
        };
        for (stage, all_accounted, review) in [
            (Stage::Tickets, true, "incomplete"),
            (Stage::SpecReview, true, "incomplete"),
            (Stage::Push, false, "incomplete"),
            (Stage::Push, true, "complete"),
            (Stage::Ci, true, "complete"),
        ] {
            let mut recovery = Recovery::new(stage, Preservation::Remote);
            recovery.add_tickets(progress, all_accounted);
            assert_eq!(
                recovery.lines()[1],
                format!("Progress: 3/3 Tickets landed; final review {review}"),
                "{stage:?}, all accounted: {all_accounted}"
            );
        }
    }

    #[test]
    fn retained_work_from_two_layers_is_kept_in_order() {
        let mut recovery = Recovery::new(Stage::Ci, Preservation::Remote);
        recovery.add_command_context(context(), false);
        recovery.add_child_work(["Ticket #22 kept at /kept/22".to_string()]);
        recovery.add_child_work(["Base fix #30 kept at /kept/30".to_string()]);
        let lines = recovery.lines();
        let retained: Vec<_> = lines
            .iter()
            .filter(|line| line.starts_with(RETAINED_WORK))
            .collect();
        assert_eq!(
            retained,
            [
                "Retained work: Ticket #22 kept at /kept/22",
                "Retained work: Base fix #30 kept at /kept/30"
            ]
        );
        assert!(has(&recovery, BEFORE_RETRYING));
    }

    #[test]
    fn local_preservation_names_the_recorded_worktree_or_else_the_launch_directory() {
        let mut recovery = Recovery::new(Stage::Push, Preservation::Local);
        recovery.add_command_context(context(), false);
        assert_eq!(
            preserved(&recovery),
            "Preserved: work may exist only locally on issue-21 at /launch; push was not confirmed"
        );
        recovery.record_worktree("/worktrees/issue-21".into());
        assert_eq!(
            preserved(&recovery),
            "Preserved: work may exist only locally on issue-21 at /worktrees/issue-21; push was not confirmed"
        );
        assert!(has(&recovery, BEFORE_RETRYING));
    }

    #[test]
    fn the_comment_names_the_cause_stop_preserved_branch_and_pull_request_machine_and_retry() {
        let mut recovery = Recovery::new(Stage::Ci, Preservation::Remote);
        recovery.add_command_context(context(), false);
        assert_eq!(
            recovery.comment(
                "CI failed",
                Some("https://github.com/acme/widgets/pull/3"),
                Some("night-host")
            ),
            "This comment was generated by AI.\n\n\
             thirdshift's Run on this issue failed, so it waits for the Day shift.\n\n\
             - Cause: CI failed\n\
             - Stopped at: CI watching\n\
             - Preserved: Issue branch `issue-21` on origin, with pull request \
             https://github.com/acme/widgets/pull/3\n\
             - Machine: night-host\n\n\
             Put `ready-for-agent` back to retry.\n"
        );
    }

    #[test]
    fn the_comment_leaves_out_local_paths_and_the_continue_command() {
        let mut recovery = Recovery::new(Stage::Push, Preservation::Local);
        recovery.add_command_context(context(), false);
        recovery.record_worktree("/worktrees/issue-21".into());
        recovery.add_child_work(["Ticket #22 kept at /kept/22".to_string()]);
        let comment = recovery.comment(
            "could not push (/worktrees/issue-21): see ~/.thirdshift/logs/a.jsonl,\nthen retry",
            None,
            Some("night-host"),
        );
        for local in [
            "/worktrees",
            "/kept",
            "~/",
            "/launch",
            "thirdshift https://",
        ] {
            assert!(!comment.contains(local), "{local}: {comment}");
        }
        assert!(
            comment
                .contains("- Cause: could not push (<local path>): see <local path>, then retry\n"),
            "{comment}"
        );
        assert!(
            comment.contains(
                "- Preserved: Issue branch `issue-21` may exist only locally on night-host; its \
                 push was not confirmed; some child work may exist only locally on night-host\n"
            ),
            "{comment}"
        );
    }

    #[test]
    fn a_comment_without_a_recovery_names_the_branch_and_pull_request_it_has() {
        let comment = comment(
            None,
            Some("issue-21"),
            "could not create the worktree",
            Some("https://github.com/acme/widgets/pull/3"),
            None,
        );
        assert!(
            comment.contains(
                "- Preserved: Issue branch `issue-21`, with pull request \
                 https://github.com/acme/widgets/pull/3\n- Machine: unknown\n"
            ),
            "{comment}"
        );
        assert!(
            comment.contains("- Stopped at: Start, before any work began\n"),
            "{comment}"
        );
    }

    #[test]
    fn a_comment_without_a_recovery_still_says_where_the_run_stopped() {
        let comment = comment(
            None,
            Some("issue-21"),
            "could not create the worktree",
            None,
            None,
        );
        assert!(comment.contains("- Stopped at: "), "{comment}");
    }

    #[test]
    fn a_comment_after_the_spec_pr_changed_says_to_decide_before_retrying() {
        let mut recovery = Recovery::new(Stage::Tickets, Preservation::Remote);
        recovery.add_command_context(context(), false);
        recovery.add_spec_pr_changed();
        let comment = recovery.comment("Spec PR closed", None, Some("night-host"));
        assert!(comment.contains("Spec PR changed"), "{comment}");
    }

    #[test]
    fn the_comment_scrubs_a_path_joined_by_an_equals_sign() {
        let comment = comment(
            None,
            None,
            "git --git-dir=/home/u/repo/.git failed",
            None,
            None,
        );
        assert!(!comment.contains("/home/u"), "{comment}");
    }

    #[test]
    fn the_comment_scrubs_a_path_after_a_colon_but_keeps_urls() {
        let comment = comment(
            None,
            None,
            "path:/home/u/x, see https://github.com/acme/widgets/pull/3",
            None,
            None,
        );
        assert!(
            comment.contains(
                "- Cause: path:<local path>, see https://github.com/acme/widgets/pull/3\n"
            ),
            "{comment}"
        );
    }
}