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
#[allow(clippy::wildcard_imports)]
use super::*;

/// Collect every finding for one issue file: a `missing`/`parse` diagnostic
/// when the file cannot be parsed, otherwise value validation (FR-016).
/// The outcome of one file's pass: the issue it parsed, if it parsed at all.
///
/// The relationship sweep graphs exactly the issues this walk produced, rather
/// than re-reading the tree through `Store::list`. `list` aborts on the first
/// malformed file — which is exactly why lint walks the store itself (FR-018) —
/// so building the graph that way made one broken file kill the whole command
/// (exit 2, and every relationship problem in the tree went unreported).
pub(super) struct ParsedFile {
    pub(super) rel: String,
    pub(super) text: String,
    pub(super) issue: Issue,
}

pub(super) fn collect_for_file(
    config: &Config,
    store: &Store,
    planner: &Planner,
    milestone_names: &[String],
    rel: &str,
    findings: &mut Vec<TixIssueFinding>,
) -> Result<Option<ParsedFile>> {
    let text = match fs::read_to_string(store.issues_dir.join(rel)) {
        Ok(text) => text,
        Err(err) if err.kind() == std::io::ErrorKind::InvalidData => {
            // Non-UTF-8 bytes: a clean diagnostic, keep scanning (FR-018).
            findings.push(TixIssueFinding {
                severity: Severity::Error,
                file: rel.to_string(),
                line: 0,
                column: 0,
                value: String::new(),
                kind: "parse".to_string(),
                message: "file is not valid UTF-8".to_string(),
            });
            return Ok(None);
        }
        Err(err) => return Err(TixError::Io(err)),
    };
    let issue = match Issue::parse(&text) {
        Ok(issue) => issue,
        Err(TixError::Parse(msg)) => {
            findings.push(TixIssueFinding {
                severity: Severity::Error,
                file: rel.to_string(),
                line: 0,
                column: 0,
                value: String::new(),
                kind: if text.starts_with("---\n") {
                    "parse".to_string()
                } else {
                    "missing".to_string()
                },
                message: msg,
            });
            return Ok(None);
        }
        Err(other) => return Err(other),
    };
    validate_issue(
        config,
        planner,
        milestone_names,
        rel,
        &text,
        &issue,
        findings,
    );
    unknown_frontmatter_keys(config, rel, &text, &issue, findings);
    Ok(Some(ParsedFile {
        rel: rel.to_string(),
        text,
        issue,
    }))
}

/// Warn about top-level frontmatter keys this model does not know (#1361).
///
/// A **warning**, not an error, and the difference is the whole design: the key is
/// preserved on write, so the file is valid and `tix lint` exiting 0 is honest. The
/// warning exists because a key `tix` does not recognise is very often a **typo** —
/// `titel:` renders, round-trips, and is never read by anything. Before this, such a
/// key was not merely silent, it was deleted on the next write, so a typo and a
/// deliberate custom key were indistinguishable.
///
/// Suppressed by `[custom_attributes]` in `tix.toml`: a project that genuinely uses
/// a key declares it once and stops being told about it. That is the escape hatch,
/// and it is why the finding is a warning rather than an error — the fix is always
/// available and is never urgent.
///
/// The retired `links:` key is **not** reported here. It is recognised, reported by
/// its own `retired_links_key` finding, and dropped (C-001); warning about it twice
/// would be two findings for one problem.
pub(super) fn unknown_frontmatter_keys(
    config: &Config,
    rel: &str,
    text: &str,
    issue: &Issue,
    findings: &mut Vec<TixIssueFinding>,
) {
    let declared = config.custom_attributes();
    for key in issue.extra_frontmatter.keys() {
        if declared.iter().any(|d| d == key) {
            continue;
        }
        findings.push(TixIssueFinding {
            severity: Severity::Warning,
            file: rel.to_string(),
            line: locate_key_line(text, key),
            column: 1,
            value: key.clone(),
            kind: "unknown_key".to_string(),
            message: format!(
                "unknown top-level frontmatter key `{key}`: it is preserved on write but \
                 nothing reads it. If that is deliberate, declare it in \
                 `[custom_attributes]` in tix.toml; if not, it is probably a typo."
            ),
        });
    }
}

