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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
#[allow(clippy::wildcard_imports)]
use super::super::*;
#[allow(clippy::wildcard_imports)]
use super::helpers::*;
use std::fs;
use tempfile::TempDir;

#[test]
fn editor_return_warns_on_invalid_issue() {
    let (_tmp, mut app) = make_app();
    let _ = app.handle_key(press(KeyCode::Char('n'))).unwrap();
    if let Mode::Form = &app.mode {
        for c in "Lint Warn".chars() {
            let _ = app.handle_key(press(KeyCode::Char(c))).unwrap();
        }
        let _ = app.handle_key(press(KeyCode::Enter)).unwrap();
    }
    let issue = app
        .board
        .get_selected_card()
        .cloned()
        .expect("selected issue");
    let path = app.store.issues_dir.join(&issue.filename);
    let mut text = std::fs::read_to_string(&path).unwrap();
    // Rewrite whatever the form actually wrote, rather than assuming it is
    // `medium`. The form seeds `priority: String::new()`, so the previous
    // `replace("priority: medium", …)` was a no-op, the issue was never made
    // invalid, and the test asserted a warning that had nothing to warn
    // about. It passed for the wrong reason and would have kept passing after
    // the form changed again.
    let before = text.clone();
    text = text
        .lines()
        .map(|l| {
            if l.starts_with("priority:") {
                "priority: strange"
            } else {
                l
            }
        })
        .collect::<Vec<_>>()
        .join("\n");
    assert_ne!(
        text, before,
        "the fixture must actually change the priority"
    );
    std::fs::write(&path, text).unwrap();

    app.after_editor(&issue.filename);

    assert!(matches!(app.mode, Mode::EditRepair { .. }));
    assert!(
        matches!(&app.mode, Mode::EditRepair { key: None, .. }),
        "an invalid priority is not an undeclared key: {:?}",
        app.mode
    );
}

/// #1506, the "discard" half: the warning is a **report**, so the editor's
/// custom key is on disk before the warning is even computed — and must still
/// be there afterwards.
#[test]
fn editor_return_preserves_an_unknown_key_and_warns_with_it() {
    let (_tmp, mut app) = make_app();
    let dir = app.store.issues_dir.clone();
    write_issue_with_custom_key(&dir, "2026-01-01-a.md", "build_id");

    app.after_editor("2026-01-01-a.md");

    let on_disk = std::fs::read_to_string(dir.join("2026-01-01-a.md")).unwrap();
    assert!(
        on_disk.contains("build_id: \"ci-4471\""),
        "the edit warning must not discard the custom key it warns about:\n{on_disk}"
    );
    match &app.mode {
        Mode::EditRepair { key, .. } => assert_eq!(
            key.as_deref(),
            Some("build_id"),
            "the warning carries the key `a` can declare"
        ),
        other => panic!("expected the edit warning, got {other:?}"),
    }
}

/// #1510 — the editor round trip against a write that lands while the editor
/// is open.
///
/// The editor is a real `/bin/sh` script pointed at by the config's `editor`
/// setting, as the CLI's editor test does: the temp copy, the pre-edit
/// snapshot, and the concurrency this ticket is about all live *outside* the
/// key handler, so only a real round trip can exercise them.
#[cfg(unix)]
mod edit_conflict {
    #[allow(clippy::wildcard_imports)]
    use super::*;
    use std::os::unix::fs::PermissionsExt;

    /// The edit the "user" makes in the editor: the temp copy `$1` goes from the
    /// fixture's `medium` to `high`.
    ///
    /// The pattern is **unquoted** on purpose: the temp copy is not the raw
    /// fixture — it is `Issue::to_file_contents`, tix's own canonical form, which
    /// writes `priority: medium`. The concurrent writer edits the raw issue file
    /// instead, and that one *is* the fixture's quoted text.
    const USER_EDIT: &str = r#"sed -i 's/priority: medium/priority: high/' "$1""#;

