tix-tracker 0.12.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
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
686
687
688
689
#[allow(clippy::wildcard_imports)]
use super::*;

impl App {
    /// Detect a concurrent write and decide what a finished round trip does
    /// (tix #1510).
    ///
    /// The comparison is on the file's **raw bytes**: anything that rewrote the
    /// file — an agent editing through MCP, another session, a watcher's repair —
    /// leaves different bytes, and at this point nothing has been written yet.
    /// Identical bytes mean the file is the one the editor was handed, so the edit
    /// is committed exactly as it was before #1510 existed.
    pub(in crate::app) fn settle_pending_edit(&mut self, pending: PendingEdit) {
        let disk_path = self.store.issues_dir.join(&pending.filename);
        let edited = match std::fs::read_to_string(&pending.temp) {
            Ok(text) => text,
            Err(e) => {
                self.status_msg = Some(format!("editor: {e}"));
                return;
            }
        };
        // A read failure counts as a change: the bytes cannot be shown to be the
        // ones the editor saw, and assuming "unchanged" would write over a file
        // this process cannot even read.
        let unchanged = std::fs::read(&disk_path)
            .map(|bytes| bytes == pending.snapshot)
            .unwrap_or(false);
        if !unchanged {
            // Nothing is written and the temp copy is deliberately kept: it *is*
            // the editor's version, and the prompt may still write it or reopen it.
            self.mode = Mode::EditConflict {
                filename: pending.filename,
                temp: pending.temp,
                disk_path,
            };
            self.status_msg =
                Some("the issue changed on disk while you were editing it".to_string());
            return;
        }
        let issue = match Issue::parse(&edited) {
            Ok(issue) => issue,
            Err(e) => {
                // The reported bug (tix #1506). The old flow returned the generic
                // `file not valid after edit` from `run_editor` and then deleted
                // the temp copy, destroying the user's work. Now the real
                // diagnostic is classified, nothing is written, the round trip
                // stays in flight, and the retained copy is kept for the repair
                // prompt to reopen.
                let filename = pending.filename.clone();
                let previous = self.previous_issue(&filename);
                let problems =
                    edit_problems::for_parse_error(&error_message(&e), &edited, previous.as_ref());
                let temp = pending.temp.clone();
                self.pending_edit = Some(pending);
                self.enter_repair(&filename, Some(temp), false, problems);
                return;
            }
        };
        let temp = pending.temp.clone();
        self.commit_edited_issue(&pending.filename, issue, "Edited", Some(temp));
    }

    /// Persist an issue an editor round trip produced and settle it (#1506/#1510).
    ///
    /// The one write both entry points and the conflict prompt's override share,
    /// so an override cannot land somewhere an ordinary save would not: it refuses
    /// a titleless issue (no slug, no stable filename), reassigns the segment when
    /// the edit changed the assignee (FR-031), updates the detail pane when it is
    /// showing this issue, rebuilds the board, and reports through
    /// [`App::report_or_repair`].
    ///
    /// `temp` is the retained edited copy when there is one. It is **not** removed
    /// here: `report_or_repair` keeps it if the written file still has problems,
    /// so the repair prompt has something to reopen, and removes it only once the
    /// edit is clean.
    pub(in crate::app) fn commit_edited_issue(
        &mut self,
        original_filename: &str,
        issue: Issue,
        message: &str,
        temp: Option<PathBuf>,
    ) {
        if issue.title.trim().is_empty() {
            let previous = self.previous_issue(original_filename);
            // A titleless issue has no slug and no stable filename. Nothing is
            // written; the prompt offers the pre-edit title back.
            let problems = vec![edit_problems::missing_title(previous.as_ref())];
            self.enter_repair(original_filename, temp, false, problems);
            return;
        }
        // Back up the version this write is about to replace, so even a clean
        // save leaves the previous content recoverable and names where.
        let backup = self.backup_previous_content(original_filename);
        match self.persist_issue(original_filename, issue) {
            Ok(location) => self.report_or_repair(&location, temp, message, backup),
            Err(e) => {
                self.status_msg = Some(format!("editor: {e}"));
            }
        }
    }