/// The 1-based line of `key:` in the file's frontmatter, or 0 when it cannot be
/// found. `0` renders as a file-level finding, which is the honest answer when the
/// key is present in the model but not locatable in the text.
pub(super) fn locate_key_line(text: &str, key: &str) -> usize {
    let frontmatter = match text.strip_prefix("---\n") {
        Some(rest) => rest,
        None => return 0,
    };
    for (offset, line) in frontmatter.lines().enumerate() {
        if line == key
            || line.starts_with(&format!("{key}:"))
            || line.starts_with(&format!("\"{key}\":"))
        {
            return offset + 2; // +1 for the opening `---`, +1 for 1-based lines.
        }
        if line == "---" {
            break;
        }
    }
    0
}

/// Value validation over the parsed issue.
///
/// Used to say "unknown keys are never flagged", which was the charter's stated
/// policy and is now **reversed** by #1361: unknown keys warn. See
/// [`unknown_frontmatter_keys`].
/// Planning fields (WP03) add three reference checks that all route through
/// the WP01 registry and WP02 date-pair validator — no copied rules:
///   - every `cycles` name must be a configured `[cycles.*]` entry,
///   - every `milestones` name must be a registry file under `milestones_dir`,
///   - `start_date`/`due_date` must parse and satisfy `due_date >= start_date`.
#[allow(clippy::too_many_lines)]
pub(super) fn validate_issue(
    config: &Config,
    planner: &Planner,
    milestone_names: &[String],
    rel: &str,
    text: &str,
    issue: &Issue,
    findings: &mut Vec<TixIssueFinding>,
) {
    let status = issue.status.display();
    let columns = &config.default_config().columns;
    if !columns.iter().any(|c| c == status) {
        findings.push(value_finding(
            rel,
            text,
            "status",
            status,
            format!("valid options: {}", columns.join(", ")),
        ));
    }
    if issue.title.trim().is_empty() {
        findings.push(value_finding(
            rel,
            text,
            "title",
            &issue.title,
            "title is required".to_string(),
        ));
    }
    // An unset priority — `priority: ''` — is a legitimate state, not an unknown
    // value: the author said "no priority" rather than failing to choose one. It
    // is exempted, and exempted *only* as the empty string, so a genuine typo
    // (`priority: 'hih'`, `priority: 'urgent'`) is still reported. Silently
    // coercing it to the default `medium` instead would lose the author's
    // statement, which is the one thing the typed model is not supposed to do.
    if let Priority::Other(unknown) = &issue.priority
        && !issue.priority.is_undefined()
    {
        findings.push(value_finding(
            rel,
            text,
            "priority",
            unknown,
            "valid options: '' (unset), low, medium, high".to_string(),
        ));
    }
    // The issue type, always checked against the configured vocabulary. An
    // unknown value is a **warning** with the remedy in the message: the reader
    // can accept it by adding it to `custom_types` in `tix.toml`.
    if let Some(t) = issue
        .type_
        .as_deref()
        .map(str::trim)
        .filter(|t| !t.is_empty())
    {
        let allowed = config.custom_types();
        if !allowed.iter().any(|a| a.eq_ignore_ascii_case(t)) {
            let located = locate_value(text, "type");
            findings.push(TixIssueFinding {
                severity: Severity::Warning,
                file: rel.to_string(),
                line: located.as_ref().map_or(0, |l| l.line),
                column: located.as_ref().map_or(0, |l| l.column),
                value: t.to_string(),
                kind: "unknown_type".to_string(),
                message: format!(
                    "unknown issue type `{t}`; valid types: {}. Add it to \
                     `types` in tix.toml to accept it.",
                    allowed.join(", ")
                ),
            });
        }
    }
    if !is_iso_date(&issue.created) {
        findings.push(value_finding(
            rel,
            text,
            "created",
            &issue.created,
            "expected a date in `YYYY-MM-DD` format".to_string(),
        ));
    }
    if !is_iso_date(&issue.updated) {
        findings.push(value_finding(
            rel,
            text,
            "updated",
            &issue.updated,
            "expected a date in `YYYY-MM-DD` format".to_string(),
        ));
    }
    if let Some(estimate) = &issue.estimate
        && crate::wip::Estimate::parse_terms(estimate).is_err()
    {
        findings.push(value_finding(
            rel,
            text,
            "estimate",
            estimate,
            "estimate must be a duration such as `3`, `3d`, `1 day` or `0.5-1 day`".to_string(),
        ));
    }
    // The retired `links:` key is a validation result, not a parse fallback:
    // the field is reported and its value is never read as typed data (C-001).
    // A hand-edited `## History` line is a per-issue diagnostic, never a
    // parse failure: the line is preserved verbatim and the rest of the file
    // stays readable. Reported once per offending line so the author can see
    // exactly which lines the tool could not read.
    // A `## History` section that is **not at the front of the body**.
    //
    // `data-model.md` §8 pins the section to the front: "Only a section at the
    // *front* of the body is recognised — the position pinned above — so a
    // `## History` heading appearing later in an issue's prose is ordinary body
    // text." The parser implements that correctly, which is exactly why the
    // violation is dangerous: the section and its events are not rejected, they
    // are reclassified as body prose.
    //
    // The two consequences are both silent and both bad. `tix view` shows the
    // heading as text, so the issue appears to have no audit trail at all; and
    // `tix edit --body` replaces the body wholesale, which destroys the section
    // and every event in it. A plain write preserves it, so the loss arrives
    // later and looks unrelated to whatever hand-edit caused it.
    //
    // Reported once per occurrence rather than once per issue, because a file
    // can carry a misplaced section *and* a real one, and the difference matters.
    //
    // Fenced code blocks are skipped. A ``` console sample that prints a
    // `## History` heading, or a ``` markdown example of the format, is
    // **literal text**, not a section — and reporting it flagged every issue
    // that documents the History format, including this repository's own
    // mission findings. A heading inside a fence is not a misplaced section,
    // so the scan has to know where the fences are.
    //
    // The finding also carries the **absolute** line of the offending heading,
    // derived from the body's offset in the file (`body_start_line`). The old
    // form went through `value_finding`, which locates a *frontmatter key* —
    // and `## History` is not one, so the diagnostic always landed at 1:1 and
    // underlined the opening `---` instead of the heading it was about.
    let fenced = fenced_lines(&issue.body);
    let body_line = body_start_line(text, &issue.body);
    for (index, line) in issue.body.lines().enumerate() {
        if fenced.get(index).copied().unwrap_or(false) {
            continue;
        }
        if crate::model::is_history_heading(line) {
            findings.push(finding_at_line(
                rel,
                body_line + index,
                1,
                "history",
                line.trim(),
                "a `## History` section must be the first thing in the body; \
                 this one is treated as body text, so its entries are not in the \
                 audit trail and the next `tix edit --body` deletes them"
                    .to_string(),
            ));
        }
    }
    // A body line shaped like a History entry but not recognised as one. The
    // section has no end-of-section delimiter, so an entry hand-typed with ASCII
    // hyphens instead of U+2014 cannot be told apart from prose by shape alone
    // and is left in the body rather than absorbed. Reporting it means the
    // author finds out, instead of the entry silently disappearing from the
    // audit trail. Fenced lines are skipped here too, for the same reason.
    for (index, line) in issue.body.lines().enumerate() {
        if fenced.get(index).copied().unwrap_or(false) {
            continue;
        }
        if crate::model::looks_like_an_unrecognised_entry(line) {
            findings.push(finding_at_line(
                rel,
                body_line + index,
                1,
                "history",
                line.trim(),
                "looks like a `## History` entry but was not recognised \u{2014} \
                 entries need U+2014 em-dash separators, not ASCII hyphens"
                    .to_string(),
            ));
        }
    }
    for line in issue.history.unparsed() {
        let finding = value_finding(
            rel,
            text,
            "history",
            line,
            "unparseable `## History` entry \u{2014} kept verbatim, never repaired; \
             expected `- <timestamp> \u{2014} <actor> \u{2014} <kind> \u{2014} <detail>` \
             with U+2014 em-dash separators"
                .to_string(),
        );
        findings.push(finding);
    }
    if let Some(cycles) = &issue.cycles {
        for name in cycles {
            if planner.cycle(name).is_none() {
                let known = planner.cycle_names();
                let list = if known.is_empty() {
                    "none configured".to_string()
                } else {
                    known.join(", ")
                };
                findings.push(value_finding(
                    rel,
                    text,
                    "cycles",
                    name,
                    format!("unknown cycle — valid cycles: {list}"),
                ));
            }
        }
    }
    if let Some(milestones) = &issue.milestones {
        for name in milestones {
            if planner.milestone(name).is_err() || !milestone_names.iter().any(|m| m == name) {
                let list = if milestone_names.is_empty() {
                    "none configured".to_string()
                } else {
                    milestone_names.join(", ")
                };
                findings.push(value_finding(
                    rel,
                    text,
                    "milestones",
                    name,
                    format!("unknown milestone — valid milestones: {list}"),
                ));
            }
        }
    }
    // The date-pair rule surfaces as one finding named after the offending
    // member; the message reuses the WP02 validator verbatim.
    if let Err(TixError::Config(msg)) =
        crate::model::validate_issue_dates(issue.start_date.as_deref(), issue.due_date.as_deref())
    {
        let (kind, value) = if msg.starts_with("start_date") {
            ("start_date", issue.start_date.as_deref().unwrap_or(""))
        } else {
            ("due_date", issue.due_date.as_deref().unwrap_or(""))
        };
        findings.push(value_finding(rel, text, kind, value, msg));
    }
}

