thirdshift 0.35.1

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
//! Format machine-wide Command observations.

pub(crate) mod fleet;
mod inbox;
pub mod inspect;
mod target;
mod text;
pub(crate) mod time;
mod watching;
pub(crate) use inbox::validate_remote;
pub(crate) use inbox::{Archive, ArchivePage};
pub(crate) use inbox::{Inbox, Row, issue_url, subject, subject_link_matches};
pub(crate) use target::GitHubTarget;
pub(crate) use watching::{Process, watching};

use anyhow::Result;
use chrono::Local;
use serde::Serialize;

use super::command_record::CommandRecord;
use super::pass_starts::PassStart;
use super::reading::{Command, Group, IdlePass, InboxItem, Snapshot};
use crate::config::UserConfig;
use crate::issue::IssueUrl;

#[derive(Serialize)]
struct Status<'a> {
    version: u32,
    hostname: String,
    active_runs: usize,
    commands: Vec<InboxItem<'a>>,
    idle_passes: &'a [IdlePass],
    pass_starts: &'a [PassStart],
    github_quota_wait: Option<String>,
    /// Every route a Command with no Harness flags would take on this
    /// machine is unavailable by Plan usage, so scheduled Passes skip.
    plan_usage_banner: Option<String>,
    /// How old the Inbox's kept GitHub answer is, in seconds. `None` where
    /// no answer is kept: with no ready pull requests to read, or before
    /// the first read.
    github_answer_age_seconds: Option<u64>,
    github_last_answered_at: Option<String>,
    github_failure: Option<&'a str>,
}

/// One captured read, rendered by the CLI, Console page or Console API.
pub(crate) struct Read {
    snapshot: Snapshot,
    kept: super::github::Kept,
    now: chrono::DateTime<Local>,
}

impl Read {
    pub fn capture(config: &UserConfig, refresh: bool) -> Result<Self> {
        let now = Local::now();
        let snapshot = Snapshot::for_user(config, now)?;
        let kept = if refresh {
            super::github::refresh(&snapshot, config, super::github::FRESH_FOR)?
        } else {
            super::github::load(&config.logs_dir)
        };
        Ok(Self {
            snapshot,
            kept,
            now,
        })
    }

    fn status(&self, config: &UserConfig, all: bool) -> Status<'_> {
        Status {
            version: fleet::VERSION,
            hostname: crate::host::name().unwrap_or_else(|| "unknown".into()),
            active_runs: self.snapshot.active_runs(),
            commands: self
                .snapshot
                .evaluate_inbox(config.inbox_days, &self.kept)
                .into_rows(all),
            idle_passes: &self.snapshot.idle_passes,
            pass_starts: &self.snapshot.pass_starts,
            github_quota_wait: self.kept.quota_wait(),
            plan_usage_banner: crate::plan_usage::banner(config),
            github_answer_age_seconds: self.kept.age.map(|age| age.as_secs()),
            github_last_answered_at: self.kept.last_answered_at(),
            github_failure: self.kept.failure.as_deref(),
        }
    }

    pub fn json(&self, config: &UserConfig, all: bool) -> Result<serde_json::Value> {
        Ok(serde_json::to_value(self.document(config, all)?)?)
    }

    pub fn document(&self, config: &UserConfig, all: bool) -> Result<fleet::Document> {
        fleet::local(
            serde_json::to_value(self.status(config, all))?,
            self.now.into(),
        )
    }

    pub fn inbox(&self, config: &UserConfig) -> Result<Inbox> {
        inbox::from_read(config, &self.snapshot, &self.kept, self.now)
    }

    pub fn archive(
        &self,
        config: &UserConfig,
        page: ArchivePage,
        outcome: &str,
        repository: &str,
        commands: Option<&[String]>,
    ) -> Result<Archive> {
        inbox::archive_from_read(
            config,
            page,
            &inbox::Chosen {
                outcome,
                repository,
                commands,
            },
            &self.snapshot,
            self.now,
        )
    }

    pub fn times(&self, hours: f64, by_repository: bool) -> Result<time::Views> {
        time::from_read(&self.snapshot, self.now, hours, by_repository)
    }
}

