thirdshift 0.36.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
//! Durable Command facts shared by the recorder and status reader.

use std::path::{Path, PathBuf};

use anyhow::{Result, ensure};
use chrono::{DateTime, FixedOffset};
use serde::{Deserialize, Serialize};

use super::Work;
use super::effects::{OnMachine, Outside};
use crate::harness::Choice;
use crate::issue::IssueUrl;

/// A Pass owns its dispatched work in the same process and atomic record.
#[derive(Clone, Serialize, Deserialize)]
pub(super) struct CommandTree {
    #[serde(flatten, deserialize_with = "read_command")]
    pub command: CommandRecord,
    #[serde(default)]
    pub dispatched: Vec<CommandRecord>,
}

fn read_command<'de, D: serde::Deserializer<'de>>(reader: D) -> Result<CommandRecord, D::Error> {
    // With arbitrary_precision, Serde's flattened buffer represents fractional
    // numbers as maps. Value restores them before typed metrics read their f64s.
    let value = serde_json::Value::deserialize(reader)?;
    serde_json::from_value(value).map_err(serde::de::Error::custom)
}

impl CommandTree {
    fn active_dispatch_index(&self) -> Option<usize> {
        self.dispatched
            .iter()
            .rposition(|dispatched| dispatched.outcome.is_none())
    }

    /// Completing a nested dispatch restores the unfinished outer run.
    pub fn active(&mut self) -> &mut CommandRecord {
        match self.active_dispatch_index() {
            Some(index) => &mut self.dispatched[index],
            None => &mut self.command,
        }
    }

    pub fn active_ref(&self) -> &CommandRecord {
        self.active_dispatch_ref().unwrap_or(&self.command)
    }

    pub fn active_dispatch_ref(&self) -> Option<&CommandRecord> {
        let index = self.active_dispatch_index()?;
        Some(&self.dispatched[index])
    }

    pub fn active_dispatch(&mut self) -> Option<&mut CommandRecord> {
        let index = self.active_dispatch_index()?;
        Some(&mut self.dispatched[index])
    }
}

/// A human recheck changes the Verdict, without changing when the Command ran.
/// The Experiment's exclusive lock serializes this with completion and rechecks.
pub(crate) fn experiment_rechecked(log: &Path, id: &str, outcome: &str) -> Result<()> {
    let path = log.with_extension("command.json");
    let bytes = match std::fs::read(&path) {
        Ok(bytes) => bytes,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(error) => return Err(error.into()),
    };
    let mut tree: CommandTree = serde_json::from_slice(&bytes)?;
    ensure!(
        tree.command.kind == "Experiment"
            && tree
                .command
                .experiment
                .as_ref()
                .is_some_and(|experiment| experiment.id == id)
            && tree.command.outcome.is_some(),
        "Command record does not belong to the completed Experiment"
    );
    tree.command.outcome = Some(outcome.into());
    OnMachine.replace_record(&path, &serde_json::to_vec_pretty(&tree)?)
}

#[derive(Clone, Serialize, Deserialize)]
pub(super) struct CommandRecord {
    pub version: u32,
    pub kind: String,
    pub repository: String,
    #[serde(default)]
    pub name: String,
    pub issue: Option<Issue>,
    pub hostname: String,
    pub process_id: u32,
    /// The `thirdshift` release that started this Command. Older records
    /// lack it; readers recover it from their Session traces.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub thirdshift_version: Option<String>,
    /// Reader-only provenance: the version came from a Session trace, not this record.
    #[serde(skip)]
    pub version_recovered: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub started_by: Option<super::Actor>,
    pub process_start: String,
    pub harness: String,
    pub model: Option<String>,
    pub effort: Option<String>,
    pub started_at: String,
    #[serde(default)]
    pub ended_at: Option<String>,
    /// Reader-only provenance: legacy retention estimates are not recorded finishes.
    #[serde(skip)]
    pub end_time_estimated: bool,
    pub stages: Vec<Stage>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quota_wait_until: Option<String>,
    pub session_log: Option<PathBuf>,
    pub outcome: Option<String>,
    #[serde(default)]
    pub run_metrics: Option<super::run_metrics::RunMetrics>,
    pub cause: Option<String>,
    /// The stage a failure ending stopped at, in Command record stage words.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stopped_at: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub failure_category: Option<FailureCategory>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub waiting_for: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<crate::session::limits::Limit>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resume_command: Option<String>,
    /// A Paused Command's Claim put `ready-for-agent` back, so a later
    /// Pickup run retakes its issue: it sits in Done, not Needs you.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub handed_back_for_pickup: bool,
    pub issue_branch: Option<String>,
    /// The selected Base branch for a Fix Pass repairing its CI, not its repair branch.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub base_branch: Option<String>,
    pub pull_request: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub release_url: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pull_request_title: Option<String>,
    #[serde(default)]
    pub parent_record: Option<PathBuf>,
    #[serde(default)]
    pub parent_dispatch: Option<String>,
    #[serde(default)]
    pub tickets: Vec<TicketRecord>,
    /// Local knowledge at completion; the Inbox overlays its kept GitHub answer.
    #[serde(default)]
    pub security_findings_waiting: bool,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub security_findings: Vec<crate::security::RecordedFinding>,
    /// Findings this dispatched Security fix addresses, kept before launch.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub security_fix_findings: Vec<crate::security::RecordedFinding>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub experiment: Option<crate::evals::experiment::Description>,
    /// Process provenance is independent of the run type and Command selector.
    #[serde(flatten)]
    pub process: crate::processes::Identity,
}