/// A value finding, located by scanning the raw frontmatter (serde_yaml
/// loses spans, so the line/column come from the source text itself).
pub(super) fn value_finding(
    rel: &str,
    text: &str,
    kind: &str,
    value: &str,
    message: String,
) -> TixIssueFinding {
    finding_at(rel, text, kind, kind, value, message)
}

/// As [`value_finding`], but the finding's `kind` and the frontmatter key used to
/// locate the value are named separately.
///
/// They are the same string for every per-file check, which is why one parameter
/// used to do both jobs. They are **not** the same for a relationship diagnostic:
/// the finding's kind is the contract's name (`retired_links_key`,
/// `conflicting_edge`, …) while the key to look up is whatever the diagnostic
/// names (`links`, `kind`, `to`). Passing the contract name to `locate_value`
/// looks for a frontmatter key that does not exist, so every relationship finding
/// came out at line 0, column 0 — a file-level finding that points at the first
/// line of the file rather than at the offending value.
pub(super) fn finding_at(
    rel: &str,
    text: &str,
    kind: &str,
    locate_key: &str,
    value: &str,
    message: String,
) -> TixIssueFinding {
    let (line, column) = locate_value(text, locate_key)
        .map(|l| (l.line, l.column))
        .unwrap_or((0, 0));
    TixIssueFinding {
        severity: Severity::Error,
        file: rel.to_string(),
        line,
        column,
        value: value.to_string(),
        kind: kind.to_string(),
        message,
    }
}

