tix-tracker 0.11.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
//! Every problem an editor round trip can leave behind, and the repair tix can
//! apply to each one (tix #1506).
//!
//! The old flow ended with a `run_editor` that re-parsed the temp copy and threw
//! the diagnostic away, so the caller could only report `file not valid after
//! edit` and the real parse error never reached the user. This module is the
//! replacement: `run_editor` no longer validates (its job is to run the editor),
//! and the callers classify what came back here, where each problem carries the
//! diagnostic **and** — where tix can do so safely — a machine-applicable fix.
//!
//! The taxonomy is deliberately small and closed:
//!
//! | kind | source | automatic fix |
//! |---|---|---|
//! | `history_not_first` | a `tix lint` `history` finding | move the section to the top of the body |
//! | `unknown_key` | a `tix lint` `unknown_key` finding | declare the key in `[custom_attributes]` |
//! | `duplicate_key` | a YAML duplicate-field parse error | drop the later duplicate, keep the first |
//! | `retired_links_key` | a `tix lint` `retired_links_key` finding | remove the key |
//! | `missing_title` | an empty `title:` after the edit | restore the pre-edit title |
//! | `history_entry` | a hand-edited `## History` line | none — reopen the editor |
//! | `invalid_value` | any other `tix lint` finding | none — reopen the editor |
//! | `unparsable` | a frontmatter that will not parse | none — reopen the editor |
//!
//! Every problem carries a [`proposal`](EditProblem::proposal), even when the
//! only honest proposal is "reopen the editor on the retained copy and fix it by
//! hand". A problem with no proposal would be a dead end, which is exactly what
//! this ticket exists to remove.

use crate::commands::lint::TixIssueFinding;
use crate::model::{HISTORY_HEADING, Issue, is_history_heading};

/// What kind of post-edit problem this is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EditProblemKind {
    /// A `## History` section that is not the first thing in the body.
    HistoryNotFirst,
    /// A top-level frontmatter key tix does not know.
    UnknownKey,
    /// The same frontmatter key declared twice.
    DuplicateKey,
    /// The retired `links:` key, whose value tix no longer reads.
    RetiredLinksKey,
    /// The issue has no title, so it has no stable slug or filename.
    MissingTitle,
    /// A `## History` line that could not be parsed, or that looks like an entry
    /// without being one.
    HistoryEntry,
    /// Any other value `tix lint` rejects.
    InvalidValue,
    /// The frontmatter does not parse at all (bad YAML, a missing `---` fence,
    /// or anything else the parser refused).
    Unparsable,
}

impl EditProblemKind {
    /// The stable name, used in the prompt heading and in tests.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::HistoryNotFirst => "history_not_first",
            Self::UnknownKey => "unknown_key",
            Self::DuplicateKey => "duplicate_key",
            Self::RetiredLinksKey => "retired_links_key",
            Self::MissingTitle => "missing_title",
            Self::HistoryEntry => "history_entry",
            Self::InvalidValue => "invalid_value",
            Self::Unparsable => "unparsable",
        }
    }
}

/// A machine-applicable repair.
///
/// "Machine-applicable" is the whole bar: a fix is only offered when tix can
/// perform it without guessing at what the author meant. Prose problems get no
/// fix, only a proposal, because a tool that rewrites a user's words is worse
/// than one that says "here is the file, fix it".
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EditFix {
    /// Move the misplaced `## History` heading and its whole entry block to the
    /// top of the body, byte-for-byte.
    MoveHistoryToFront,
    /// Declare `key` in `tix.toml`'s `[custom_attributes]`. Applied by the app
    /// (it writes `tix.toml`), not by rewriting the issue file.
    DeclareCustomAttribute { key: String },
    /// Drop the later occurrence of `key`, keeping the first.
    DropDuplicateKey { key: String, kept: String },
    /// Remove the retired `links:` key and its block.
    RemoveRetiredLinksKey { key: String },
    /// Put the pre-edit title back.
    RestoreTitle { title: String },
}

