thirdshift 0.6.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
//! The Run notification: one email when a Run, a Spec run or an Architect run
//! ends, whatever its outcome, through the same checks and the same send as
//! `email-test`.

use std::path::Path;
use std::time::{Duration, Instant};

use anyhow::Result;

use crate::architect;
use crate::config::EmailSettings;
use crate::email::Resend;
use crate::failed_run::FailedRun;
use crate::github;
use crate::host;
use crate::issue::{IssueUrl, Repo};
use crate::progress;
use crate::run::Ended;

/// What a Run or an Architect run asks about its Run notification, by its
/// command or, without `email` or `no-email`, by the User config.
#[derive(Debug, PartialEq, Eq)]
pub enum NotificationAsk {
    /// Send one, to this address, else to `email.to`.
    Send(Option<String>),
    /// Send none.
    Skip,
}

/// A Run notification, checked and waiting for the Run to end.
pub struct RunNotification {
    resend: Resend,
    issue: IssueUrl,
    /// The issue's title, if GitHub gave it when the Run started.
    title: Option<String>,
    started: Instant,
}

impl RunNotification {
    /// The Run notification for a Run on `issue` starting now, sent to `to`,
    /// else to `email.to`. Fails, before any work, with the same checks as
    /// `email-test`: an address is known and `RESEND_API_KEY` is set. Once
    /// they pass, it reads the issue's title now, while someone may be
    /// watching, rather than after the Run, when a hung `gh` could keep the
    /// notification from ever going.
    pub fn new(to: Option<String>, settings: &EmailSettings, issue: &IssueUrl) -> Result<Self> {
        let started = Instant::now();
        let resend = Resend::new(to, settings)?;
        Ok(RunNotification {
            resend,
            issue: issue.clone(),
            // Left out of the subject if GitHub can't be asked; the Run's own
            // preflight reports why.
            title: github::issue_title(issue).ok(),
            started,
        })
    }

    /// Send the notification for the Run that `ended`, with what became of
    /// the Base fix it started or waited on, if any. A failed send is only a
    /// warning: it never changes the Run's outcome.
    pub fn send(self, ended: &Ended) {
        let ending = Ending::of(ended);
        let subject = subject(&self.issue, self.title.as_deref(), ending.outcome);
        send(&self.resend, &subject, self.started, None, &ending);
    }
}

/// An Architect run's Run notification, checked and waiting for the Architect
/// run to end.
pub struct ArchitectNotification {
    resend: Resend,
    /// The repository the Launch directory's `origin` names, if it names one.
    repo: Option<Repo>,
    started: Instant,
}

impl ArchitectNotification {
    /// The Run notification for an Architect run starting now from the Launch
    /// directory, sent to `to`, else to `email.to`. Fails, before any work,
    /// with the checks [`RunNotification::new`] makes.
    pub fn new(to: Option<String>, settings: &EmailSettings) -> Result<Self> {
        let started = Instant::now();
        let resend = Resend::new(to, settings)?;
        Ok(ArchitectNotification {
            resend,
            // Left out of the subject if origin names none; the Architect
            // run's own preflight reports why.
            repo: architect::repo().ok(),
            started,
        })
    }

    /// Send the one notification for the Architect run whose Architecture
    /// review ended as `reviewed` and, if its plan was dispatched, whose Spec
    /// run or Run `dispatched`, with what became of the Base fix that took,
    /// if any. A failed send is only a warning: it never changes the
    /// Architect run's outcome.
    pub fn send(
        self,
        reviewed: &Result<architect::Outcome, FailedRun>,
        dispatched: Option<&Ended>,
    ) {
        let review = match reviewed {
            Ok(outcome) => format!("{}: {}", outcome.review(), outcome.url()),
            Err(failed) => failure_outcome(failed, "failed").to_string(),
        };
        let ending = match (reviewed, dispatched) {
            (_, Some(ended)) => Ending::of(ended),
            (Ok(outcome), None) => Ending {
                outcome: outcome.review(),
                pr_url: None,
                cause: None,
                base_fix: None,
                log: None,
                tickets: &[],
            },
            (Err(failed), None) => Ending {
                outcome: failure_outcome(failed, "review failed"),
                ..Ending::of_failure(failed)
            },
        };
        let lines = ArchitectLines {
            review: &review,
            dispatched: dispatched.map(|_| ending.outcome),
        };
        let subject = architect_subject(self.repo.as_ref(), ending.outcome);
        send(&self.resend, &subject, self.started, Some(lines), &ending);
    }
}

/// How a Run, a Spec run or an Architecture review ended, as a Run
/// notification tells it.
struct Ending<'a> {
    outcome: &'static str,
    pr_url: Option<&'a str>,
    cause: Option<String>,
    /// What became of the Base fix the Run started or waited on, if any.
    base_fix: Option<&'a str>,
    log: Option<&'a Path>,
    /// In a Spec run, a line on each Ticket, as in its summary on stderr.
    tickets: &'a [String],
}