/// A finding located by an **absolute** line/column in the file.
///
/// For a body-level subject there is no frontmatter key to search for, so
/// [`finding_at`] cannot place it: `## History` is a heading, not a key, and a
/// search for it misses and falls back to line 0 — a diagnostic that underlines
/// the opening `---` while talking about a heading fifty lines down. The caller
/// has already computed the line (`body_start_line` + the body offset), so the
/// value is carried straight through.
pub(super) fn finding_at_line(
    rel: &str,
    line: usize,
    column: usize,
    kind: &str,
    value: &str,
    message: String,
) -> TixIssueFinding {
    TixIssueFinding {
        severity: Severity::Error,
        file: rel.to_string(),
        line,
        column,
        value: value.to_string(),
        kind: kind.to_string(),
        message,
    }
}

/// Mark each line of `body` as inside (`true`) or outside (`false`) a fenced
/// code block.
///
/// A fence opens on a line whose first non-space run is three or more backticks
/// or tildes (```` ``` ````, `~~~`) and closes on a matching run of the same
/// character at least as long, with nothing after it. Only fenced *content*
/// matters here; the fence lines themselves are marked outside, which is
/// harmless because a `## History` heading never looks like a fence.
///
/// This exists so the History scan can tell a **section heading** from a
/// **documented example** of one. Without it, an issue that quotes the History
/// format inside a code block — the natural way to describe this very defect —
/// was reported as if its prose carried a misplaced section.
pub(super) fn fenced_lines(body: &str) -> Vec<bool> {
    let mut flags = Vec::new();
    // The open fence's marker character and the length of its run.
    let mut fence: Option<(char, usize)> = None;
    for line in body.lines() {
        let trimmed = line.trim_start();
        let marker = trimmed.chars().next().filter(|c| *c == '`' || *c == '~');
        let run = marker.map_or(0, |c| trimmed.chars().take_while(|x| *x == c).count());
        flags.push(fence.is_some());
        match fence {
            // A closing fence: same character, at least as long, and the rest of
            // the line blank — the same rule the CommonMark spec uses, so an
            // inline `` ` `` run inside a fence does not close it early.
            Some((c, len)) => {
                if marker == Some(c) && run >= len && trimmed[run..].trim().is_empty() {
                    fence = None;
                }
            }
            None if run >= 3 => fence = marker.map(|c| (c, run)),
            None => {}
        }
    }
    flags
}