impl EditFix {
    /// The human description of what applying the fix does.
    pub fn label(&self) -> String {
        match self {
            Self::MoveHistoryToFront => {
                "move the `## History` section to the top of the body".to_string()
            }
            Self::DeclareCustomAttribute { key } => {
                format!("declare `{key}` in `[custom_attributes]` in tix.toml")
            }
            Self::DropDuplicateKey { key, .. } => {
                format!("drop the later duplicate `{key}:`")
            }
            Self::RemoveRetiredLinksKey { key } => {
                format!("remove the retired `{key}:` key")
            }
            Self::RestoreTitle { title } => format!("restore the title `{title}`"),
        }
    }

    /// Whether the fix is a rewrite of the issue text, as opposed to an action
    /// the app performs elsewhere (declaring a key writes `tix.toml`).
    pub const fn is_text_fix(&self) -> bool {
        !matches!(self, Self::DeclareCustomAttribute { .. })
    }

    /// Apply the fix to `contents`, returning the repaired text.
    ///
    /// `None` when the fix cannot be applied — the declared-key fix is not a
    /// text edit at all, and the text fixes refuse rather than guess when the
    /// shape they expect is absent. A `None` means the caller must leave the
    /// file untouched.
    pub fn apply(&self, contents: &str) -> Option<String> {
        match self {
            Self::DeclareCustomAttribute { .. } => None,
            Self::MoveHistoryToFront => move_history_to_front(contents),
            Self::DropDuplicateKey { key, .. } => remove_key_occurrence(contents, key, 1),
            Self::RemoveRetiredLinksKey { key } => remove_key_occurrence(contents, key, 0),
            Self::RestoreTitle { title } => set_title(contents, title),
        }
    }
}

/// One classified problem, with the diagnostic and the way out.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EditProblem {
    /// The taxonomy entry.
    pub kind: EditProblemKind,
    /// The real diagnostic. For a parse failure this is the parser's own
    /// message, verbatim — never the old `file not valid after edit`.
    pub message: String,
    /// What to do about it. Always populated; the least a problem can propose is
    /// reopening the editor on the retained copy.
    pub proposal: Option<String>,
    /// The repair tix can perform, when there is one it can perform safely.
    pub fix: Option<EditFix>,
}

impl EditProblem {
    /// `kind: message`, the one-line form the prompt and status line use.
    pub fn summary(&self) -> String {
        format!("{}: {}", self.kind.as_str(), self.message)
    }

    /// The proposal text, or a plain "reopen the editor" fallback so a problem
    /// can never render as a dead end.
    pub fn proposal_text(&self) -> String {
        self.proposal.clone().unwrap_or_else(|| {
            "reopen the editor on the retained copy and fix it by hand".to_string()
        })
    }

    /// The fix tix can apply, if any.
    pub fn fix(&self) -> Option<&EditFix> {
        self.fix.as_ref()
    }
}

/// Classify a failed `Issue::parse`.
///
/// `contents` is the text that would not parse — needed to locate a duplicate
/// key's later occurrence. `previous` is the issue as it was before the edit,
/// used only for the (rare) restore-title case; a parse failure never has a
/// title to restore, so it stays unused here and exists for symmetry with
/// [`for_lint_findings`].
pub fn for_parse_error(
    message: &str,
    contents: &str,
    _previous: Option<&Issue>,
) -> Vec<EditProblem> {
    if let Some(key) = duplicate_field_key(message)
        && let Some(problem) = duplicate_key_problem(contents, &key)
    {
        return vec![problem];
    }
    vec![EditProblem {
        kind: EditProblemKind::Unparsable,
        message: message.to_string(),
        proposal: Some(
            "reopen the editor on the retained copy and fix it by hand — nothing has \
             been written"
                .to_string(),
        ),
        fix: None,
    }]
}

/// Classify the findings of a `tix lint` pass over the edited file.
pub fn for_lint_findings(
    findings: &[TixIssueFinding],
    previous: Option<&Issue>,
) -> Vec<EditProblem> {
    findings
        .iter()
        .map(|finding| for_lint_finding(finding, previous))
        .collect()
}

/// A titleless issue's problem, with the pre-edit title as the fix when there is
/// one to restore.
pub fn missing_title(previous: Option<&Issue>) -> EditProblem {
    missing_title_problem(previous, None)
}

