thirdshift 0.15.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
//! Owned Inbox presentation for the Console, from the same observations as status.
use anyhow::Result;
use chrono::{DateTime, Local, Utc};
use std::path::Path;

use super::{age, stage_text, ticket_text};
use crate::config::UserConfig;
use crate::logs::command_record::Issue;
use crate::logs::reading::{Command, Entry, Group, Health, Observation, Snapshot};

pub(crate) struct Inbox {
    /// Outer Command trees with live work, independent of sections and rows.
    pub active_runs: usize,
    pub sections: Vec<Section>,
    pub idle_passes: Vec<String>,
    pub warning: Option<&'static str>,
    pub github_warning: Option<String>,
}

pub(crate) struct Section {
    pub group: &'static str,
    pub title: &'static str,
    pub open: bool,
    pub rows: Vec<Row>,
    pub references: Vec<String>,
}

pub(crate) struct Row {
    pub id: String,
    pub started_ms: i64,
    pub occurred_ms: i64,
    pub live: bool,
    pub logging: bool,
    pub log_growth: String,
    pub selector: String,
    pub logs_url: String,
    pub subject: String,
    /// The issue's `https://` address, which the subject links to.
    pub subject_url: Option<String>,
    pub title: String,
    pub state: String,
    pub now_line: String,
    pub timing: Timing,
    pub count: usize,
    pub cause: String,
    /// Why and when the row left Needs you or Ready for review, empty
    /// while it still waits or never waited.
    pub left: String,
    pub harness: String,
    pub pull_request: String,
    pub tickets: Vec<String>,
    pub children: Vec<Row>,
    pub findings: Vec<crate::security::RecordedFinding>,
    pub sessions: Vec<std::path::PathBuf>,
}

pub(crate) struct Timing {
    pub finish: Option<Finish>,
    pub age: String,
}

pub(crate) struct Finish {
    pub datetime: String,
    pub label: String,
}

impl Timing {
    fn new(live: bool, start: &str, end: Option<&str>, now: DateTime<Local>) -> Self {
        if live {
            return Self {
                finish: None,
                age: elapsed(start, now),
            };
        }
        let finish = end.and_then(|end| {
            DateTime::parse_from_rfc3339(end).ok().map(|time| Finish {
                datetime: end.into(),
                label: time
                    .with_timezone(&Utc)
                    .format("%b %-d, %Y at %H:%M:%S UTC")
                    .to_string(),
            })
        });
        let age = finish.as_ref().map_or_else(
            || "End time unknown".into(),
            |finish| format!("{} ago", elapsed(&finish.datetime, now)),
        );
        Self { finish, age }
    }
}

impl Row {
    pub fn peek_url(&self) -> String {
        super::inspect::url("/peek", &self.selector, None)
    }
    pub fn log_url(&self) -> String {
        super::inspect::url("/log", &self.selector, None)
    }
    pub fn session_url(&self, session: &std::path::Path) -> String {
        super::inspect::url("/log", &self.selector, Some(session))
    }
}

pub(crate) struct Archive {
    pub rows: Vec<Row>,
    pub repositories: Vec<String>,
    pub outcomes: Vec<String>,
}

#[derive(Clone, Copy)]
pub(crate) enum ArchivePage {
    History,
    Security,
}

pub(crate) fn archive(
    config: &UserConfig,
    page: ArchivePage,
    outcome: &str,
    repository: &str,
) -> Result<Archive> {
    let now = Local::now();
    let snapshot = Snapshot::load_with_silence(&config.logs_dir, now, config.silent_interval)?;
    let mut entries: Vec<_> = snapshot
        .entries()
        .iter()
        .filter(|entry| match (page, entry) {
            (ArchivePage::History, Entry::Record(command)) => command.state != "live",
            (ArchivePage::History, Entry::History(_)) => true,
            (ArchivePage::Security, Entry::Record(command)) => {
                command.record.kind == "Security run"
            }
            (ArchivePage::Security, Entry::History(command)) => command.kind == "Security run",
        })
        .collect();
    fn facts(entry: &Entry) -> (&str, &str, &str) {
        match entry {
            Entry::Record(command) => (
                &command.record.repository,
                command.record.outcome.as_deref().unwrap_or(command.state),
                command
                    .record
                    .ended_at
                    .as_deref()
                    .unwrap_or(&command.record.started_at),
            ),
            Entry::History(command) => (
                &command.repository,
                command.outcome.as_deref().unwrap_or(command.state),
                command.ended_at.as_deref().unwrap_or(&command.started_at),
            ),
        }
    }
    entries
        .sort_by_key(|entry| std::cmp::Reverse(DateTime::parse_from_rfc3339(facts(entry).2).ok()));
    let repositories = entries
        .iter()
        .map(|entry| facts(entry).0.to_owned())
        .collect::<std::collections::BTreeSet<_>>()
        .into_iter()
        .collect();
    let outcomes = entries
        .iter()
        .map(|entry| facts(entry).1.to_owned())
        .collect::<std::collections::BTreeSet<_>>()
        .into_iter()
        .collect();
    let rows = entries
        .into_iter()
        .filter(|entry| {
            let (repo, result, _) = facts(entry);
            (repository.is_empty() || repository == repo)
                && (outcome.is_empty() || outcome == result)
        })
        .map(|entry| {
            entry_row(
                match entry {
                    Entry::Record(command) => Observation::Record(command),
                    Entry::History(command) => Observation::History(command),
                },
                now,
                &config.logs_dir,
            )
        })
        .collect::<Result<_>>()?;
    Ok(Archive {
        rows,
        repositories,
        outcomes,
    })
}