fn print_command_line(
    facts: &CommandRecord,
    stage: &str,
    account: Option<&str>,
    state_word: &str,
    indent: &str,
    machine: Option<&str>,
) {
    let mut subject = if let Some(name) = facts.process_label() {
        match &facts.issue {
            Some(issue) => format!(
                "{name} {}#{} {}",
                facts.repository,
                issue.number,
                issue.title.as_deref().unwrap_or("(title unavailable)")
            ),
            None => format!("{name} on {}", facts.repository),
        }
    } else {
        match &facts.issue {
            Some(issue) => format!(
                "{}#{} {}",
                facts.repository,
                issue.number,
                issue.title.as_deref().unwrap_or("(title unavailable)")
            ),
            None => format!("{} on {}", facts.name, facts.repository),
        }
    };
    if let Some(pull_request) = &facts.pull_request {
        subject.push_str(&format!(" · {pull_request}"));
    }
    if let Some(release) =
        inbox::command_release_link(&facts.kind, facts.release_url.as_deref(), &facts.repository)
    {
        subject.push_str(&format!(" · {}", release.url));
    }
    if let Some(account) = account {
        subject.push_str(&format!(" · [{account}]"));
    }
    let tag = machine
        .map(|machine| format!("[{machine}] "))
        .unwrap_or_default();
    println!(
        "{indent}{tag}{} {subject} · {} · {} · {} · {} · {stage}",
        super::display_name(&facts.kind),
        state_word,
        facts.harness,
        facts.model.as_deref().unwrap_or("default Model"),
        facts.effort.as_deref().unwrap_or("default Effort")
    );
}

pub(super) fn print_pause(facts: &super::command_record::CommandRecord, indent: &str) {
    if facts.outcome.as_deref() == Some("paused") {
        if let Some(cause) = &facts.cause {
            println!("{indent}  {cause}");
        }
        if let Some(command) = &facts.resume_command {
            println!("{indent}  Resume: {command}");
        }
    }
}

pub(super) fn print_history(command: &super::reading::HistoricalCommand) {
    if let Some(account) = &command.account {
        print!("[{account}] ");
    }
    let issue = command
        .issue
        .as_ref()
        .map(|issue| format!("#{}", issue.number))
        .unwrap_or_default();
    println!(
        "{}{issue} {} · {} → {} · {}",
        command.repository,
        super::display_name(&command.kind),
        command.started_at,
        command.ended_at.as_deref().unwrap_or("unknown end"),
        command.outcome.as_deref().unwrap_or("unknown outcome")
    );
}

pub fn show(json: bool, all: bool, machine: Option<&str>, local_only: bool) -> Result<()> {
    let config = UserConfig::load()?;
    let waiting = config.effective_waiting_line_interval();
    if waiting != config.waiting_line_interval {
        eprintln!(
            "thirdshift: warning: logs.waiting_line_minutes must be less than inbox.silent_minutes; using half the silent time ({} sec) for waiting lines",
            waiting.as_secs()
        );
    }
    let read = Read::capture(&config, true)?;
    for account in &read.snapshot.unavailable_accounts {
        eprintln!("thirdshift: account {account}: logs unavailable or unreadable");
    }
    let status = read.status(&config, all);
    let local = fleet::local(serde_json::to_value(&status)?, read.now.into())?;
    let document = if local_only {
        local
    } else {
        fleet::fetch_and_merge(&config, local, machine, all)?
    };
    let include_local = machine.is_none_or(|machine| machine == status.hostname);
    let tags = document.machines.len() > 1 || !include_local;
    if json {
        println!("{}", serde_json::to_string_pretty(&document)?);
    } else {
        println!("{}", status.hostname);
        println!("{}", active_runs_text(document.active_runs));
        if tags {
            for machine in &document.machines {
                let reachability = serde_json::to_value(&machine.reachability)?;
                println!(
                    "{}: {} · {}{}",
                    machine.name,
                    active_runs_text(machine.active_runs),
                    reachability.as_str().unwrap(),
                    machine
                        .error
                        .as_ref()
                        .map(|error| format!(" · {error}"))
                        .unwrap_or_default()
                );
            }
        }
        if include_local && let Some(warning) = read.kept.warning() {
            println!("Warning: {warning}");
        }
        let rows: Vec<_> = document
            .commands
            .iter()
            .map(text::Row::read)
            .collect::<Result<_>>()?;
        for group in Group::ORDER {
            let items: Vec<_> = rows.iter().filter(|row| row.group == group).collect();
            let references: Vec<_> = rows
                .iter()
                .filter(|row| {
                    group == Group::Landing && row.landing && row.group == Group::NeedsYou
                })
                .collect();
            if items.is_empty() && references.is_empty() {
                continue;
            }
            println!("{}:", group.title());
            for item in items {
                item.print(tags);
            }
            for item in references {
                item.print_reference(tags);
            }
        }
        for pass in status.idle_passes.iter().filter(|_| include_local) {
            println!("{}", pass.line());
        }
        for pass in status.pass_starts.iter().filter(|_| include_local) {
            println!("{}", pass.line());
        }
        if include_local && let Some(wait) = status.github_quota_wait {
            println!("{wait}");
        }
        if include_local && let Some(banner) = status.plan_usage_banner {
            println!("{banner}");
        }
    }
    Ok(())
}