fn for_lint_finding(finding: &TixIssueFinding, previous: Option<&Issue>) -> EditProblem {
    match finding.kind.as_str() {
        "unknown_key" => {
            let key = finding.value.trim().to_string();
            EditProblem {
                kind: EditProblemKind::UnknownKey,
                message: finding.message.clone(),
                proposal: Some(format!(
                    "declare `{key}` in `[custom_attributes]` in tix.toml"
                )),
                fix: (!key.is_empty()).then_some(EditFix::DeclareCustomAttribute { key }),
            }
        }
        "retired_links_key" => EditProblem {
            kind: EditProblemKind::RetiredLinksKey,
            message: finding.message.clone(),
            proposal: Some(
                "remove the retired `links:` key — its value is no longer read".to_string(),
            ),
            fix: Some(EditFix::RemoveRetiredLinksKey {
                key: if finding.value.trim().is_empty() {
                    "links".to_string()
                } else {
                    finding.value.trim().to_string()
                },
            }),
        },
        // The misplaced-section finding is the one `history` finding with a
        // mechanical fix; the others are hand-edited lines that must not be
        // rewritten.
        "history" if finding.value.trim() == HISTORY_HEADING => EditProblem {
            kind: EditProblemKind::HistoryNotFirst,
            message: finding.message.clone(),
            proposal: Some(
                "move the `## History` section to the top of the body, preserving every \
                 entry"
                    .to_string(),
            ),
            fix: Some(EditFix::MoveHistoryToFront),
        },
        "history" => hand_fix_problem(
            EditProblemKind::HistoryEntry,
            finding.message.clone(),
            "reopen the editor on the retained copy and correct the entry by hand — its \
             bytes are preserved",
        ),
        "title" => missing_title_problem(previous, Some(finding.message.clone())),
        _ => hand_fix_problem(
            EditProblemKind::InvalidValue,
            format!("{}: {}", finding.kind, finding.message),
            "reopen the editor on the retained copy and correct the value by hand",
        ),
    }
}

fn hand_fix_problem(kind: EditProblemKind, message: String, proposal: &str) -> EditProblem {
    EditProblem {
        kind,
        message,
        proposal: Some(proposal.to_string()),
        fix: None,
    }
}

fn missing_title_problem(previous: Option<&Issue>, message: Option<String>) -> EditProblem {
    let restored = previous
        .map(|issue| issue.title.clone())
        .filter(|title| !title.trim().is_empty());
    EditProblem {
        kind: EditProblemKind::MissingTitle,
        message: message.unwrap_or_else(|| "title is required".to_string()),
        proposal: Some(match &restored {
            Some(title) => format!("restore the pre-edit title `{title}`"),
            None => "reopen the editor on the retained copy and add a title".to_string(),
        }),
        fix: restored.map(|title| EditFix::RestoreTitle { title }),
    }
}

/// The field name from serde's duplicate-field diagnostic: `duplicate field
/// \`title\``.
fn duplicate_field_key(message: &str) -> Option<String> {
    let rest = message.strip_prefix("duplicate field `")?;
    let (key, _) = rest.split_once('`')?;
    (!key.is_empty()).then(|| key.to_string())
}

fn duplicate_key_problem(contents: &str, key: &str) -> Option<EditProblem> {
    if count_key_occurrences(contents, key) < 2 {
        return None;
    }
    let kept = key_value(contents, key, 0).unwrap_or_default();
    Some(EditProblem {
        kind: EditProblemKind::DuplicateKey,
        message: format!("duplicate field `{key}`"),
        proposal: Some(format!(
            "drop the later `{key}:` entry, keeping the first value (`{kept}`)"
        )),
        fix: Some(EditFix::DropDuplicateKey {
            key: key.to_string(),
            kept,
        }),
    })
}

/// The byte range of the frontmatter **content** (between the opening and
/// closing `---` lines). `None` when the fences are missing or unterminated.
fn frontmatter_region(contents: &str) -> Option<(usize, usize)> {
    let rest = contents.strip_prefix("---\n")?;
    let start = contents.len() - rest.len();
    let mut offset = start;
    for line in rest.split_inclusive('\n') {
        if line.trim_end_matches('\n') == "---" {
            return Some((start, offset));
        }
        offset += line.len();
    }
    None
}