    /// Write `issue` over `original_filename`, reassigning the segment when the
    /// edit changed the assignee, and refresh what the shell shows.
    ///
    /// Returns the relative path actually written (the assignee segment may have
    /// changed, FR-031).
    pub(in crate::app) fn persist_issue(
        &mut self,
        original_filename: &str,
        mut issue: Issue,
    ) -> Result<String> {
        issue.bump_updated();
        // FR-031: when the editor assigned the issue, physically move it into the
        // new assignee segment before writing content. An unassigned edit keeps the
        // current file location.
        let mut location = match &issue.assignee {
            Some(a) => self
                .store
                .reassign(original_filename, Some(a))?
                .to_string_lossy()
                .to_string(),
            None => original_filename.to_string(),
        };
        location = self.store.update(&location, &issue)?;
        issue.filename = location.clone();
        if let Some(d) = &mut self.detail
            && (d.issue.filename == original_filename || d.issue.filename == location)
        {
            d.issue = issue;
            d.scroll_offset.set(0);
        }
        let _ = self.refresh_corpus();
        Ok(location)
    }

    /// Lint the written file and either report `message` or enter the repair
    /// prompt (#1506).
    ///
    /// The edit is already on disk here, so a finding is a *report*: the custom
    /// keys the edit added are preserved either way ([`App::report_or_repair`]
    /// never deletes the file). `backup` is the pre-write copy, named in the
    /// status so the previous version stays findable.
    pub(in crate::app) fn report_or_repair(
        &mut self,
        filename: &str,
        temp: Option<PathBuf>,
        message: &str,
        backup: Option<PathBuf>,
    ) {
        match self.classify_file_problems(filename) {
            Ok(problems) if !problems.is_empty() => {
                // The edit is on disk now, so the round trip is over: only the
                // *unwritten* path keeps `pending_edit` in flight.
                self.pending_edit = None;
                self.enter_repair(filename, temp, true, problems);
            }
            Ok(_) => {
                if let Some(temp) = &temp {
                    let _ = std::fs::remove_file(temp);
                }
                // The round trip is resolved: `reedit_repair` arrives here with
                // the repair prompt still up, so the board is set explicitly
                // rather than assumed.
                self.mode = Mode::Board;
                self.pending_edit = None;
                self.status_msg = Some(names_backup(message, backup.as_ref()));
            }
            Err(e) => {
                if let Some(temp) = &temp {
                    let _ = std::fs::remove_file(temp);
                }
                self.mode = Mode::Board;
                self.pending_edit = None;
                self.status_msg = Some(format!("editor: {e}"));
            }
        }
    }

    /// Every problem `tix lint` reports for `filename`, classified.
    pub(in crate::app) fn classify_file_problems(
        &self,
        filename: &str,
    ) -> Result<Vec<EditProblem>> {
        let findings =
            crate::commands::lint::collect_file(&self.store.config, &self.store, filename)?;
        if findings.is_empty() {
            return Ok(Vec::new());
        }
        let previous = self.previous_issue(filename);
        Ok(edit_problems::for_lint_findings(
            &findings,
            previous.as_ref(),
        ))
    }

    /// The issue as it is on disk, used for the pre-edit title and as the
    /// fallback previous version. `None` when it cannot be read or parsed.
    pub(in crate::app) fn previous_issue(&self, filename: &str) -> Option<Issue> {
        let path = self.store.issues_dir.join(filename);
        let contents = std::fs::read_to_string(path).ok()?;
        Issue::parse(&contents).ok()
    }

    /// Write a recoverable copy of `filename`'s current content into the
    /// centralized backup directory (#1581).
    ///
    /// Every write that replaces the on-disk issue from the editor, repair, or
    /// conflict path goes through this first, so a change tix made is always
    /// recoverable. The copy lands in [`crate::backup::dir`] beside the issues
    /// directory (never beside the issue), and the path is returned so the
    /// status line can name it.
    pub(in crate::app) fn backup_previous_content(&self, filename: &str) -> Option<PathBuf> {
        crate::backup::save(&self.store.issues_dir, filename)
    }