fn entry_row(entry: Observation<'_>, now: DateTime<Local>, root: &std::path::Path) -> Result<Row> {
    match entry {
        Observation::Record(command) => row(command, now, None, root),
        Observation::History(command) => {
            let (subject, title) =
                subject(&command.repository, &command.kind, command.issue.as_ref());
            Ok(Row {
                id: identity(&format!(
                    "history:{}:{}:{}",
                    command.repository, command.kind, command.started_at
                )),
                started_ms: timestamp(&command.started_at),
                occurred_ms: timestamp(command.ended_at.as_deref().unwrap_or(&command.started_at)),
                live: false,
                logging: false,
                log_growth: String::new(),
                selector: Observation::History(command).selector().unwrap_or_default(),
                logs_url: command
                    .command_log
                    .as_ref()
                    .map(|path| logs_url(path, root))
                    .unwrap_or_else(|| "/?page=logs".into()),
                subject,
                subject_url: issue_url(command.issue.as_ref()),
                title,
                state: command.state.into(),
                now_line: command
                    .outcome
                    .clone()
                    .unwrap_or_else(|| "unknown outcome".into()),
                timing: Timing::new(false, &command.started_at, command.ended_at.as_deref(), now),
                count: 1,
                cause: String::new(),
                left: String::new(),
                harness: String::new(),
                pull_request: String::new(),
                tickets: Vec::new(),
                children: Vec::new(),
                findings: Vec::new(),
                sessions: Observation::History(command).sessions()?,
            })
        }
    }
}

pub(crate) fn inbox(config: &UserConfig) -> Result<Inbox> {
    let now = Local::now();
    let snapshot = Snapshot::load_with_silence(&config.logs_dir, now, config.silent_interval)?;
    // The Console shows the same groups as `status` by reading the same
    // kept answer. The Console's background reader refreshes it independently
    // of requests; status reads GitHub only when that answer is too old.
    let kept = crate::logs::github::load(&config.logs_dir);
    let items = snapshot.inbox(false, config.inbox_days, &kept);
    let listed: std::collections::BTreeSet<_> = items
        .iter()
        .filter_map(|item| item.command.selector())
        .collect();
    let sections = Group::ORDER
        .into_iter()
        .filter(|group| *group != Group::History)
        .map(|group| {
            let rows = items
                .iter()
                .filter(|item| item.group == group)
                .map(|item| {
                    let mut row = entry_row(item.command, now, &config.logs_dir)?;
                    // Ready dispatched Runs have their own Inbox row, in
                    // whichever group they reached. Preserve the full tree in
                    // history/show without duplicating DOM IDs.
                    row.children
                        .retain(|child| !listed.contains(&child.selector));
                    row.state = item.state_word().into();
                    row.count = item.count;
                    row.cause = item.cause().unwrap_or_default().into();
                    row.left = item
                        .dismissal
                        .as_ref()
                        .map(|dismissal| dismissal.line())
                        .into_iter()
                        .chain(item.left_line())
                        .collect::<Vec<_>>()
                        .join("; ");
                    Ok(row)
                })
                .collect::<Result<_>>()?;
            let references = items
                .iter()
                .filter(|item| {
                    group == Group::Landing && item.landing && item.group == Group::NeedsYou
                })
                .filter_map(|item| {
                    let Observation::Record(command) = item.command else {
                        return None;
                    };
                    let (subject, _) = subject(
                        &command.record.repository,
                        &command.record.name,
                        command.record.issue.as_ref(),
                    );
                    Some(format!(
                        "{subject} · {} · see Needs you",
                        item.needs_you_kind.expect("Needs you has a kind").title()
                    ))
                })
                .collect();
            Ok(Section {
                group: match group {
                    Group::NeedsYou => "needs you",
                    Group::ReadyForReview => "ready for review",
                    Group::Landing => "landing",
                    Group::Working => "working",
                    Group::Done => "done",
                    Group::Resolved => "resolved",
                    Group::History => unreachable!(),
                },
                title: group.title(),
                open: group == Group::NeedsYou,
                rows,
                references,
            })
        })
        .collect::<Result<_>>()?;
    Ok(Inbox {
        active_runs: snapshot.active_runs(),
        sections,
        github_warning: kept.warning(),
        idle_passes: snapshot.idle_passes.iter().map(|pass| format!("{} idle on {}: {}", pass.kind, pass.repository, pass.reason)).collect(),
        warning: (config.effective_waiting_line_interval() != config.waiting_line_interval).then_some(
            "logs.waiting_line_minutes must be less than inbox.silent_minutes; using half the silent time for waiting lines"),
    })
}