    /// Point the app's editor at a fresh `sh` script and return the script's
    /// path. `$1` is the temp copy the round trip hands the editor.
    ///
    /// The script is written by a **child** `sh`, not by this process. A write
    /// descriptor this process holds — even briefly, even if `fs::write` has
    /// already returned — is inherited by any child another test thread forks,
    /// and the next `exec` of that file then fails with `ETXTBSY` ("Text file
    /// busy"). That is a real flake in a parallel test binary, and never holding
    /// the descriptor here is the fix.
    pub(super) fn script(
        app: &mut App,
        tmp: &TempDir,
        name: &str,
        body: &str,
    ) -> std::path::PathBuf {
        use std::io::Write as _;

        let path = tmp.path().join(name);
        let full = format!("#!/bin/sh\n{body}\n");
        let mut writer = std::process::Command::new("sh")
            .args(["-c", "cat > \"$1\"", "sh"])
            .arg(&path)
            .stdin(std::process::Stdio::piped())
            .spawn()
            .expect("spawn the script writer");
        writer
            .stdin
            .take()
            .expect("the writer's stdin is piped")
            .write_all(full.as_bytes())
            .expect("write the script body");
        assert!(
            writer.wait().expect("wait for the script writer").success(),
            "the script writer failed"
        );
        fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
        app.store.config.editor = Some(path.to_string_lossy().to_string());
        path
    }

    /// The temp copy issue `number` gets, with any stale file removed first.
    /// Every test in this binary shares one process id, so the issue number is
    /// what keeps two tests off each other's path.
    pub(super) fn temp_for(number: u32) -> std::path::PathBuf {
        let path =
            std::env::temp_dir().join(format!("tix-edit-{}-{number}.md", std::process::id()));
        let _ = fs::remove_file(&path);
        path
    }

    /// The fixture every decision test starts from: an editor that makes the
    /// user's edit *and* a concurrent writer that rewrites the issue file, then
    /// the round trip run to completion. Returns the app already sitting in the
    /// conflict prompt, so the test is about what a decision does.
    fn raced_round_trip(number: u32, name: &str) -> (TempDir, App, std::path::PathBuf) {
        let (tmp, mut app) = make_app();
        let dir = app.store.issues_dir.clone();
        write_issue(&dir, name, number, "Raced", "todo", None);
        let disk = dir.join(name);
        script(
            &mut app,
            &tmp,
            "editor.sh",
            &format!(
                "{USER_EDIT}\nsed -i 's/priority: \"medium\"/priority: \"low\"/' '{}'",
                disk.display()
            ),
        );
        let temp = temp_for(number);
        app.open_editor_round_trip(name).unwrap();
        assert!(
            matches!(app.mode, Mode::EditConflict { .. }),
            "the fixture must actually produce a conflict, got {:?}",
            app.mode
        );
        (tmp, app, temp)
    }

    /// No concurrent write: the bytes are the ones the editor was handed, so
    /// the edit is written and no conflict prompt appears.
    #[test]
    fn an_unchanged_file_writes_normally_and_never_enters_the_conflict_prompt() {
        let (tmp, mut app) = make_app();
        let dir = app.store.issues_dir.clone();
        write_issue(&dir, "2026-01-01-a.md", 1, "A", "todo", None);
        script(&mut app, &tmp, "editor.sh", USER_EDIT);
        let temp = temp_for(1);

        app.open_editor_round_trip("2026-01-01-a.md").unwrap();

        assert!(
            matches!(app.mode, Mode::Board),
            "an unchanged file is not a conflict: {:?}",
            app.mode
        );
        // The status names the recoverable copy of the previous version
        // (#1506), so it starts with the outcome rather than being it.
        assert!(
            app.status_msg
                .as_deref()
                .is_some_and(|m| m.contains("Edited")),
            "got {:?}",
            app.status_msg
        );
        let on_disk = fs::read_to_string(dir.join("2026-01-01-a.md")).unwrap();
        assert!(
            on_disk.contains("priority: high"),
            "the edit is on disk:\n{on_disk}"
        );
        assert!(!temp.exists(), "the temp copy is cleaned up");
        assert!(app.pending_edit.is_none(), "the round trip is finished");
    }