    /// Enter the repair prompt with `problems` (#1506).
    ///
    /// Does nothing when there is nothing to report — every caller guards on a
    /// non-empty list, but an empty prompt would be worse than no prompt.
    pub(in crate::app) fn enter_repair(
        &mut self,
        filename: &str,
        temp: Option<PathBuf>,
        written: bool,
        problems: Vec<EditProblem>,
    ) {
        let Some(first) = problems.first() else {
            return;
        };
        let key = problems.iter().find_map(|problem| match problem.fix() {
            Some(EditFix::DeclareCustomAttribute { key }) => Some(key.clone()),
            _ => None,
        });
        let message = first.summary();
        self.mode = Mode::EditRepair {
            filename: filename.to_string(),
            message: message.clone(),
            key,
            problems,
            temp,
            written,
            discard_armed: false,
        };
        self.status_msg = Some(message);
    }

    /// Override the newer on-disk version with the editor's version (#1510).
    ///
    /// The **only** conflict outcome that writes, and it writes the temp copy's
    /// content rather than the on-disk one: the prompt has already said which file
    /// changed and the user chose their own edit. A temp copy that cannot be read
    /// or parsed leaves the prompt in place instead of closing it, so the user
    /// still has the abandon and compare keys.
    pub(in crate::app) fn override_conflicting_edit(
        &mut self,
        filename: &str,
        temp: &std::path::Path,
    ) {
        let edited = match std::fs::read_to_string(temp) {
            Ok(edited) => edited,
            Err(e) => {
                self.status_msg = Some(format!("editor: {e}"));
                return;
            }
        };
        let issue = match Issue::parse(&edited) {
            Ok(issue) => issue,
            Err(e) => {
                // The temp copy cannot be parsed, so nothing can be written over
                // the newer file. The prompt stays up with both versions intact.
                self.status_msg = Some(format!("editor: {e}"));
                return;
            }
        };
        self.mode = Mode::Board;
        // The temp copy is handed to the commit, which keeps it if the written
        // file still has problems and removes it once the edit is clean.
        self.commit_edited_issue(
            filename,
            issue,
            "Overrode the version that changed on disk with your edit",
            Some(temp.to_path_buf()),
        );
    }

    /// Abandon the editor's version and keep the newer on-disk one (#1510).
    ///
    /// The safe default, and the reason `Esc` is bound to it: the temp copy is
    /// removed and nothing is written, so a write that arrived while the editor was
    /// open is never clobbered by a keypress the user did not mean as a decision.
    pub(in crate::app) fn abandon_conflicting_edit(&mut self, temp: &std::path::Path) {
        let _ = std::fs::remove_file(temp);
        self.mode = Mode::Board;
        self.status_msg =
            Some("kept the version that changed on disk; your edit was discarded".to_string());
    }

    /// Re-open the editor on the conflict prompt's temp copy so the user can
    /// compare the two versions (#1510), then land back on the prompt.
    ///
    /// The disk file's bytes are read **before** and **after** the second editor
    /// run, so a change made while the user compares is detected too — that is the
    /// "re-reading the disk state" the prompt promises. It needs the child and the
    /// child needs the terminal, which is why the keypress returns
    /// [`Action::CompareEdit`] instead of doing this where the key is handled.
    /// Nothing is written either way: the editor opens the temp copy, never the
    /// issue file.
    pub fn compare_conflicting_edit(&mut self) -> Result<()> {
        let (filename, temp, disk_path) = match &self.mode {
            Mode::EditConflict {
                filename,
                temp,
                disk_path,
            } => (filename.clone(), temp.clone(), disk_path.clone()),
            _ => return Ok(()),
        };
        let name = editor::resolve_editor(self.store.config.editor.as_deref())?;
        let before = std::fs::read(&disk_path).map_err(TixError::Io)?;
        editor::run_editor(&name, &temp, &self.store.config)?;
        let after = std::fs::read(&disk_path).map_err(TixError::Io)?;
        // Back to the same prompt: a second look is not a decision, and the three
        // choices have to still be there once the user has looked.
        self.mode = Mode::EditConflict {
            filename,
            temp,
            disk_path,
        };
        self.status_msg = Some(if after == before {
            "the issue changed on disk while you were editing it".to_string()
        } else {
            "the issue changed on disk again while you were comparing it".to_string()
        });
        Ok(())
    }