/// The 1-based line of `body`'s first line within the whole file `text`.
///
/// `Issue::parse` leaves `body` as a **suffix** of the file — the frontmatter
/// and any leading `## History` section are stripped as a prefix — so the
/// offset is just the length difference, and counting the newlines before it
/// gives the line. A `body` that is somehow not a suffix degrades to line 1
/// rather than panicking (`saturating_sub`).
pub(super) fn body_start_line(text: &str, body: &str) -> usize {
    let start = text.len().saturating_sub(body.len());
    text[..start].matches('\n').count() + 1
}

/// The 1-based line/column of the raw `key:` value inside the frontmatter
/// block (before the closing `---` delimiter), if present.
pub(super) fn locate_value(text: &str, key: &str) -> Option<Located> {
    let prefix = format!("{key}:");
    let fm_end = text[4..].find("\n---").map(|i| i + 4).unwrap_or(text.len());
    let fm = &text[..fm_end];
    let mut line_start = 0usize;
    for (idx, line) in fm.split_inclusive('\n').enumerate() {
        let content = line.trim_end_matches(['\n', '\r']);
        if let Some(rest) = content.trim_start().strip_prefix(&prefix) {
            let pad = content.len() - content.trim_start().len();
            let value_skip = rest.len() - rest.trim_start().len();
            let start = line_start + pad + prefix.len() + value_skip;
            return Some(Located {
                line: idx + 1,
                column: start - line_start + 1,
            });
        }
        line_start += line.len();
    }
    None
}

/// Where a frontmatter value sits, in 1-based line/column terms.
///
/// Only the line and column are carried. Byte offsets used to be here as well, and
/// `span_for` read them — but it re-derived them from a search keyed on the
/// finding's *kind*, which is a diagnostic name rather than a frontmatter key, so
/// it never found anything and the offsets were dead in practice. `span_for` now
/// derives the span from the line and column directly.
pub(super) struct Located {
    pub(super) line: usize,
    pub(super) column: usize,
}

/// A strict `YYYY-MM-DD` calendar-date check (shape + month 1..=12, day
/// 1..=31), so `2026-13-99` is flagged as malformed.
pub(super) fn is_iso_date(s: &str) -> bool {
    let b = s.as_bytes();
    if b.len() != 10 || b[4] != b'-' || b[7] != b'-' {
        return false;
    }
    for &c in &b[0..4] {
        if !c.is_ascii_digit() {
            return false;
        }
    }
    for &c in &[b[5], b[6], b[8], b[9]] {
        if !c.is_ascii_digit() {
            return false;
        }
    }
    let month = u32::from(b[5] - b'0') * 10 + u32::from(b[6] - b'0');
    let day = u32::from(b[8] - b'0') * 10 + u32::from(b[9] - b'0');
    (1..=12).contains(&month) && (1..=31).contains(&day)
}