/// How a failure ending stopped, decided from its typed error, never from
/// its cause's text. A Command that died never ended, so it has none.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum FailureCategory {
    /// A policy, security or merge hold held its Self-merge.
    Held,
    /// A Spec run ended only waiting on a person or on other work.
    Waiting,
    /// A Harness Session failed: it exited non-zero, by signal, or its turn failed.
    Crashed,
    /// Any other failure of the stage it stopped at.
    StageFailed,
}

impl FailureCategory {
    pub(crate) const ALL: [Self; 4] = [Self::Held, Self::Waiting, Self::Crashed, Self::StageFailed];

    pub(crate) fn name(self) -> &'static str {
        match self {
            Self::Held => "held",
            Self::Waiting => "waiting",
            Self::Crashed => "crashed",
            Self::StageFailed => "stage_failed",
        }
    }
}

#[derive(Clone, Serialize, Deserialize)]
pub(crate) struct Issue {
    pub number: u64,
    pub url: String,
    pub title: Option<String>,
}

impl From<&IssueUrl> for Issue {
    fn from(issue: &IssueUrl) -> Self {
        Self {
            number: issue.number,
            url: issue.url.clone(),
            title: None,
        }
    }
}

#[derive(Clone, Serialize, Deserialize)]
pub(crate) struct TicketRecord {
    pub issue: Issue,
    pub state: TicketState,
    pub blockers: Vec<Issue>,
}

#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum TicketState {
    Running,
    Merged,
    Failed,
    Waiting,
    #[serde(rename = "not started")]
    NotStarted,
}

#[derive(Clone, Serialize, Deserialize)]
pub(super) struct Stage {
    pub name: String,
    pub began_at: String,
    pub session_log: Option<PathBuf>,
    /// The Harness, Model and Effort the stage's latest session ran on: a
    /// Step Plan usage routed runs on another route than the Command's.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub harness: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effort: Option<String>,
    #[serde(default, skip_serializing_if = "is_zero")]
    pub suspended_seconds: u64,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub suspensions: Vec<Suspension>,
}

/// The sampled end of a suspension locates it relative to log activity.
#[derive(Clone, Serialize, Deserialize)]
pub(super) struct Suspension {
    pub resumed_at: DateTime<FixedOffset>,
    pub seconds: u64,
}

impl Stage {
    pub fn suspended_between(
        &self,
        since: DateTime<FixedOffset>,
        until: DateTime<FixedOffset>,
    ) -> u64 {
        // Older aggregate-only records can locate their Suspended time only
        // when the quiet interval covers the whole stage.
        if self.suspensions.is_empty() {
            return DateTime::parse_from_rfc3339(&self.began_at)
                .ok()
                .filter(|began| since <= *began)
                .map_or(0, |_| self.suspended_seconds);
        }
        self.suspensions
            .iter()
            .filter_map(|suspension| {
                let duration =
                    chrono::Duration::try_seconds(i64::try_from(suspension.seconds).ok()?)?;
                let began = suspension.resumed_at.checked_sub_signed(duration)?;
                Some(
                    (suspension.resumed_at.min(until) - began.max(since))
                        .num_seconds()
                        .max(0) as u64,
                )
            })
            .fold(0, u64::saturating_add)
            .min(self.suspended_seconds)
    }
}