/// The top-level key a frontmatter line declares, or `None` for a line that is
/// not a top-level key (indented, blank, a comment, or without a colon).
fn top_level_key(line: &str) -> Option<String> {
    if line.is_empty() || line.starts_with([' ', '\t', '#']) {
        return None;
    }
    let (head, _) = line.split_once(':')?;
    let key = strip_quotes(head.trim());
    (!key.is_empty()).then(|| key.to_string())
}

fn strip_quotes(value: &str) -> &str {
    if let Some(inner) = value.strip_prefix('"').and_then(|v| v.strip_suffix('"')) {
        return inner;
    }
    if let Some(inner) = value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')) {
        return inner;
    }
    value
}

/// Every `offset..line_end` span inside `contents`' frontmatter whose line
/// declares `key` at the top level, in file order.
fn key_spans(contents: &str, key: &str) -> Vec<(usize, usize)> {
    let Some((start, end)) = frontmatter_region(contents) else {
        return Vec::new();
    };
    let mut spans = Vec::new();
    let mut offset = start;
    while offset < end {
        let line_end = contents[offset..]
            .find('\n')
            .map_or(end, |index| offset + index + 1);
        let line = &contents[offset..line_end];
        if top_level_key(line).as_deref() == Some(key) {
            // Extend over the value's indented continuation lines (a block
            // sequence or mapping), never over a blank line or the next key.
            let mut block_end = line_end;
            while block_end < end {
                let next_end = contents[block_end..]
                    .find('\n')
                    .map_or(end, |index| block_end + index + 1);
                let next = &contents[block_end..next_end];
                // A value's block is either indented (a nested mapping or an
                // indented sequence) or a column-0 `- ` sequence, which YAML
                // allows at the key's own indentation. A top-level key line can
                // never start with `- `, so this cannot swallow the next key.
                if next.starts_with(' ') || next.starts_with('\t') || next.starts_with("- ") {
                    block_end = next_end;
                } else {
                    break;
                }
            }
            spans.push((offset, block_end));
        }
        offset = line_end;
    }
    spans
}

fn count_key_occurrences(contents: &str, key: &str) -> usize {
    key_spans(contents, key).len()
}

/// The inline value of the `occurrence`-th `key:` entry, or the first non-empty
/// line of its block. Used only for the message that says which value was kept.
fn key_value(contents: &str, key: &str, occurrence: usize) -> Option<String> {
    let spans = key_spans(contents, key);
    let (start, end) = *spans.get(occurrence)?;
    let block = &contents[start..end];
    let mut lines = block.lines();
    let head = lines.next()?;
    let inline = strip_quotes(head.split_once(':').map_or("", |(_, v)| v).trim());
    if !inline.is_empty() {
        return Some(inline.to_string());
    }
    lines
        .map(str::trim)
        .find(|line| !line.is_empty())
        .map(str::to_string)
}

/// Remove the `occurrence`-th top-level `key:` entry and its indented block.
fn remove_key_occurrence(contents: &str, key: &str, occurrence: usize) -> Option<String> {
    let (start, end) = *key_spans(contents, key).get(occurrence)?;
    let mut out = String::with_capacity(contents.len());
    out.push_str(&contents[..start]);
    out.push_str(&contents[end..]);
    Some(out)
}

/// Replace the first `title:` value with `title`.
fn set_title(contents: &str, title: &str) -> Option<String> {
    let (start, end) = *key_spans(contents, "title").first()?;
    let line = &contents[start..end];
    let colon = line.find(':')?;
    let rendered = serde_yaml::to_string(title)
        .map(|yaml| yaml.trim_end().to_string())
        .unwrap_or_else(|_| format!("{title:?}"));
    let mut out = String::with_capacity(contents.len());
    out.push_str(&contents[..=start + colon]);
    out.push(' ');
    out.push_str(&rendered);
    out.push('\n');
    out.push_str(&contents[end..]);
    Some(out)
}