/// Render one finding as a rustc-style diagnostic (C-004) and return it as a
/// `String`; [`run_with`] prints it to stderr.
///
/// The header names the field and the offending value; the snippet points at the
/// exact line; the annotation label carries the explanation; and a `help:` footer
/// names the remedy for every kind the linter can produce. **Every** finding —
/// error *and* warning — runs through this one renderer, so the severity is
/// expressed by the level, the id prefix, and the colour together, and the output
/// always agrees with the exit code (#1361).
///
/// Returning the string, rather than printing here, keeps the formatting
/// unit-testable without a stderr harness. The `help:` line is what makes the
/// output *actionable*: the fix for most findings is a one-liner the reader
/// cannot infer from the message alone ("valid options: …" says what is wrong,
/// not what to type).
pub(super) fn render_diagnostic(issues_dir: &Path, f: &TixIssueFinding) -> String {
    let title = match f.kind.as_str() {
        "missing" => "missing frontmatter".to_string(),
        "parse" => "parse error".to_string(),
        // The WIP family (WP07): a column over its limit, or an estimate that cannot
        // be counted. Named rather than run through the generic `invalid X value`
        // form, which reads as a frontmatter problem and is not one.
        "over_limit" => "work-in-progress limit exceeded".to_string(),
        "duplicate_number" => "duplicate issue number".to_string(),
        "malformed_estimate" | "missing_conversion" | "ambiguous_conversion" => {
            "estimate cannot be counted".to_string()
        }
        _ => format!("invalid {} value '{}'", f.kind, f.value),
    };
    // A warning must not be **rendered** as an error either (#1361). The level, the
    // id prefix, and the colour all follow the severity, so the output agrees with
    // the exit code.
    let id = match f.severity {
        Severity::Error => "E-tix-lint",
        Severity::Warning => "W-tix-lint",
    };
    let mut diagnostic = match f.severity {
        Severity::Error => Diagnostic::error(id, title),
        Severity::Warning => Diagnostic::warning(id, title),
    };
    let path = issues_dir.join(&f.file);
    match fs::read_to_string(&path) {
        Ok(text) if !f.file.is_empty() => {
            diagnostic = diagnostic
                .at(&path, span_for(f, &text))
                .labelled(&f.message);
        }
        // No source to point at — a configuration finding, or a diagnostic with no
        // single subject, or a file that vanished between the walk and the render.
        // The explanation rides as a `note:` so it is never dropped: folding it into
        // the title (what this branch used to do) lost the sentence for exactly the
        // finding the reader needed it for.
        _ if !f.message.is_empty() => {
            let note = if f.file.is_empty() {
                f.message.clone()
            } else {
                format!("{}: {}", f.file, f.message)
            };
            diagnostic = diagnostic.with_note(note);
        }
        _ => {}
    }
    if let Some(help) = diagnostic_help(&f.kind) {
        diagnostic = diagnostic.with_help(help);
    }
    diagnostic.render_auto()
}