    /// The edit-conflict prompt's keys (tix #1510).
    ///
    /// The arms read the keys' **canonical** events, like every other modal: the
    /// prompt binds `o`/`y` to `confirm` (canonical `y`), `a`/`Esc` to `ignore`
    /// (canonical `Enter`), and `c`/`r` to `reedit` (canonical `r`), so what arrives
    /// here is `y`, `Enter` and `r` whatever chords the keymap names. `Esc`
    /// therefore abandons exactly as the prompt promises, and no key that is not one
    /// of the three does anything.
    pub(in crate::app) fn handle_edit_conflict_key(&mut self, key: KeyEvent) -> Result<Action> {
        let (filename, temp) = match &self.mode {
            Mode::EditConflict { filename, temp, .. } => (filename.clone(), temp.clone()),
            _ => return Ok(Action::None),
        };
        match key.code {
            KeyCode::Char('y') => {
                self.override_conflicting_edit(&filename, &temp);
                Ok(Action::None)
            }
            // The child needs the terminal, so the event loop runs this and not
            // the handler (see `compare_conflicting_edit`).
            KeyCode::Char('r') => Ok(Action::CompareEdit),
            KeyCode::Enter | KeyCode::Esc => {
                self.abandon_conflicting_edit(&temp);
                Ok(Action::None)
            }
            _ => Ok(Action::None),
        }
    }

    /// Declare `key` in `tix.toml`'s `[custom_attributes]` (#1506) — the one fix
    /// the repair prompt applies by writing config rather than the issue, and the
    /// reason the prompt is not just a nag.
    ///
    /// The entry is appended and `tix.toml` is written through
    /// [`Config::save`](crate::config::Config::save), the same atomic temp-file
    /// path the Config mode uses. An entry that is already declared — compared
    /// case-insensitively, the rule [`Config::custom_attributes`] itself applies —
    /// is not appended again: a second `a` on an open warning is an idempotent
    /// re-run, not a duplicate row.
    ///
    /// `key == None` is a finding that is not an undeclared key, so `a` has
    /// nothing to declare and says so rather than writing an entry that would
    /// silence nothing.
    pub(in crate::app) fn declare_custom_attribute(&mut self, key: Option<&str>) {
        let Some(key) = key.map(str::trim).filter(|k| !k.is_empty()) else {
            self.status_msg = Some(
                "nothing to declare: this finding is not an undeclared frontmatter key".into(),
            );
            return;
        };
        let declared = self.store.config.custom_attributes();
        let already_declared = declared.iter().any(|d| d == &key.to_ascii_lowercase());
        if !already_declared {
            self.store
                .config
                .custom_attributes
                .keys
                .push(key.to_string());
        }
        match self
            .store
            .config_path()
            .and_then(|path| self.store.config.save(&path))
        {
            Ok(()) => {
                self.status_msg = Some(format!(
                    "declared `{key}` in [custom_attributes] in tix.toml"
                ));
            }
            Err(e) => {
                // The warning closed either way, so the status line is the only
                // place this can be reported. Roll the in-memory entry back, so
                // it never claims a declaration that is not on disk.
                if !already_declared {
                    self.store.config.custom_attributes.keys.pop();
                }
                self.status_msg = Some(format!("declare `{key}`: {e}"));
            }
        }
    }

    /// The repair prompt's keys (tix #1506).
    ///
    /// The arms read the keys' **canonical** events, like every other modal:
    /// `handle_key` rewrites a bound key to its action's canonical event before
    /// this runs, so `a`/`y` arrive as `y` (`confirm`), `d` as `d`
    /// (`declare_key`), `r` as `r` (`reedit`), `i`/`Esc` as `Enter` (`ignore`),
    /// and `x` as `x` (`discard`).
    ///
    /// `reedit` hands back [`Action::ReeditRepair`] because the child needs the
    /// terminal; everything else is decided here. **No key discards silently**:
    /// `Esc` acknowledges and keeps the copy, and only a second `x` removes it.
    pub(in crate::app) fn handle_edit_repair_key(&mut self, key: KeyEvent) -> Result<Action> {
        match key.code {
            KeyCode::Char('y') => {
                self.apply_repair_fix();
                Ok(Action::None)
            }
            KeyCode::Char('d') => {
                self.declare_repair_key();
                Ok(Action::None)
            }
            KeyCode::Char('r') => Ok(Action::ReeditRepair),
            KeyCode::Char('x') => {
                self.arm_or_discard_repair();
                Ok(Action::None)
            }
            KeyCode::Enter | KeyCode::Esc => {
                self.acknowledge_repair();
                Ok(Action::None)
            }
            _ => Ok(Action::None),
        }
    }