fn subject(repository: &str, name: &str, issue: Option<&Issue>) -> (String, String) {
    match issue {
        Some(issue) => (
            format!("{repository}#{}", issue.number),
            issue
                .title
                .clone()
                .unwrap_or_else(|| "(title unavailable)".into()),
        ),
        None => (
            format!("{} on {repository}", crate::logs::display_name(name)),
            String::new(),
        ),
    }
}

fn issue_url(issue: Option<&Issue>) -> Option<String> {
    issue
        .map(|issue| issue.url.clone())
        .filter(|url| url.starts_with("https://"))
}

fn row(
    command: &Command,
    now: DateTime<Local>,
    outer_log: Option<&Path>,
    root: &Path,
) -> Result<Row> {
    let facts = &command.record;
    let log = outer_log.unwrap_or(&command.command_log);
    let live = command.state == "live";
    let (subject, title) = subject(&facts.repository, &facts.name, facts.issue.as_ref());
    Ok(Row {
        // A Pass's dispatched Runs share its storage path. Their immutable
        // Command facts distinguish them without tying identity to ordering.
        id: identity(&format!(
            "{}\0{}\0{}\0{}\0{}",
            command.record_path.to_string_lossy(),
            facts.kind,
            facts.name,
            facts.issue.as_ref().map_or("", |issue| issue.url.as_str()),
            facts.started_at
        )),
        started_ms: timestamp(&facts.started_at),
        occurred_ms: timestamp(facts.ended_at.as_deref().unwrap_or(&facts.started_at)),
        live,
        logging: live && !matches!(command.health, Some(Health::Silent { .. })),
        log_growth: format!(
            "{}:{}",
            log_length(Some(log)),
            log_length(
                facts
                    .session_log
                    .as_deref()
                    .map(crate::logs::session::path)
                    .as_deref()
            )
        ),
        selector: Observation::Record(command).selector().unwrap_or_default(),
        logs_url: logs_url(&command.record_path, root),
        subject,
        subject_url: issue_url(facts.issue.as_ref()),
        title,
        state: command.state.into(),
        now_line: stage_text(command),
        timing: Timing::new(
            live,
            &facts.started_at,
            facts
                .ended_at
                .as_deref()
                .filter(|_| !facts.end_time_estimated),
            now,
        ),
        count: 1,
        cause: facts.cause.clone().unwrap_or_default(),
        left: String::new(),
        harness: format!(
            "{} · {} · {}",
            facts.harness,
            facts.model.as_deref().unwrap_or("default Model"),
            facts.effort.as_deref().unwrap_or("default Effort")
        ),
        pull_request: facts.pull_request.clone().unwrap_or_default(),
        tickets: facts
            .tickets
            .iter()
            .map(|ticket| ticket_text(ticket, &facts.repository))
            .collect(),
        children: command
            .dispatched
            .iter()
            .chain(&command.children)
            .map(|child| row(child, now, Some(log), root))
            .collect::<Result<_>>()?,
        findings: facts.security_findings.clone(),
        sessions: command.sessions()?,
    })
}

fn logs_url(path: &std::path::Path, root: &std::path::Path) -> String {
    path.strip_prefix(root)
        .map(|path| format!("/logs/command/{}", crate::logs::catalog::id(path)))
        .unwrap_or_else(|_| "/?page=logs".into())
}

fn log_length(path: Option<&Path>) -> u64 {
    path.and_then(|path| std::fs::metadata(path).ok())
        .map_or(0, |file| file.len())
}

fn timestamp(value: &str) -> i64 {
    DateTime::parse_from_rfc3339(value).map_or(0, |time| time.timestamp_millis())
}

fn identity(value: &str) -> String {
    // Encode the exact storage identity: issue numbers and timestamps alone
    // can collide, and DOM IDs cannot contain whitespace.
    let encoded: String = value
        .as_bytes()
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect();
    format!("command-{encoded}")
}

fn elapsed(time: &str, now: DateTime<Local>) -> String {
    DateTime::parse_from_rfc3339(time)
        .map(|time| age(now.signed_duration_since(time).num_seconds().max(0)))
        .unwrap_or_else(|_| "unknown age".into())
}