/// Move the first misplaced `## History` section, with its whole entry block, to
/// the top of the body.
///
/// Every line of the section is copied across byte-for-byte: the heading, the
/// entry lines (parsed or hand-edited), and the blank lines between them. The
/// block ends at the last line that is blank or a `- ` list item, so body prose
/// that follows the section stays in the body.
fn move_history_to_front(contents: &str) -> Option<String> {
    let fence_end = closing_fence_end(contents)?;
    let head = &contents[..fence_end];
    let mut body = &contents[fence_end..];
    if let Some(rest) = body.strip_prefix('\n') {
        body = rest;
    }
    let lines: Vec<&str> = body.split('\n').collect();
    let heading = lines.iter().position(|line| is_history_heading(line))?;
    if heading == 0 {
        // Already the first thing in the body; nothing to move.
        return None;
    }
    let mut block_end = heading + 1;
    while block_end < lines.len()
        && (lines[block_end].trim().is_empty() || lines[block_end].trim_start().starts_with("- "))
    {
        block_end += 1;
    }
    // Trim trailing blank lines from the captured block so the section does not
    // carry the separator that belonged to the prose it sat above.
    while block_end > heading + 1 && lines[block_end - 1].trim().is_empty() {
        block_end -= 1;
    }
    let block: Vec<&str> = lines[heading..block_end].to_vec();
    let mut remaining: Vec<&str> = Vec::new();
    remaining.extend_from_slice(&lines[..heading]);
    remaining.extend_from_slice(&lines[block_end..]);
    let remaining = remaining.join("\n");
    let remaining = remaining.trim_matches('\n');
    let mut new_body = block.join("\n");
    new_body.push('\n');
    if !remaining.is_empty() {
        new_body.push('\n');
        new_body.push_str(remaining);
        new_body.push('\n');
    }
    Some(format!("{head}\n{new_body}"))
}

/// The end offset of the closing `---` fence line, including its newline.
fn closing_fence_end(contents: &str) -> Option<usize> {
    let rest = contents.strip_prefix("---\n")?;
    let mut offset = contents.len() - rest.len();
    for line in rest.split_inclusive('\n') {
        if line.trim_end_matches('\n') == "---" {
            return Some(offset + line.len());
        }
        offset += line.len();
    }
    None
}

#[cfg(test)]
mod tests {
    #[allow(clippy::wildcard_imports)]
    use super::*;
    use crate::model::Issue;

    fn issue_with_history(body: &str) -> String {
        format!(
            "---\nnumber: 1\ntitle: \"Hist\"\nstatus: todo\npriority: medium\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\n{body}"
        )
    }

    #[test]
    fn parse_error_for_a_duplicate_key_offers_the_drop_fix() {
        let contents = "---\nnumber: 1\ntitle: \"First\"\ntitle: \"Second\"\nstatus: todo\npriority: medium\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody.\n";
        let problem = &for_parse_error("duplicate field `title`", contents, None)[0];
        assert_eq!(problem.kind, EditProblemKind::DuplicateKey);
        assert!(problem.proposal.as_deref().unwrap().contains("First"));
        let fixed = problem.fix().unwrap().apply(contents).unwrap();
        let issue = Issue::parse(&fixed).unwrap();
        assert_eq!(
            issue.title, "First",
            "the first value must be kept:\n{fixed}"
        );
        assert_eq!(fixed.matches("title:").count(), 1);
    }

    #[test]
    fn parse_error_for_garbage_has_no_fix_and_says_nothing_was_written() {
        for message in [
            "priority: invalid type: sequence, expected a string at line 4 column 11",
            "file must start with a `---` delimiter",
            "frontmatter is not terminated by a closing `---`",
        ] {
            let problems = for_parse_error(message, "garbage", None);
            assert_eq!(problems.len(), 1);
            assert_eq!(problems[0].kind, EditProblemKind::Unparsable);
            assert_eq!(problems[0].message, message, "the real diagnostic is kept");
            assert!(problems[0].fix.is_none());
            assert!(
                problems[0]
                    .proposal_text()
                    .contains("nothing has been written")
            );
            assert_ne!(problems[0].message, "file not valid after edit");
        }
    }