    /// Apply the first fix the prompt proposes (#1506).
    ///
    /// An undeclared key's fix *is* the declaration, so `confirm` keeps #1506's
    /// behaviour there. The fix operates on the retained copy (or the issue file
    /// when the edit is already written) and the result is re-parsed: a fix that
    /// does not make the file valid leaves it untouched and re-reports, and one
    /// that does is written with the previous version backed up.
    pub(in crate::app) fn apply_repair_fix(&mut self) {
        let (filename, temp, problems) = match &self.mode {
            Mode::EditRepair {
                filename,
                temp,
                problems,
                ..
            } => (filename.clone(), temp.clone(), problems.clone()),
            _ => return,
        };
        let Some(problem) = problems.iter().find(|problem| problem.fix().is_some()) else {
            // #1506: `confirm` on a prompt whose problem is the undeclared key is
            // the declaration itself, whether or not the key was carried as a fix.
            if let Mode::EditRepair { key: Some(key), .. } = &self.mode {
                let key = key.clone();
                self.declare_custom_attribute(Some(&key));
                self.mode = Mode::Board;
                self.pending_edit = None;
                return;
            }
            // A finding that is not an undeclared key has nothing to declare, and
            // the wording is the one the old warning used. `confirm` closes the
            // prompt, exactly as the old warning did (the reported problem stays
            // on disk and in `tix lint`; there is nothing to decide here).
            self.status_msg = Some(
                "nothing to declare: this finding is not an undeclared frontmatter key".into(),
            );
            self.mode = Mode::Board;
            self.pending_edit = None;
            return;
        };
        let Some(fix) = problem.fix().cloned() else {
            return;
        };
        if let EditFix::DeclareCustomAttribute { key } = &fix {
            self.declare_custom_attribute(Some(key));
            self.mode = Mode::Board;
            self.pending_edit = None;
            return;
        }
        let source = match &temp {
            Some(temp) => temp.clone(),
            None => self.store.issues_dir.join(&filename),
        };
        let contents = match std::fs::read_to_string(&source) {
            Ok(contents) => contents,
            Err(e) => {
                self.status_msg = Some(format!("editor: {e}"));
                return;
            }
        };
        let Some(fixed) = fix.apply(&contents) else {
            self.status_msg = Some(format!(
                "could not apply `{}`; the file is untouched",
                fix.label()
            ));
            return;
        };
        let label = fix.label();
        match Issue::parse(&fixed) {
            Ok(issue) => {
                let backup = self.backup_previous_content(&filename);
                match self.persist_issue(&filename, issue) {
                    Ok(location) => {
                        if let Some(temp) = &temp {
                            let _ = std::fs::remove_file(temp);
                        }
                        self.pending_edit = None;
                        self.mode = Mode::Board;
                        self.status_msg = Some(names_backup(
                            &format!("applied `{label}` to {location}"),
                            backup.as_ref(),
                        ));
                    }
                    Err(e) => self.status_msg = Some(format!("editor: {e}")),
                }
            }
            Err(e) => {
                // The fix did not make the file valid. Nothing was written — the
                // repaired text only ever existed as a local string — so the
                // retained copy is untouched and the remaining problems are what
                // the prompt now lists.
                let previous = self.previous_issue(&filename);
                let problems =
                    edit_problems::for_parse_error(&error_message(&e), &fixed, previous.as_ref());
                if let Mode::EditRepair {
                    problems: current, ..
                } = &mut self.mode
                {
                    *current = problems;
                }
                self.status_msg = Some(format!(
                    "the fix did not make the file valid: {e}; the file is untouched"
                ));
            }
        }
    }

    /// Declare the prompt's undeclared key (#1506), or say there is none.
    ///
    /// Closes to the board either way, as the old warning did: the declaration is
    /// what silences the finding, and the custom key is already on disk.
    pub(in crate::app) fn declare_repair_key(&mut self) {
        let key = match &self.mode {
            Mode::EditRepair { key, .. } => key.clone(),
            _ => None,
        };
        self.declare_custom_attribute(key.as_deref());
        self.mode = Mode::Board;
        self.pending_edit = None;
    }