fn is_zero(seconds: &u64) -> bool {
    *seconds == 0
}

/// A retained stage interval, optionally extended to an observation of live work.
pub(super) struct StageTime<'a> {
    pub stage: &'a Stage,
    pub began: Option<DateTime<FixedOffset>>,
    pub ended: Option<DateTime<FixedOffset>>,
}

impl StageTime<'_> {
    pub fn seconds(&self) -> Option<f64> {
        let (began, ended) = self.began.zip(self.ended)?;
        let milliseconds = ended.signed_duration_since(began).num_milliseconds();
        (milliseconds >= 0).then_some(milliseconds as f64 / 1000.0)
    }
}

// Keep typed stages, persisted names and display order in one declaration.
macro_rules! stage_names {
    ($($(#[$meta:meta])* $stage:ident => $name:literal,)*) => {
        /// Internal transitions are typed; persisted names stay tolerant of new stages.
        #[derive(Clone, Copy)]
        pub enum StageName {
            $($(#[$meta])* $stage,)*
        }

        impl StageName {
            pub fn name(self) -> &'static str {
                match self {
                    $(Self::$stage => $name,)*
                }
            }

            /// Declaration order, with unfamiliar persisted names after every known stage.
            pub(super) fn order(name: &str) -> usize {
                match name {
                    $($name => Self::$stage as usize,)*
                    _ => usize::MAX,
                }
            }
        }
    };
}

stage_names! {
    ProcessStep => "Process Step",
    Implement => "implement",
    CodeReview => "Code review",
    Resume => "Resume",
    SecurityReview => "Security review",
    PullRequest => "pull request",
    CiWatch => "CI watch",
    Repair => "Repair",
    SelfMerge => "Self-merge",
    Cleanup => "cleanup",
    ArchitectureReview => "Architecture review",
    Tickets => "Tickets",
    SpecReview => "Spec review",
    SecurityAudit => "Security audit",
    SecurityReproduction => "Security reproduction",
    SecurityFixPublishing => "Security fix publishing",
    /// A fixed finding's proof-of-concept recheck against the merged Base
    /// branch, before its private record is closed.
    SecurityCloseCheck => "Security close check",
    WaitingForCommands => "Waiting for Commands",
    ArmBuilds => "Arm builds",
    EvalTasks => "Eval tasks",
    Trials => "Trials",
    Sampling => "sampling",
    Grading => "grading",
    Triage => "Triage",
    ReleaseSummary => "Release summary",
    /// A Pickup run or Security run waiting on the Run it dispatched.
    DispatchedRun => "dispatched Run",
    /// A Pickup run or Security run waiting on the Spec run it dispatched.
    DispatchedSpecRun => "dispatched Spec run",
}

impl StageName {
    /// The stage a pass enters while `work`, the Command it dispatched, runs.
    pub(super) fn dispatched(work: Work<'_>) -> Self {
        match work {
            Work::Starting { .. } => Self::ProcessStep,
            Work::SpecRun(_) => Self::DispatchedSpecRun,
            Work::Run(_)
            | Work::BaseFix(_)
            | Work::PickupRun(_)
            | Work::ArchitectRun(_)
            | Work::SecurityRun(_)
            | Work::ScoringRun(_)
            | Work::ReviewRun(_)
            | Work::FixRun(_)
            | Work::ReleaseRun(_)
            | Work::TriageRun { .. }
            | Work::Experiment(_)
            | Work::Process { .. } => Self::DispatchedRun,
        }
    }

    /// Whether the stage named `name` is a pass's dispatch stage. Such a
    /// stage has no Usual range and is never Silent: the dispatched
    /// Command's own stages carry its health.
    pub(super) fn is_dispatch(name: &str) -> bool {
        [Self::DispatchedRun, Self::DispatchedSpecRun]
            .into_iter()
            .any(|stage| stage.name() == name)
    }

    /// Stages entered by Sessions, as distinct from delivery or dispatch work.
    pub(super) fn is_session(name: &str) -> bool {
        [
            Self::Implement,
            Self::CodeReview,
            Self::Resume,
            Self::Repair,
            Self::SpecReview,
            Self::SecurityReview,
            Self::ArchitectureReview,
            Self::Triage,
            Self::ReleaseSummary,
            Self::SecurityAudit,
            Self::SecurityReproduction,
            Self::SecurityFixPublishing,
        ]
        .into_iter()
        .any(|stage| stage.name() == name)
    }

    pub(super) fn known(name: &str) -> bool {
        Self::order(name) != usize::MAX
    }
}

impl CommandRecord {
    /// The Custom process's own name. An older record with no `process_name`
    /// falls back to the selector in `name`.
    pub(super) fn process_label(&self) -> Option<&str> {
        (self.kind == "Process").then(|| self.process.name.as_deref().unwrap_or(self.name.as_str()))
    }

    /// `Process <name> on <repo>`, or `Process <name> · <repo>#<n>` when the
    /// record names an issue. Status text adds the kind word itself.
    pub(super) fn process_heading(&self) -> Option<String> {
        let name = self.process_label()?;
        Some(match self.issue.as_ref() {
            Some(issue) => format!("Process {name} · {}#{}", self.repository, issue.number),
            None => format!("Process {name} on {}", self.repository),
        })
    }

    /// The next transition closes a stage; only a recorded outcome closes the
    /// final stage. A live caller can supply its single sampled observation time.
    pub fn stage_times(
        &self,
        live_until: Option<DateTime<FixedOffset>>,
    ) -> impl Iterator<Item = StageTime<'_>> {
        self.stages.iter().enumerate().map(move |(index, stage)| {
            let ended = if let Some(next) = self.stages.get(index + 1) {
                DateTime::parse_from_rfc3339(&next.began_at).ok()
            } else if self.outcome.is_some() {
                self.ended_at
                    .as_deref()
                    .and_then(|end| DateTime::parse_from_rfc3339(end).ok())
            } else {
                live_until
            };
            StageTime {
                stage,
                began: DateTime::parse_from_rfc3339(&stage.began_at).ok(),
                ended,
            }
        })
    }

    /// Exact retained Session references, including earlier stages. Callers
    /// decide whether they need a deduplicated inventory.
    pub fn session_references(&self) -> impl Iterator<Item = &PathBuf> {
        self.stages
            .iter()
            .filter_map(|stage| stage.session_log.as_ref())
            .chain(self.session_log.as_ref())
    }

    pub fn finish(
        &mut self,
        account: &crate::run_ending::Account<'_>,
        outside: &mut impl super::effects::Outside,
        ranges: &super::usual_range::UsualRanges,
        unaddressed_findings: Option<crate::pull_request::UnaddressedFindings>,
    ) {
        self.ended_at = Some(outside.now().to_rfc3339());
        self.outcome = Some(account.outcome.into());
        // A Quota wait may already have opened this record. Pre-audit GitHub
        // diagnostics stay on the terminal; the record keeps the fixed cause.
        self.cause = account.pre_audit_failure.map(str::to_owned).or_else(|| {
            account
                .ended
                .as_ref()
                .err()
                .map(|cause| cause.full().to_owned())
        });
        // A plan limit pauses work; it is not a failure to attribute.
        let failure = account
            .ended
            .as_ref()
            .err()
            .filter(|_| account.outcome != "paused");
        self.stopped_at = failure.and_then(|_| {
            account
                .recovery
                .and_then(|recovery| recovery.stage().recorded())
                .map(|stage| stage.name().to_owned())
                .or_else(|| self.stopped_stage().map(str::to_owned))
        });
        self.failure_category = failure.map(|cause| cause.category(account.interrupted));
        if let Some(pr_url) = account.pr_url {
            self.pull_request = Some(pr_url.into());
        }
        if let Some(release_url) = account.release_url {
            self.release_url = Some(release_url.into());
        }
        self.security_findings_waiting = account.security_findings_waiting;
        self.security_findings = account.security_findings.unwrap_or_default().to_vec();
        if matches!(
            self.kind.as_str(),
            "Run"
                | "Spec run"
                | "Base fix"
                | "Review run"
                | "Triage run"
                | "Fix run"
                | "Release run"
        ) {
            self.run_metrics = Some(super::run_metrics::RunMetrics::of(
                self,
                ranges,
                outside,
                unaddressed_findings,
            ));
        }
    }

    pub fn live(&self, outside: &mut impl super::effects::Outside) -> bool {
        self.outcome.is_none()
            && !self.process_start.is_empty()
            && outside.process_start(self.process_id).as_deref() == Some(&self.process_start)
    }

    pub fn new(work: Work<'_>, stamp: &str, harness: &Choice, now: DateTime<FixedOffset>) -> Self {
        let issue = work.issue_url().map(|issue| Issue {
            number: issue.number,
            url: issue.url.clone(),
            // The Ready issue listing named a Pickup run's issue before it started.
            title: match work {
                Work::PickupRun(listed) => Some(listed.title.clone()),
                Work::Starting { .. }
                | Work::Run(_)
                | Work::BaseFix(_)
                | Work::SpecRun(_)
                | Work::ArchitectRun(_)
                | Work::SecurityRun(_)
                | Work::ScoringRun(_)
                | Work::ReviewRun(_)
                | Work::FixRun(_)
                | Work::ReleaseRun(_)
                | Work::TriageRun { .. }
                | Work::Experiment(_)
                | Work::Process { .. } => None,
            },
        });
        let name = match work {
            Work::Starting { command, issue, .. } => match issue {
                Some(issue) => format!("{}#{}", issue.repo_slug(), issue.number),
                None => format!("{}-{stamp}", command.folder()),
            },
            Work::ArchitectRun(_) => format!("architect-{stamp}"),
            Work::SecurityRun(_) => format!("secure-{stamp}"),
            Work::ScoringRun(_) => format!("scoring-{stamp}"),
            Work::ReviewRun(_) => format!("review-{stamp}"),
            Work::FixRun(_) => format!("fix-{stamp}"),
            Work::ReleaseRun(_) => format!("release-{stamp}"),
            Work::TriageRun { .. } => format!("triage-{stamp}"),
            Work::PickupRun(_) => format!("pickup-{stamp}"),
            Work::Experiment(_) => format!("experiment-{stamp}"),
            Work::Process { name, .. } => format!("process-{name}-{stamp}"),
            Work::Run(issue) | Work::BaseFix(issue) | Work::SpecRun(issue) => {
                format!("{}#{}", issue.repo_slug(), issue.number)
            }
        };
        Self {
            version: 2,
            kind: if matches!(work, Work::BaseFix(_)) {
                "Base fix".into()
            } else {
                work.kind().to_string()
            },
            repository: work.repo().slug(),
            name,
            issue,
            hostname: String::new(),
            process_id: std::process::id(),
            thirdshift_version: Some(env!("CARGO_PKG_VERSION").into()),
            version_recovered: false,
            started_by: super::Actor::starting(),
            process_start: String::new(),
            harness: harness.harness.name().into(),
            model: harness.model.clone(),
            effort: harness.effort.clone(),
            started_at: now.to_rfc3339(),
            ended_at: None,
            end_time_estimated: false,
            stages: Vec::new(),
            quota_wait_until: None,
            session_log: None,
            outcome: None,
            run_metrics: None,
            cause: None,
            stopped_at: None,
            failure_category: None,
            waiting_for: Vec::new(),
            limit: None,
            resume_command: None,
            handed_back_for_pickup: false,
            issue_branch: None,
            base_branch: None,
            pull_request: None,
            release_url: None,
            pull_request_title: None,
            parent_record: None,
            parent_dispatch: None,
            tickets: Vec::new(),
            security_findings_waiting: false,
            security_findings: Vec::new(),
            security_fix_findings: Vec::new(),
            experiment: None,
            process: work.process(),
        }
    }

    /// Where a failure stopped when nothing recorded it: the stage entered
    /// last, by its persisted name, known or not. A Worktree dropped while the
    /// failure unwinds enters cleanup after the stage that failed, so trailing
    /// cleanup is passed over unless it is the only stage.
    pub fn stopped_stage(&self) -> Option<&str> {
        let names = || self.stages.iter().rev().map(|stage| stage.name.as_str());
        names()
            .find(|name| *name != StageName::Cleanup.name())
            .or_else(|| names().next())
    }

    /// Unknown stages are deliberately not used to interpret a newer record.
    pub fn current_stage(&self) -> Option<&Stage> {
        self.stages
            .iter()
            .rev()
            .find(|stage| StageName::known(&stage.name))
    }
}