    /// A concurrent write is detected and **nothing** is written: the newer
    /// file is intact, the editor's version is still the temp copy, and the
    /// prompt carries all three paths it promises.
    #[test]
    fn a_concurrent_write_enters_the_conflict_prompt_and_writes_nothing() {
        let (_tmp, app, temp) = raced_round_trip(2, "2026-01-01-b.md");
        let disk = app.store.issues_dir.join("2026-01-01-b.md");

        match &app.mode {
            Mode::EditConflict {
                filename,
                temp: kept,
                disk_path,
            } => {
                assert_eq!(filename, "2026-01-01-b.md");
                assert_eq!(kept, &temp);
                assert_eq!(disk_path, &disk);
            }
            other => panic!("expected the conflict prompt, got {other:?}"),
        }
        assert!(
            temp.is_file(),
            "the editor's version must survive for the prompt to decide about"
        );
        let on_disk = fs::read_to_string(&disk).unwrap();
        assert!(
            on_disk.contains(r#"priority: "low""#),
            "the concurrent write must not be clobbered:\n{on_disk}"
        );
        assert!(
            !on_disk.contains(r#"priority: "high""#),
            "nothing of the editor's version may be written:\n{on_disk}"
        );
        assert!(
            app.status_msg
                .as_deref()
                .is_some_and(|m| m.contains("changed on disk")),
            "got {:?}",
            app.status_msg
        );
        // The prompt deliberately keeps the editor's copy — that is the point of
        // it — so a test that stops here owns the cleanup.
        let _ = fs::remove_file(&temp);
    }

    /// Override is the one outcome that writes, and it writes the editor's
    /// version — the user has already been told which file changed.
    #[test]
    fn overriding_writes_the_editors_version_and_removes_the_temp_copy() {
        let (_tmp, mut app, temp) = raced_round_trip(3, "2026-01-01-c.md");
        let disk = app.store.issues_dir.join("2026-01-01-c.md");

        let action = app.handle_key(press(KeyCode::Char('o'))).unwrap();

        assert_eq!(action, Action::None);
        assert!(
            matches!(app.mode, Mode::Board),
            "override returns to the board: {:?}",
            app.mode
        );
        assert!(
            app.status_msg
                .as_deref()
                .is_some_and(|m| m.contains("Overrode")),
            "the status says what happened: {:?}",
            app.status_msg
        );
        let on_disk = fs::read_to_string(&disk).unwrap();
        assert!(
            on_disk.contains("priority: high"),
            "the editor's version wins:\n{on_disk}"
        );
        assert!(!temp.exists(), "the temp copy is consumed by the write");
    }

    /// `Esc` is the safe default the prompt promises, and `a` is its spelled
    /// out chord; both keep the newer on-disk version and discard the edit.
    #[test]
    fn abandoning_keeps_the_on_disk_version_and_removes_the_temp_copy() {
        for (number, key) in [(4u32, KeyCode::Esc), (5, KeyCode::Char('a'))] {
            let name = format!("2026-01-01-{number}.md");
            let (_tmp, mut app, temp) = raced_round_trip(number, &name);
            let disk = app.store.issues_dir.join(&name);

            let action = app.handle_key(press(key)).unwrap();

            assert_eq!(action, Action::None, "{key:?}");
            assert!(matches!(app.mode, Mode::Board), "{key:?}: {:?}", app.mode);
            let on_disk = fs::read_to_string(&disk).unwrap();
            assert!(
                on_disk.contains(r#"priority: "low""#),
                "{key:?} keeps the concurrent write:\n{on_disk}"
            );
            assert!(!temp.exists(), "{key:?}: the temp copy is discarded");
            assert!(
                app.status_msg
                    .as_deref()
                    .is_some_and(|m| m.contains("kept the version")),
                "{key:?}: got {:?}",
                app.status_msg
            );
        }
    }

    /// Compare opens the editor again **on the temp copy** and comes back to
    /// the same prompt — the second look is not a decision.
    #[test]
    fn comparing_reopens_the_editor_on_the_temp_copy_and_keeps_it() {
        let (tmp, mut app, temp) = raced_round_trip(6, "2026-01-01-f.md");
        let runs = tmp.path().join("runs.txt");
        // The second look edits the temp copy only and records that it ran.
        script(
            &mut app,
            &tmp,
            "compare.sh",
            &format!(
                "printf 'run\\n' >> '{}'\nprintf 'compared\\n' >> \"$1\"",
                runs.display()
            ),
        );

        let action = app.handle_key(press(KeyCode::Char('c'))).unwrap();
        assert_eq!(
            action,
            Action::CompareEdit,
            "the editor needs the terminal, so the key hands it to the event loop"
        );

        app.compare_conflicting_edit().unwrap();

        assert!(
            matches!(app.mode, Mode::EditConflict { .. }),
            "compare returns to the same prompt: {:?}",
            app.mode
        );
        assert!(temp.is_file(), "the temp copy survives a look");
        let temp_text = fs::read_to_string(&temp).unwrap();
        assert!(
            temp_text.contains("compared"),
            "the editor ran on the temp copy:\n{temp_text}"
        );
        assert_eq!(
            fs::read_to_string(&runs).unwrap().lines().count(),
            1,
            "and it ran exactly once"
        );
        // Same again: the prompt is still open and still holds the copy.
        let _ = fs::remove_file(&temp);
    }

    /// The disk state is re-read around the compare run, so a write that lands
    /// *while* the user compares is detected too.
    #[test]
    fn a_second_change_while_comparing_is_detected_too() {
        let (tmp, mut app, temp) = raced_round_trip(7, "2026-01-01-g.md");
        let disk = app.store.issues_dir.join("2026-01-01-g.md");
        // The concurrent writer is busy too: the compare run rewrites the file
        // again, as `raced_round_trip` left it at `low`.
        script(
            &mut app,
            &tmp,
            "compare.sh",
            &format!(
                "sed -i 's/priority: \"low\"/priority: \"medium\"/' '{}'",
                disk.display()
            ),
        );

        app.compare_conflicting_edit().unwrap();

        assert!(matches!(app.mode, Mode::EditConflict { .. }));
        assert!(
            app.status_msg
                .as_deref()
                .is_some_and(|m| m.contains("again")),
            "the second change must be named: {:?}",
            app.status_msg
        );
        // The prompt is still open, so its copy is the test's to remove.
        let _ = fs::remove_file(&temp);
    }

    /// The rendered rows with runs of whitespace collapsed, so an assertion is
    /// about the text rather than about where the wrap happened to fall: the
    /// modal is three quarters of the *board* area (the mode navigation takes a
    /// column), which is narrower than the terminal. The box-drawing characters
    /// between panes are spaces for the same reason — a wrapped line has a
    /// border in the middle of it in the cell grid.
    fn flattened(text: &str) -> String {
        text.replace(['│', '─', '┌', '┐', '└', '┘'], " ")
            .split_whitespace()
            .collect::<Vec<_>>()
            .join(" ")
    }

    /// The prompt states what happened, names both files, and offers the three
    /// decisions with the chords the effective keymap binds.
    #[test]
    fn the_conflict_prompt_names_its_three_choices_and_both_files() {
        let (_tmp, mut app) = make_app();
        let temp = std::path::PathBuf::from("/tmp/tix-edit-1-42.md");
        let disk_path = std::path::PathBuf::from("/tmp/store/issues/2026-01-01-prompt.md");
        app.mode = Mode::EditConflict {
            filename: "2026-01-01-prompt.md".to_string(),
            temp: temp.clone(),
            disk_path: disk_path.clone(),
        };
        let hints = [
            "overwrite the file with this edit",
            "keep the on-disk version",
            "compare in the editor",
        ];
        let actions = [TuiAction::Confirm, TuiAction::Ignore, TuiAction::Reedit];

        // Roomy: the full chord label and both paths are visible.
        let text = flattened(&cells_to_text(&draw_board(&app, 100, 30), 100, 30));
        assert!(text.contains("Edit Conflict"), "{text}");
        assert!(text.contains("2026-01-01-prompt.md"), "{text}");
        assert!(
            text.contains(&temp.display().to_string()),
            "the editor's copy must be named where the user can open it:\n{text}"
        );
        assert!(
            text.contains(&disk_path.display().to_string()),
            "and so must the newer file:\n{text}"
        );
        for (action, hint) in actions.iter().zip(hints) {
            let chord = app.bindings.label(InputContext::EditConflict, *action);
            assert!(
                text.contains(&chord),
                "the prompt names the effective chord `{chord}`:\n{text}"
            );
            assert!(text.contains(hint), "`{chord}` says what it does:\n{text}");
        }

        // Minimum size: the offers must survive it, or the prompt is a prompt
        // most users never see.
        let text = flattened(&cells_to_text(&draw_board(&app, 80, 24), 80, 24));
        assert!(text.contains("2026-01-01-prompt.md"), "{text}");
        assert!(text.contains(&temp.display().to_string()), "{text}");
        for hint in hints {
            assert!(
                text.contains(hint),
                "`{hint}` must survive an 80x24 terminal:\n{text}"
            );
        }
    }
}

/// The repair prompt (tix #1506): the data-loss bug, the never-discard
/// guarantee, and each classified fix.
#[cfg(unix)]
mod edit_repair {
    use super::edit_conflict::{script, temp_for};
    #[allow(clippy::wildcard_imports)]
    use super::*;
    use crate::edit_problems::EditProblemKind;

    /// An editor script that leaves the temp copy unparsable.
    const BREAK: &str = r#"sed -i 's/priority: medium/priority: [broken/' "$1""#;

    /// An issue with a `## History` section in the middle of its body, where
    /// the parser treats it as prose (the dangerous shape #1506 quotes).
    fn write_issue_with_misplaced_history(dir: &std::path::Path, name: &str, number: u32) {
        let contents = format!(
            "---\nnumber: {number}\ntitle: \"Hist\"\nstatus: \"todo\"\nlabels: []\n\
                 priority: \"medium\"\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\n\
                 Some prose.\n\n## History\n\n\
                 - 2026-01-01T00:00:00Z \u{2014} alice \u{2014} created \u{2014} did it\n\
                 - 2026-01-02T00:00:00Z \u{2014} bob \u{2014} edited \u{2014} then this\n"
        );
        fs::write(dir.join(name), contents).unwrap();
    }

    /// tix #1506: a `[custom_attributes]` added to `tix.toml` while the TUI is
    /// open must be honoured by the very next editor return. Linting against
    /// the startup copy reports a false `unknown_key` for a key the user has
    /// just declared — and the declare-fix would then rewrite `tix.toml` from
    /// that stale copy.
    #[test]
    fn an_editor_return_adopts_a_tix_toml_that_gained_custom_attributes() {
        let (tmp, mut app) = make_app();
        let dir = app.store.issues_dir.clone();
        write_issue(&dir, "2026-01-01-t.md", 31, "T", "todo", None);

        // Declare the key the way a user would: edit `tix.toml` by hand while
        // the session is running.
        let config_path = app.store.config_path().unwrap();
        let mut text = fs::read_to_string(&config_path).unwrap();
        text.push_str("\n[custom_attributes]\nkeys = [\"build_id\"]\n");
        fs::write(&config_path, text).unwrap();

        // The edit introduces exactly that key.
        script(
            &mut app,
            &tmp,
            "add-type.sh",
            r#"cat > "$1" <<'ISSUE'
---
number: 31
title: "T"
status: todo
build_id: story
labels: []
priority: medium
created: 2026-01-01
updated: 2026-01-01
---
ISSUE"#,
        );
        app.open_editor_round_trip("2026-01-01-t.md").unwrap();

        assert!(
            !matches!(app.mode, Mode::EditRepair { .. }),
            "a declared key must not raise the repair prompt, got {:?}",
            app.mode
        );
        let written = fs::read_to_string(dir.join("2026-01-01-t.md")).unwrap();
        assert!(written.contains("build_id: story"), "{written}");
        assert!(
            app.store
                .config
                .custom_attributes()
                .contains(&"build_id".to_string()),
            "the reloaded configuration declares the key"
        );
        assert!(app.config_snapshot.is_some(), "the snapshot advanced");
    }

    /// A `tix.toml` that does not load is reported, the previous configuration
    /// stands, and the snapshot is **not** advanced, so a half-saved file is
    /// retried rather than latched.
    #[test]
    fn a_broken_tix_toml_is_reported_and_the_previous_config_is_kept() {
        let (_tmp, mut app) = make_app();
        let config_path = app.store.config_path().unwrap();
        let before = app.store.config.clone();
        let startup_bytes = app.config_snapshot.clone();
        fs::write(&config_path, "this is not = = toml\n").unwrap();

        assert!(
            !app.reload_config_if_changed(),
            "a broken file is not adopted"
        );
        assert_eq!(
            app.store.config, before,
            "the previous configuration stands"
        );
        assert!(
            app.status_msg
                .as_deref()
                .unwrap_or_default()
                .contains("tix.toml"),
            "and it says so: {:?}",
            app.status_msg
        );
        assert_eq!(
            app.config_snapshot, startup_bytes,
            "the snapshot did not advance, so a fixed file is picked up later"
        );
    }

    /// The reported bug: an edit that makes the file unparsable enters the
    /// prompt with the **real** diagnostic, writes nothing, and leaves the
    /// temp copy in place.
    #[test]
    fn an_unparsable_edit_enters_repair_with_the_real_diagnostic_and_writes_nothing() {
        let (tmp, mut app) = make_app();
        let dir = app.store.issues_dir.clone();
        write_issue(&dir, "2026-01-01-h.md", 21, "H", "todo", None);
        script(&mut app, &tmp, "break.sh", BREAK);
        let temp = temp_for(21);
        let before = fs::read_to_string(dir.join("2026-01-01-h.md")).unwrap();

        app.open_editor_round_trip("2026-01-01-h.md").unwrap();

        let problems = match &app.mode {
            Mode::EditRepair {
                problems,
                temp: kept,
                written,
                ..
            } => {
                assert_eq!(
                    kept.as_deref(),
                    Some(temp.as_path()),
                    "the copy is retained"
                );
                assert!(!written, "nothing has been written yet");
                problems.clone()
            }
            other => panic!("expected the repair prompt, got {other:?}"),
        };
        assert!(temp.is_file(), "the editor's copy must survive");
        assert!(
            problems
                .iter()
                .any(|p| p.kind == EditProblemKind::Unparsable),
            "{problems:?}"
        );
        let summary: String = problems
            .iter()
            .map(|p| p.message.clone())
            .collect::<Vec<_>>()
            .join(" | ");
        assert!(
            !summary.contains("file not valid after edit"),
            "the generic message is the bug: {summary}"
        );
        assert!(
            summary.contains("priority") && summary.contains("invalid type"),
            "the real parse diagnostic must reach the user: {summary}"
        );
        assert_eq!(
            fs::read_to_string(dir.join("2026-01-01-h.md")).unwrap(),
            before,
            "an unparsable edit must write nothing"
        );
        assert!(
            app.pending_edit.is_some(),
            "the round trip stays in flight until a decision is made"
        );
        let _ = fs::remove_file(&temp);
    }

    /// `Esc` acknowledges and keeps the copy; the copy is the one thing a
    /// stray key must not destroy.
    #[test]
    fn escape_acknowledges_and_keeps_the_retained_copy() {
        let (tmp, mut app) = make_app();
        let dir = app.store.issues_dir.clone();
        write_issue(&dir, "2026-01-01-e.md", 22, "E", "todo", None);
        script(&mut app, &tmp, "break.sh", BREAK);
        let temp = temp_for(22);
        app.open_editor_round_trip("2026-01-01-e.md").unwrap();

        let action = app.handle_key(press(KeyCode::Esc)).unwrap();

        assert_eq!(action, Action::None);
        assert!(matches!(app.mode, Mode::Board), "{:?}", app.mode);
        assert!(
            temp.is_file(),
            "Esc acknowledges; it never removes the retained copy"
        );
        let _ = fs::remove_file(&temp);
    }

    /// Discard needs two presses, and it is the **only** thing that removes
    /// the copy.
    #[test]
    fn discard_requires_a_second_press_and_is_the_only_removal() {
        let (tmp, mut app) = make_app();
        let dir = app.store.issues_dir.clone();
        write_issue(&dir, "2026-01-01-d.md", 23, "D", "todo", None);
        script(&mut app, &tmp, "break.sh", BREAK);
        let temp = temp_for(23);
        app.open_editor_round_trip("2026-01-01-d.md").unwrap();

        let _ = app.handle_key(press(KeyCode::Char('x'))).unwrap();
        assert!(
            matches!(
                app.mode,
                Mode::EditRepair {
                    discard_armed: true,
                    ..
                }
            ),
            "{:?}",
            app.mode
        );
        assert!(temp.is_file(), "the first press only arms the discard");
        assert!(
            app.status_msg
                .as_deref()
                .is_some_and(|m| m.contains("again")),
            "got {:?}",
            app.status_msg
        );

        let _ = app.handle_key(press(KeyCode::Char('x'))).unwrap();
        assert!(matches!(app.mode, Mode::Board), "{:?}", app.mode);
        assert!(!temp.exists(), "the confirmed discard removes the copy");
    }

    /// The history fix moves the section to the front and keeps every entry.
    #[test]
    fn the_history_fix_moves_every_entry_to_the_front_and_the_file_parses() {
        let (_tmp, mut app) = make_app();
        let dir = app.store.issues_dir.clone();
        write_issue_with_misplaced_history(&dir, "2026-01-01-hist.md", 24);

        app.after_editor("2026-01-01-hist.md");
        assert!(
            matches!(app.mode, Mode::EditRepair { .. }),
            "{:?}",
            app.mode
        );

        let action = app.handle_key(press(KeyCode::Char('a'))).unwrap();

        assert_eq!(action, Action::None);
        assert!(matches!(app.mode, Mode::Board), "{:?}", app.mode);
        let on_disk = fs::read_to_string(dir.join("2026-01-01-hist.md")).unwrap();
        let issue = Issue::parse(&on_disk).unwrap();
        assert_eq!(
            issue.history.entries.len(),
            2,
            "both entries are recognised after the move:\n{on_disk}"
        );
        for entry in ["did it", "then this"] {
            assert!(
                on_disk.contains(entry),
                "`{entry}` must survive:\n{on_disk}"
            );
        }
        assert!(
            !on_disk.contains("Some prose.\n\n## History"),
            "the section is no longer body text:\n{on_disk}"
        );
        assert!(on_disk.contains("Some prose"), "{on_disk}");
    }

    /// `r` reopens the editor on the retained copy; a valid result is
    /// committed, and the copy is consumed only then.
    #[test]
    fn reedit_reopens_the_editor_on_the_retained_copy_and_commits_a_valid_file() {
        let (tmp, mut app) = make_app();
        let dir = app.store.issues_dir.clone();
        write_issue(&dir, "2026-01-01-r.md", 29, "R", "todo", None);
        script(&mut app, &tmp, "break.sh", BREAK);
        let temp = temp_for(29);
        app.open_editor_round_trip("2026-01-01-r.md").unwrap();
        // The second look repairs what the first broke.
        script(
            &mut app,
            &tmp,
            "fix.sh",
            r#"sed -i 's/priority: \[broken/priority: high/' "$1""#,
        );
        assert_eq!(
            app.handle_key(press(KeyCode::Char('r'))).unwrap(),
            Action::ReeditRepair
        );
        app.reedit_repair().unwrap();

        assert!(matches!(app.mode, Mode::Board), "{:?}", app.mode);
        let on_disk = fs::read_to_string(dir.join("2026-01-01-r.md")).unwrap();
        let issue = Issue::parse(&on_disk).unwrap();
        assert_eq!(issue.priority, crate::model::Priority::High);
        assert!(!temp.exists(), "the copy is consumed once the edit lands");
        assert!(app.pending_edit.is_none());
    }

    /// A lost title is reported, not written over, and the fix restores the
    /// pre-edit title.
    #[test]
    fn the_missing_title_fix_restores_the_pre_edit_title() {
        let (tmp, mut app) = make_app();
        let dir = app.store.issues_dir.clone();
        write_issue(&dir, "2026-01-01-t.md", 28, "Original", "todo", None);
        script(
            &mut app,
            &tmp,
            "untitle.sh",
            r#"sed -i 's/^title: .*/title: ""/' "$1""#,
        );
        let temp = temp_for(28);
        app.open_editor_round_trip("2026-01-01-t.md").unwrap();
        match &app.mode {
            Mode::EditRepair { problems, .. } => assert!(
                problems
                    .iter()
                    .any(|p| p.kind == EditProblemKind::MissingTitle),
                "{problems:?}"
            ),
            other => panic!("expected the repair prompt, got {other:?}"),
        }

        let _ = app.handle_key(press(KeyCode::Char('a'))).unwrap();

        assert!(matches!(app.mode, Mode::Board), "{:?}", app.mode);
        let on_disk = fs::read_to_string(dir.join("2026-01-01-t.md")).unwrap();
        assert_eq!(Issue::parse(&on_disk).unwrap().title, "Original");
        assert!(
            !temp.exists(),
            "a successful fix consumes the retained copy"
        );
    }

    /// The duplicate-key fix keeps the first value.
    #[test]
    fn the_duplicate_key_fix_keeps_the_first_value() {
        let (tmp, mut app) = make_app();
        let dir = app.store.issues_dir.clone();
        write_issue(&dir, "2026-01-01-dup.md", 25, "Kept", "todo", None);
        script(
            &mut app,
            &tmp,
            "dup.sh",
            r#"sed -i 's/^title: .*/&\ntitle: "Second"/' "$1""#,
        );
        let temp = temp_for(25);
        app.open_editor_round_trip("2026-01-01-dup.md").unwrap();
        match &app.mode {
            Mode::EditRepair { problems, .. } => assert!(
                problems
                    .iter()
                    .any(|p| p.kind == EditProblemKind::DuplicateKey),
                "{problems:?}"
            ),
            other => panic!("expected the repair prompt, got {other:?}"),
        }

        let _ = app.handle_key(press(KeyCode::Char('a'))).unwrap();

        assert!(matches!(app.mode, Mode::Board), "{:?}", app.mode);
        let on_disk = fs::read_to_string(dir.join("2026-01-01-dup.md")).unwrap();
        assert_eq!(Issue::parse(&on_disk).unwrap().title, "Kept");
        assert!(
            !temp.exists(),
            "a successful fix consumes the retained copy"
        );
    }

    /// A fix that still does not parse leaves the file and the copy
    /// untouched, and re-reports.
    #[test]
    fn a_fix_that_still_does_not_parse_leaves_the_file_untouched() {
        let (tmp, mut app) = make_app();
        let dir = app.store.issues_dir.clone();
        write_issue(&dir, "2026-01-01-broken.md", 27, "Broken", "todo", None);
        script(
            &mut app,
            &tmp,
            "triple.sh",
            r#"sed -i 's/^title: .*/&\ntitle: "B"\ntitle: "C"/' "$1""#,
        );
        let temp = temp_for(27);
        let disk_before = fs::read_to_string(dir.join("2026-01-01-broken.md")).unwrap();
        app.open_editor_round_trip("2026-01-01-broken.md").unwrap();
        assert!(
            matches!(app.mode, Mode::EditRepair { .. }),
            "{:?}",
            app.mode
        );
        let temp_before = fs::read_to_string(&temp).unwrap();

        let _ = app.handle_key(press(KeyCode::Char('a'))).unwrap();

        assert!(
            matches!(app.mode, Mode::EditRepair { .. }),
            "the prompt stays up: {:?}",
            app.mode
        );
        assert_eq!(
            fs::read_to_string(dir.join("2026-01-01-broken.md")).unwrap(),
            disk_before,
            "nothing is written when the fix does not repair the file"
        );
        assert_eq!(
            fs::read_to_string(&temp).unwrap(),
            temp_before,
            "the retained copy is untouched"
        );
        assert!(
            app.status_msg
                .as_deref()
                .is_some_and(|m| m.contains("did not make the file valid")),
            "got {:?}",
            app.status_msg
        );
        let _ = fs::remove_file(&temp);
    }

    /// Overwriting the issue leaves the previous version recoverable in the
    /// centralized backup directory, and the status names where.
    #[test]
    fn an_overwrite_stores_a_recoverable_copy_of_the_previous_version() {
        let (tmp, mut app) = make_app();
        let dir = app.store.issues_dir.clone();
        write_issue(&dir, "2026-01-01-b.md", 26, "B", "todo", None);
        script(
            &mut app,
            &tmp,
            "edit.sh",
            r#"sed -i 's/priority: medium/priority: high/' "$1""#,
        );
        let _ = temp_for(26);

        app.open_editor_round_trip("2026-01-01-b.md").unwrap();

        assert!(matches!(app.mode, Mode::Board), "{:?}", app.mode);
        let backups = crate::backup::list(&dir);
        assert_eq!(backups.len(), 1, "one overwrite, one recoverable copy");
        let backup = &backups[0];
        assert!(backup.is_file(), "the previous version must be recoverable");
        assert!(
            !dir.join("2026-01-01-b.md.tixbak").exists(),
            "the copy is centralized, not beside the issue"
        );
        let previous = fs::read_to_string(backup).unwrap();
        assert!(
            previous.contains("priority: \"medium\""),
            "the backup holds the pre-edit bytes:\n{previous}"
        );
        assert!(
            app.status_msg
                .as_deref()
                .is_some_and(|m| m.contains(&backup.display().to_string())),
            "the status names the backup: {:?}",
            app.status_msg
        );
    }
}