/// The Inbox's total of outer Command trees with live work, in every group.
pub(crate) fn active_runs_text(count: usize) -> String {
    format!("{count} active run{}", if count == 1 { "" } else { "s" })
}

pub(super) fn stage_text(command: &Command) -> String {
    stage_details(
        command.record.outcome.as_deref(),
        command.state,
        command.stage.as_ref(),
        command.health.as_ref(),
        &command.record.waiting_for,
    )
}

fn stage_details(
    outcome: Option<&str>,
    state: &str,
    stage: Option<&super::reading::CurrentStage>,
    health: Option<&super::reading::Health>,
    waiting_for: &[String],
) -> String {
    if let Some(outcome) = outcome {
        return outcome.to_owned();
    }
    let mut text = stage.map_or_else(
        || {
            if state == "died" {
                "died before first stage".into()
            } else {
                "starting".into()
            }
        },
        |stage| {
            if state == "died" {
                format!("died at {}", super::display_name(&stage.name))
            } else {
                format!(
                    "{} · {}",
                    super::display_name(&stage.name),
                    stage_time(Some(stage.age_seconds as f64), stage.suspended_seconds)
                )
            }
        },
    );
    if state == "live" && !waiting_for.is_empty() {
        text.push_str(&format!(" · {}", waiting_for.join(", ")));
    }
    if let Some(health) = health.and_then(super::reading::Health::text) {
        text.push_str(&format!(" · {health}"));
    }
    text
}

pub(super) fn print_tickets(facts: &CommandRecord, indent: &str) {
    for ticket in &facts.tickets {
        println!("{indent}{}", ticket_text(ticket, &facts.repository));
    }
}

fn ticket_text(ticket: &super::command_record::TicketRecord, repository: &str) -> String {
    use super::command_record::TicketState;
    let state = match ticket.state {
        TicketState::Running => "running".into(),
        TicketState::Merged => "merged".into(),
        TicketState::Failed => "failed".into(),
        TicketState::NotStarted => "not started".into(),
        TicketState::Waiting => format!(
            "waiting on {}",
            ticket
                .blockers
                .iter()
                .map(|issue| {
                    if IssueUrl::parse(&issue.url)
                        .is_ok_and(|blocker| blocker.repo_slug().eq_ignore_ascii_case(repository))
                    {
                        format!("#{}", issue.number)
                    } else {
                        issue.url.clone()
                    }
                })
                .collect::<Vec<_>>()
                .join(", ")
        ),
    };
    format!("Ticket #{} · {state}", ticket.issue.number)
}

pub(super) fn stage_time(seconds: Option<f64>, suspended_seconds: u64) -> String {
    let mut time = seconds
        .map(|seconds| age(seconds as i64))
        .unwrap_or_else(|| "time unknown".into());
    if suspended_seconds > 0 {
        time.push_str(&format!(" · {} suspended", age(suspended_seconds as i64)));
    }
    time
}

pub(super) fn age(seconds: i64) -> String {
    if seconds < 60 {
        format!("{seconds} sec")
    } else if seconds < 3600 {
        format!("{} min", seconds / 60)
    } else {
        format!("{} hr {} min", seconds / 3600, seconds % 3600 / 60)
    }
}