    #[test]
    fn history_move_preserves_every_entry_and_the_file_then_parses() {
        let contents = issue_with_history(
            "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\nMore prose.\n",
        );
        let before = Issue::parse(&contents).unwrap();
        assert!(before.history.is_empty(), "the section is body text before");

        let fixed = EditFix::MoveHistoryToFront.apply(&contents).unwrap();
        let after = Issue::parse(&fixed).unwrap();
        assert_eq!(
            after.history.entries.len(),
            2,
            "both entries are recognised: {fixed}"
        );
        for line in contents.lines().filter(|l| l.starts_with("- 20")) {
            assert!(
                fixed.contains(line),
                "entry `{line}` must survive byte-for-byte"
            );
        }
        assert!(after.body.contains("Some prose"));
        assert!(after.body.contains("More prose"));
    }

    #[test]
    fn retired_links_fix_removes_the_key_and_its_block() {
        let contents =
            issue_with_history("Body.").replace("created:", "links:\n- \"12\"\n- task-7\ncreated:");
        let fixed = EditFix::RemoveRetiredLinksKey {
            key: "links".to_string(),
        }
        .apply(&contents)
        .unwrap();
        assert!(!fixed.contains("links:"), "{fixed}");
        assert!(Issue::parse(&fixed).is_ok());
    }

    #[test]
    fn restore_title_writes_the_previous_title_back() {
        let contents = "---\nnumber: 1\ntitle: \"\"\nstatus: todo\npriority: medium\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody.\n";
        let fixed = EditFix::RestoreTitle {
            title: "Original title".to_string(),
        }
        .apply(contents)
        .unwrap();
        assert_eq!(Issue::parse(&fixed).unwrap().title, "Original title");
    }

    fn finding(kind: &str, value: &str, message: &str) -> TixIssueFinding {
        TixIssueFinding {
            severity: crate::commands::lint::Severity::Warning,
            file: "2026-01-01-a.md".to_string(),
            line: 1,
            column: 1,
            value: value.to_string(),
            kind: kind.to_string(),
            message: message.to_string(),
        }
    }

    #[test]
    fn every_problem_carries_a_proposal() {
        let previous = Issue::parse(&issue_with_history("Body.")).unwrap();
        let findings = vec![
            finding(
                "unknown_key",
                "build_id",
                "unknown top-level frontmatter key",
            ),
            finding(
                "retired_links_key",
                "links",
                "still carries the retired key",
            ),
            finding("history", HISTORY_HEADING, "must be the first thing"),
            finding("history", "- broken", "looks like an entry"),
            finding("title", "", "title is required"),
            finding("priority", "nope", "valid options: low, medium, high"),
        ];
        let classified = for_lint_findings(&findings, Some(&previous));
        let parse = for_parse_error("duplicate field `title`", "---\n", None);
        for problem in classified.iter().chain(parse.iter()) {
            assert!(
                problem.proposal.is_some(),
                "{} must propose something: {problem:?}",
                problem.kind.as_str()
            );
            assert_ne!(problem.message, "");
        }
        // The misplaced-section finding keeps the lint message verbatim and gets
        // the move fix; the unparsed-entry finding gets a proposal but no fix.
        assert_eq!(classified[2].kind, EditProblemKind::HistoryNotFirst);
        assert_eq!(classified[2].message, "must be the first thing");
        assert_eq!(classified[2].fix, Some(EditFix::MoveHistoryToFront));
        assert_eq!(classified[3].kind, EditProblemKind::HistoryEntry);
        assert!(classified[3].fix.is_none());
        assert_eq!(classified[4].kind, EditProblemKind::MissingTitle);
        assert_eq!(
            classified[4].fix,
            Some(EditFix::RestoreTitle {
                title: "Hist".to_string()
            })
        );
    }

    #[test]
    fn a_fix_that_cannot_find_its_shape_refuses_instead_of_guessing() {
        let contents = issue_with_history("Body.");
        assert!(
            EditFix::DropDuplicateKey {
                key: "title".to_string(),
                kept: String::new(),
            }
            .apply(&contents)
            .is_none()
        );
        assert!(
            EditFix::RemoveRetiredLinksKey {
                key: "links".to_string(),
            }
            .apply(&contents)
            .is_none()
        );
        assert!(
            EditFix::RestoreTitle {
                title: "T".to_string(),
            }
            .apply("---\nnumber: 1\n---\n")
            .is_none()
        );
        assert!(
            EditFix::MoveHistoryToFront
                .apply("not a document")
                .is_none()
        );
    }
}