    /// Acknowledge the prompt and **keep** the retained copy (#1506).
    ///
    /// `Esc` lands here, which is why it can never destroy an edit: the worst a
    /// stray key does is leave the copy where the status line names it.
    pub(in crate::app) fn acknowledge_repair(&mut self) {
        let temp = match &self.mode {
            Mode::EditRepair { temp, .. } => temp.clone(),
            _ => None,
        };
        self.mode = Mode::Board;
        self.pending_edit = None;
        self.status_msg = Some(match &temp {
            Some(temp) => format!("kept your edited copy at {}", temp.display()),
            None => "kept your edit".to_string(),
        });
    }

    /// Arm a discard, or perform it on the second press (#1506).
    ///
    /// Two presses because "I saw it" and "throw it away" are two decisions, and
    /// this is the **only** action in the whole flow that removes the retained
    /// copy.
    pub(in crate::app) fn arm_or_discard_repair(&mut self) {
        if let Mode::EditRepair {
            discard_armed,
            temp,
            ..
        } = &mut self.mode
        {
            if !*discard_armed {
                *discard_armed = true;
                self.status_msg = Some(
                    "press the discard key again to remove the retained copy — this cannot be \
                     undone"
                        .to_string(),
                );
                return;
            }
            let temp = temp.clone();
            self.mode = Mode::Board;
            self.pending_edit = None;
            match temp {
                Some(temp) => {
                    let _ = std::fs::remove_file(&temp);
                    self.status_msg = Some(format!("discarded your edit ({})", temp.display()));
                }
                None => {
                    self.status_msg =
                        Some("nothing to discard: the edit is already on disk".to_string())
                }
            }
        }
    }

    /// Re-open the editor on the repair prompt's retained copy (#1506).
    ///
    /// Called from the event loop because the child needs the terminal, exactly
    /// as [`App::compare_conflicting_edit`] is. The edited copy is re-parsed when
    /// it comes back: a valid file is committed (with the previous version backed
    /// up), an invalid one re-enters the same prompt with fresh problems, and
    /// either way the copy survives.
    pub fn reedit_repair(&mut self) -> Result<()> {
        let (filename, temp) = match &self.mode {
            Mode::EditRepair { filename, temp, .. } => (filename.clone(), temp.clone()),
            _ => return Ok(()),
        };
        let name = editor::resolve_editor(self.store.config.editor.as_deref())?;
        // No retained copy means the edit is already on disk (the #1506
        // warn-after-write path): materialise one so the re-edit has a copy to
        // work on and the prompt keeps the guarantee that its copy only goes away
        // by discard.
        let temp = match temp {
            Some(temp) => temp,
            None => {
                let contents = std::fs::read_to_string(self.store.issues_dir.join(&filename))
                    .map_err(TixError::Io)?;
                let temp = std::env::temp_dir().join(format!(
                    "tix-edit-repair-{}-{}.md",
                    std::process::id(),
                    filename.replace('/', "-")
                ));
                std::fs::write(&temp, contents).map_err(TixError::Io)?;
                temp
            }
        };
        editor::run_editor(&name, &temp, &self.store.config)?;
        let edited = std::fs::read_to_string(&temp).map_err(TixError::Io)?;
        match Issue::parse(&edited) {
            Ok(issue) => {
                self.commit_edited_issue(&filename, issue, "Edited", Some(temp));
            }
            Err(e) => {
                let previous = self.previous_issue(&filename);
                let problems =
                    edit_problems::for_parse_error(&error_message(&e), &edited, previous.as_ref());
                let message = problems
                    .first()
                    .map(EditProblem::summary)
                    .unwrap_or_else(|| error_message(&e));
                if let Mode::EditRepair {
                    problems: current,
                    temp: kept,
                    written,
                    discard_armed,
                    ..
                } = &mut self.mode
                {
                    *current = problems;
                    *kept = Some(temp);
                    // The revised copy is not on disk, whatever the prompt said
                    // about the version that was.
                    *written = false;
                    *discard_armed = false;
                }
                self.status_msg = Some(message);
            }
        }
        Ok(())
    }
}