impl<'a> Ending<'a> {
    fn of(ended: &'a Ended) -> Self {
        let base_fix = ended.base_fix.as_deref();
        match &ended.outcome {
            Ok(reached) => Ending {
                outcome: reached.goal.outcome(),
                pr_url: Some(&reached.pr_url),
                cause: None,
                base_fix,
                log: reached.log.as_deref(),
                tickets: &reached.ticket_lines,
            },
            Err(failed) => Ending {
                base_fix,
                ..Ending::of_failure(failed)
            },
        }
    }

    fn of_failure(failed: &'a FailedRun) -> Self {
        Ending {
            outcome: failure_outcome(failed, "failed"),
            pr_url: failed.pr_url.as_deref(),
            cause: (!failed.interrupted).then(|| format!("{:#}", failed.error)),
            base_fix: None,
            log: failed.log.as_deref(),
            tickets: &failed.ticket_lines,
        }
    }
}

/// `interrupted`, or `failure` for a failure that was not an interrupt.
fn failure_outcome(failed: &FailedRun, failure: &'static str) -> &'static str {
    if failed.interrupted {
        "interrupted"
    } else {
        failure
    }
}

/// Send the notification with `subject` for what `started` then and ended as
/// `ending`, in an Architect run with its `architect` lines first. A failed
/// send is only a warning.
fn send(
    resend: &Resend,
    subject: &str,
    started: Instant,
    architect: Option<ArchitectLines>,
    ending: &Ending,
) {
    let host = host::name();
    let body = Body {
        architect,
        pr_url: ending.pr_url,
        cause: ending.cause.as_deref(),
        base_fix: ending.base_fix,
        log: ending.log,
        host: host.as_deref().unwrap_or("unknown host"),
        took: started.elapsed(),
        tickets: ending.tickets,
    };
    if let Err(error) = resend.send(subject, &body.text()) {
        progress::step(format_args!(
            "warning: could not send the Run notification: {error:#}"
        ));
    }
}

/// `[thirdshift] <owner>/<repo>#<n> <title>: <outcome>`, without the title
/// if it isn't known.
fn subject(issue: &IssueUrl, title: Option<&str>, outcome: &str) -> String {
    let title = title.map(|title| format!(" {title}")).unwrap_or_default();
    format!(
        "[thirdshift] {}#{}{title}: {outcome}",
        issue.repo_slug(),
        issue.number
    )
}

/// `[thirdshift] <owner>/<repo> Architect run: <outcome>`, without the
/// repository if it isn't known.
fn architect_subject(repo: Option<&Repo>, outcome: &str) -> String {
    let repo = repo
        .map(|repo| format!(" {}/{}", repo.owner, repo.name))
        .unwrap_or_default();
    format!("[thirdshift]{repo} Architect run: {outcome}")
}

/// What an Architect run's notification says before what a Run's does.
struct ArchitectLines<'a> {
    /// How the Architecture review ended, with the issue it ended on.
    review: &'a str,
    /// How the Spec run or Run the plan was dispatched as ended, if it was.
    dispatched: Option<&'a str>,
}

/// What the notification's plain-text body says.
struct Body<'a> {
    architect: Option<ArchitectLines<'a>>,
    pr_url: Option<&'a str>,
    cause: Option<&'a str>,
    /// What became of the Base fix the Run started or waited on, if any.
    base_fix: Option<&'a str>,
    log: Option<&'a Path>,
    host: &'a str,
    took: Duration,
    /// In a Spec run, a line on each Ticket, as in its summary on stderr.
    tickets: &'a [String],
}

impl Body<'_> {
    fn text(&self) -> String {
        let mut text = String::new();
        if let Some(architect) = &self.architect {
            text += &format!("Review:       {}\n", architect.review);
            if let Some(dispatched) = architect.dispatched {
                text += &format!("Dispatched:   {dispatched}\n");
            }
        }
        if let Some(pr_url) = self.pr_url {
            text += &format!("Pull request: {pr_url}\n");
        }
        if let Some(cause) = self.cause {
            text += &format!("Cause:        {cause}\n");
        }
        if let Some(base_fix) = self.base_fix {
            text += &format!("Base fix:     {base_fix}\n");
        }
        if let Some(log) = self.log {
            text += &format!("Session log:  {}\n", log.display());
        }
        text += &format!("Host:         {}\n", self.host);
        text += &format!("Took:         {}\n", took(self.took));
        if !self.tickets.is_empty() {
            text += "\nTickets:\n";
            for line in self.tickets {
                text += &format!("{line}\n");
            }
        }
        text
    }
}