/// The one-line remedy for a finding kind, rendered as a `help:` footer.
///
/// Every kind the linter can emit has an entry here, so no diagnostic ever ends
/// without telling the reader what to do about it. The annotation already says
/// *what* is wrong and, where relevant, *which values are valid*; this says which
/// edit makes it right. `None` is reserved for a kind added without a remedy,
/// which is a bug the totality test (`every_finding_kind_has_a_help_line`) makes
/// visible.
pub(super) fn diagnostic_help(kind: &str) -> Option<&'static str> {
    Some(match kind {
        // Per-issue frontmatter values.
        "status" => "set `status:` to one of the board's configured columns",
        "priority" => "use `''` (unset), `low`, `medium`, or `high`",
        "title" => "give the issue a non-empty `title:`",
        "unknown_type" => "add the type to `types` in tix.toml, or fix the spelling",
        "created" | "updated" => "use `YYYY-MM-DD`, e.g. `2026-10-06`",
        "estimate" => {
            "use a duration, e.g. `estimate: 3`, `estimate: 1 day`, or `estimate: 0.5-1 day`"
        }
        "unknown_key" => "declare it in `[custom_attributes]` in tix.toml, or remove it",
        "cycles" => "create it with `tix cycle create`, or fix the name",
        "milestones" => "create it with `tix milestone create`, or fix the name",
        "start_date" | "due_date" => {
            "use `YYYY-MM-DD`, and keep `due_date` on or after `start_date`"
        }
        "history" => {
            "keep one `## History` section as the first block of the body, with U+2014 \
             em-dash separators between the fields"
        }
        // Related-issue references.
        "related_issue_empty" => "remove the empty entry, or name an issue",
        "related_issue_unresolved" => {
            "point at an issue in this store; paths and URLs are accepted verbatim"
        }
        // Whole-file findings.
        "missing" => "add frontmatter delimited by `---` at the top of the file",
        "parse" => "fix the parse error named on the annotation",
        "layout_mismatch" => "run `tix layout migrate`",
        "duplicate_number" => {
            "renumber one file above the highest number and update every `parent:`, \
             relationship edge and link that named it; lint does not renumber"
        }
        "foreign_repo_not_linted" => "check the path in `related_issues`",
        // Typed relationships.
        "retired_links_key" => "recreate the links with `tix link`, then delete the `links:` key",
        "self_link" => "a relationship cannot point at its own issue",
        "missing_target" => "name an issue that exists",
        "ambiguous_target" => "replace the numeric alias with one canonical issue id",
        "duplicate_identity" => "give each issue a distinct 8-character canonical id",
        "conflicting_edge" => "keep one edge per pair, or use `related` for a plain link",
        "unknown_kind" => "use one of: `blocks`, `duplicates`, `related`",
        "unknown_relation" => "run `tix link list` to see the stored relationship ids",
        // Parent hierarchy.
        "self_parent" => "clear `parent:`, or point it at a different issue",
        "unresolved_parent" | "unknown_parent" => {
            "point `parent:` at an issue that exists, or clear it with `tix edit --parent ''`"
        }
        // Project associations and an epic record's project references (WP09 item A).
        // One kind, two holders: an issue association or an epic's `projects` field.
        "missing_project_reference" => {
            "point the association at a live project, or remove the dangling id with \
             `tix project remove <id> <issue>` / `tix epic edit`"
        }
        // The epic reference family (WP09 item A). One kind per failing reference
        // kind the service diagnoses.
        "missing_epic_reference" => {
            "recreate the epic, drop the reference with `tix epic remove <id> <sel>`, \
             or clear the parent with `tix epic edit <id> --parent ''`"
        }
        "missing_issue_reference" => {
            "remove the malformed entry from `epics:`, or replace it with an epic id"
        }
        "missing_milestone_reference" => {
            "create it with `tix milestone create`, or clear the epic's milestone"
        }
        "missing_cycle_reference" => "create it with `tix cycle create`, or clear the epic's cycle",
        // Workflow configuration and policy.
        "unmapped_column_default" => {
            "optional: add a `[kanban.<board>.category_map]` table to silence this"
        }
        "direct_edit_policy_violation" => {
            "resolve the contradiction yourself — `tix lint` never edits the file"
        }
        "unknown_column" => "use a column the board configures",
        "invalid_transition" => "run `tix workflow show` to see the permitted transitions",
        "missing_completion_category" => {
            "map a column to `completed` in the board's `category_map`"
        }
        "unknown_category" => "use a category from `tix workflow categories`",
        "mapping_for_unknown_column" => "map only columns the board configures",
        // `cycle` is shared by the relationship and hierarchy passes.
        "cycle" => "break the loop by removing one edge",
        _ => return None,
    })
}

/// The byte span (into the full file text) the diagnostic points at.
pub(super) fn span_for(f: &TixIssueFinding, text: &str) -> Range<usize> {
    if f.line > 0 {
        // Derived from the finding's **own** line and column, not by searching the
        // text again for a key.
        //
        // The previous version re-ran `locate_value(text, &f.kind)`, which is
        // wrong twice over for a relationship finding: the kind is a *diagnostic*
        // name (`self_link`, `retired_links_key`, `conflicting_edge`) and not a
        // frontmatter key, so the search always missed and fell through to
        // `0..text.len()` — the whole file underlined from line 1. The finding's
        // `line`/`column` were already correct; they were simply being ignored in
        // favour of a second, wrong answer.
        //
        // A finding could also point at a *body* line, which a frontmatter search
        // could never find, so deriving the span is also the only version that
        // works for a body-level diagnostic.
        let mut line_start = 0usize;
        for (idx, line) in text.split_inclusive('\n').enumerate() {
            if idx + 1 == f.line {
                let start = line_start + (f.column - 1).min(line.len());
                let end = line_start + line.trim_end_matches(['\n', '\r']).len();
                return start..end.max(start);
            }
            line_start += line.len();
        }
        // The recorded line is not in the text — a stale finding, or a file that
        // changed under us. Annotate the first line rather than the whole file,
        // which is what the file-level branch below does and is a better guess
        // than underlining everything.
        let first = text.lines().next().map(str::len).unwrap_or(0);
        return 0..if first > 0 { first } else { text.len() };
    }
    // File-level findings (missing/parse) annotate the first line.
    let first = text.lines().next().map(str::len).unwrap_or(0);
    0..if first > 0 { first } else { text.len() }
}