/// `duration` to the second, as in `1h 2m 3s`, `2m 3s` or `3s`.
fn took(duration: Duration) -> String {
    let seconds = duration.as_secs();
    let (hours, minutes, seconds) = (seconds / 3600, seconds / 60 % 60, seconds % 60);
    if hours > 0 {
        format!("{hours}h {minutes}m {seconds}s")
    } else if minutes > 0 {
        format!("{minutes}m {seconds}s")
    } else {
        format!("{seconds}s")
    }
}

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

    fn issue() -> IssueUrl {
        IssueUrl::parse("https://github.com/acme/widgets/issues/123").unwrap()
    }

    #[test]
    fn the_subject_names_the_issue_its_title_if_known_and_the_outcome() {
        assert_eq!(
            subject(&issue(), Some("Add export button"), "ready for review"),
            "[thirdshift] acme/widgets#123 Add export button: ready for review"
        );
        assert_eq!(
            subject(&issue(), None, "failed"),
            "[thirdshift] acme/widgets#123: failed"
        );
    }

    #[test]
    fn the_body_leaves_out_what_the_run_does_not_have() {
        let body = Body {
            architect: None,
            pr_url: None,
            cause: Some("origin mismatch"),
            base_fix: None,
            log: None,
            host: "droplet-1",
            took: Duration::from_secs(4),
            tickets: &[],
        };
        assert_eq!(
            body.text(),
            "Cause:        origin mismatch\n\
             Host:         droplet-1\n\
             Took:         4s\n"
        );
        let body = Body {
            pr_url: Some("https://github.com/acme/widgets/pull/1"),
            cause: None,
            log: Some(Path::new("/home/me/.thirdshift/logs/x.jsonl")),
            ..body
        };
        assert_eq!(
            body.text(),
            "Pull request: https://github.com/acme/widgets/pull/1\n\
             Session log:  /home/me/.thirdshift/logs/x.jsonl\n\
             Host:         droplet-1\n\
             Took:         4s\n"
        );
    }

    #[test]
    fn the_body_reports_the_base_fix_after_the_cause() {
        let body = Body {
            architect: None,
            pr_url: Some("https://github.com/acme/widgets/pull/1"),
            cause: Some("claude exited 1"),
            base_fix: Some("https://github.com/acme/widgets/issues/8 merged"),
            log: None,
            host: "droplet-1",
            took: Duration::from_secs(4),
            tickets: &[],
        };
        assert_eq!(
            body.text(),
            "Pull request: https://github.com/acme/widgets/pull/1\n\
             Cause:        claude exited 1\n\
             Base fix:     https://github.com/acme/widgets/issues/8 merged\n\
             Host:         droplet-1\n\
             Took:         4s\n"
        );
    }

    #[test]
    fn a_spec_runs_body_ends_with_a_line_per_ticket() {
        let tickets = [
            "#21 failed: claude exited 1".to_string(),
            "#22 blocked by #21".to_string(),
        ];
        let body = Body {
            architect: None,
            pr_url: None,
            cause: Some("Tickets not done: #21, #22"),
            base_fix: None,
            log: None,
            host: "droplet-1",
            took: Duration::from_secs(4),
            tickets: &tickets,
        };
        assert_eq!(
            body.text(),
            "Cause:        Tickets not done: #21, #22\n\
             Host:         droplet-1\n\
             Took:         4s\n\
             \n\
             Tickets:\n\
             #21 failed: claude exited 1\n\
             #22 blocked by #21\n"
        );
    }

    #[test]
    fn an_architect_runs_subject_names_the_repository_if_known_and_the_outcome() {
        let repo = Repo::of_origin("https://github.com/acme/widgets.git").unwrap();
        assert_eq!(
            architect_subject(Some(&repo), "plan published"),
            "[thirdshift] acme/widgets Architect run: plan published"
        );
        assert_eq!(
            architect_subject(None, "review failed"),
            "[thirdshift] Architect run: review failed"
        );
    }

    #[test]
    fn an_architect_runs_body_starts_with_the_review_and_the_dispatched_runs_outcome() {
        let body = Body {
            architect: Some(ArchitectLines {
                review: "plan published: https://github.com/acme/widgets/issues/8",
                dispatched: Some("merged"),
            }),
            pr_url: Some("https://github.com/acme/widgets/pull/1"),
            cause: None,
            base_fix: None,
            log: None,
            host: "droplet-1",
            took: Duration::from_secs(4),
            tickets: &[],
        };
        assert_eq!(
            body.text(),
            "Review:       plan published: https://github.com/acme/widgets/issues/8\n\
             Dispatched:   merged\n\
             Pull request: https://github.com/acme/widgets/pull/1\n\
             Host:         droplet-1\n\
             Took:         4s\n"
        );
        let body = Body {
            architect: Some(ArchitectLines {
                review: "idea filed: https://github.com/acme/widgets/issues/8",
                dispatched: None,
            }),
            pr_url: None,
            ..body
        };
        assert_eq!(
            body.text(),
            "Review:       idea filed: https://github.com/acme/widgets/issues/8\n\
             Host:         droplet-1\n\
             Took:         4s\n"
        );
    }

    #[test]
    fn took_is_to_the_second() {
        for (seconds, text) in [
            (0, "0s"),
            (59, "59s"),
            (60, "1m 0s"),
            (3599, "59m 59s"),
            (3723, "1h 2m 3s"),
        ] {
            assert_eq!(took(Duration::from_secs(seconds)), text);
        }
    }
}