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
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
#[allow(clippy::wildcard_imports)]
use super::*;
use std::fs;
use tempfile::TempDir;

fn make_store() -> (TempDir, Store) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(&dir).unwrap();
    let config_path = tmp.path().join("tix.toml");
    let config = crate::config::Config {
        issues_dir: dir.clone(),
        milestones_dir: Some(tmp.path().join("docs/milestones")),
        ..crate::config::Config::default()
    };
    config.save(&config_path).unwrap();
    let config = crate::config::Config::load_with_warning(&config_path, |_| {}).unwrap();
    (
        tmp,
        Store {
            issues_dir: dir,
            config,
        },
    )
}

/// Seed one milestone into the store's configured milestones dir.
fn seed_milestone(store: &Store, name: &str) {
    crate::planning::Planner::from_config(store.config.clone(), std::path::PathBuf::new())
        .create_milestone_file(name, None, None)
        .unwrap();
}

fn write(store: &Store, name: &str, contents: &str) {
    if let Some(dir) = name.rsplit_once('/').map(|(d, _)| d) {
        fs::create_dir_all(store.issues_dir.join(dir)).unwrap();
    }
    fs::write(store.issues_dir.join(name), contents).unwrap();
}

const CLEAN: &str = "---\nnumber: 1\ntitle: \"A clean issue\"\nstatus: todo\npriority: medium\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody.\n";

/// Findings that set the exit code.
fn errors(findings: &[TixIssueFinding]) -> Vec<&TixIssueFinding> {
    findings
        .iter()
        .filter(|f| f.severity == Severity::Error)
        .collect()
}

#[test]
fn collect_reports_no_error_on_a_clean_store() {
    // WP06: this test used to assert `findings.is_empty()`, and that premise is
    // now false **by design**. T026 step 3 requires `unmapped_column_default` for
    // every column relying on the safe default, and the default board has four,
    // so a repository that has never configured a `category_map` — which is
    // every repository, including this one — now reports four warnings.
    //
    // "Clean" therefore means "no finding that sets the exit code". The warnings
    // are asserted separately, by
    // `the_safe_default_is_reported_as_a_warning_not_an_error`.
    let (tmp, store) = make_store();
    let _ = tmp;
    write(&store, "alice/2026-01-01-clean.md", CLEAN);
    let findings = collect(&store.config, &store).unwrap();
    assert_eq!(errors(&findings).len(), 0, "errors: {findings:#?}");
}

#[test]
fn duplicate_numbers_are_errors_on_every_file_that_shares_them() {
    let (tmp, store) = make_store();
    let _ = tmp;
    let first = CLEAN.replace("number: 1", "number: 7");
    let second = CLEAN
        .replace("number: 1", "number: 7")
        .replace("A clean issue", "Another issue");
    write(&store, "alice/2026-01-01-a.md", &first);
    write(&store, "bob/2026-01-02-b.md", &second);

    let findings = collect(&store.config, &store).unwrap();
    let duplicates: Vec<&TixIssueFinding> = findings
        .iter()
        .filter(|f| f.kind == "duplicate_number")
        .collect();
    assert_eq!(duplicates.len(), 2, "one finding per involved file");
    for finding in duplicates {
        assert_eq!(finding.severity, Severity::Error);
        assert_eq!(finding.value, "7");
        assert!(finding.line > 0, "the finding points at the `number:` line");
        assert!(
            finding.message.contains("alice/2026-01-01-a.md")
                && finding.message.contains("bob/2026-01-02-b.md"),
            "the message names every file in the group: {}",
            finding.message
        );
    }
    assert_eq!(errors(&findings).len(), 2);
}

#[test]
fn distinct_numbers_are_not_duplicate_findings() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write(&store, "alice/2026-01-01-a.md", CLEAN);
    let second = CLEAN
        .replace("number: 1", "number: 2")
        .replace("A clean issue", "Another issue");
    write(&store, "bob/2026-01-02-b.md", &second);

    let findings = collect(&store.config, &store).unwrap();
    assert!(
        !findings.iter().any(|f| f.kind == "duplicate_number"),
        "distinct numbers are not a collision: {findings:#?}"
    );
}

#[test]
fn an_unset_priority_is_accepted_but_a_typo_is_still_reported() {
    // `priority: ''` means "no priority", which is a statement the author
    // made, not a value they failed to supply. It is exempt from the
    // unknown-priority check. The exemption is for the empty string *only*,
    // so this test asserts both halves: the empty string is clean, and every
    // neighbouring near-miss is still reported. An exemption written as
    // "ignore priorities we do not recognise" would silence all of them.
    let (tmp, store) = make_store();
    let _ = tmp;
    for (i, value) in ["''", "'hih'", "'urgent'", "'Medium '", "'0'"]
        .iter()
        .enumerate()
    {
        write(
            &store,
            &format!("alice/2026-01-01-p{i}.md"),
            &format!(
                "---\nnumber: {}\ntitle: \"P{i}\"\nstatus: todo\npriority: {value}\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody.\n",
                i as u32 + 10
            ),
        );
    }
    let findings = collect(&store.config, &store).unwrap();
    let priority_findings: Vec<&str> = findings
        .iter()
        .filter(|f| f.kind == "priority")
        .map(|f| f.value.as_str())
        .collect();

    assert!(
        !priority_findings.contains(&""),
        "an unset priority is not an error: {findings:?}"
    );
    for typo in ["hih", "urgent", "Medium ", "0"] {
        assert!(
            priority_findings.contains(&typo),
            "{typo:?} must still be reported, got {priority_findings:?}"
        );
    }
}

#[test]
fn collect_flags_invalid_status_and_priority() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write(
        &store,
        "alice/2026-01-01-broken.md",
        "---\nnumber: 2\ntitle: \"Broken\"\nstatus: shipped\npriority: critical\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody.\n",
    );
    let findings = collect(&store.config, &store).unwrap();
    let kinds: Vec<&str> = findings.iter().map(|f| f.kind.as_str()).collect();
    assert!(
        kinds.contains(&"status"),
        "unknown status must be flagged, got {kinds:?}"
    );
    assert!(
        kinds.contains(&"priority"),
        "unknown priority must be flagged, got {kinds:?}"
    );
    assert!(
        findings.iter().any(|f| f.kind == "status"
            && f.message
                .contains("valid options: todo, in progress, in review, done")),
        "status finding must name the valid set, got {findings:?}"
    );
}

#[test]
fn collect_flags_an_unrecognised_history_entry_left_in_the_body() {
    // The body-scan that reports these is only reachable when the line really
    // is in the body. The previous fixture had a `## History` section whose
    // sole line was ASCII-hyphen, which the parser does not recognise — so
    // the section was empty, the line landed in the body, and the finding
    // came from the `unparsed()` loop instead. Removing the entire body-scan
    // left the test green: it never exercised the code it was named for.
    //
    // The case where the line is unambiguously body text: there is no
    // `## History` section at all, so nothing can put it inside one. The
    // companion case — a trailing bullet after the last real event — is
    // *retained* in the section rather than reaching the body, and is covered
    // by `a_trailing_bullet_after_the_last_event_is_retained_and_reported`.
    let (tmp, store) = make_store();
    let _ = tmp;
    write(
        &store,
        "alice/2026-01-01-no-history-section.md",
        concat!(
            "---\nnumber: 3\ntitle: \"H\"\nstatus: todo\npriority: medium\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\n",
            "## Notes\n",
            "\n",
            "- 2026-01-01T00:00:00Z - alice - relationship_added - ascii hyphens\n",
        ),
    );
    let issue = store.get(crate::storage::IssueSelector::Number(3)).unwrap();
    // Explicit precondition, because this test used to pass for the wrong
    // reason: its old fixture's finding came from the `unparsed()` loop, so
    // deleting the whole body-scan left it green.
    assert!(
        issue
            .body
            .contains("- 2026-01-01T00:00:00Z - alice - relationship_added"),
        "precondition — the line must really be body text, got {:?}",
        issue.body
    );

    let findings = collect(&store.config, &store).unwrap();
    let flagged: Vec<_> = findings.iter().filter(|f| f.kind == "history").collect();
    assert_eq!(flagged.len(), 1, "exactly one finding, {findings:?}");
    assert!(
        flagged[0].message.contains("em-dash"),
        "and it says what is wrong: {}",
        flagged[0].message
    );
}

#[test]
fn lint_does_not_flag_ordinary_body_bullets() {
    // The mirror case, so the diagnostic cannot become noise: prose bullets
    // must stay silent.
    //
    // Cycle-4 F5 widened this list considerably. The first version of the
    // reporting predicate accepted any 10-character run of digits, dashes
    // and punctuation, so `tix lint` — which runs on every issue, on every
    // invocation — told authors to use em-dash separators on schedule
    // windows, phone numbers, version strings and bare ticket numbers. The
    // two bullets this test originally used (`- Reproduction: run it`,
    // `- Expected: it works`) cannot trip that heuristic, so the test was
    // green throughout and the noise was invisible to it.
    let (tmp, store) = make_store();
    let _ = tmp;
    let bullets = [
        "- Reproduction: run it",
        "- Expected: it works",
        "- 10:00-11:00 sync with infra",
        "- 10:00:00.000 elapsed before the timeout",
        "- 1234567890 is the upstream ticket",
        "- +49-30-12345678 is the hotline",
        "- 1.2.3.4.5.6 shipped",
        "- ----------",
        "- 2026-02-02: review the migration",
        "- 2026-01-01..2026-01-05 was the freeze",
        "- 2026-02-02 review the migration",
        // Cycle-5 Blocker 3: three hyphen-separated fields after a date is a
        // changelog line, not a mistyped entry. A version that required only
        // three total fields flagged every one of these, and `tix lint` exits
        // non-zero — so this is a failing lint on ordinary prose, not a
        // cosmetic nit. Four fields is what the format specifies.
        "- 2026-01-01 - owner - status",
        "- 2026-01-01 - Bob - Done",
        "- 2026-01-02 - alice - reviewed",
        "- 2026-01-01 - start - end",
        "- 2026-01-01 - v1.2 - released",
    ];
    for (i, bullet) in bullets.iter().enumerate() {
        write(
            &store,
            &format!("alice/2026-01-01-b{i}.md"),
            &format!(
                "---\nnumber: {}\ntitle: \"B{i}\"\nstatus: todo\npriority: medium\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\n## Notes\n\n{bullet}\n",
                i as u32 + 4
            ),
        );
    }
    let findings = collect(&store.config, &store).unwrap();
    assert!(
        !findings.iter().any(|f| f.kind == "history"),
        "ordinary prose must not be reported: {findings:?}"
    );
}

#[test]
fn a_trailing_bullet_after_the_last_event_is_retained_and_reported() {
    // The other side of cycle-4 F1's fix, and the trade it makes explicitly.
    //
    // A `- ` bullet with no em dash at the *end* of a History section is
    // ambiguous: a hand-edited entry, or body prose. The old rule always
    // called it prose, which meant an ordinary command could delete the
    // `## History` heading, demote the line into the body, and render the
    // next append *above* it — with lint silent, because a demoted line is
    // body prose and the unparsed loop no longer sees it.
    //
    // The new rule retains it, and retention is *reported*, so the failure
    // mode is disclosed rather than silent. N1's actual trigger — several
    // body bullets in a row — is unaffected: the second one disqualifies the
    // first, so the section ends where it should and both stay body text.
    for (name, body) in [
        (
            "dated-typo",
            concat!(
                "## History\n",
                "\n",
                "- 2026-01-01T00:00:00Z \u{2014} alice \u{2014} relationship_added \u{2014} real\n",
                "\n",
                "- 2026-02-02T00:00:00Z - alice - relationship_added - ascii\n",
            ),
        ),
        (
            "after-a-real-event",
            concat!(
                "## History\n",
                "\n",
                "- 2026-01-01T00:00:00Z \u{2014} alice \u{2014} relationship_added \u{2014} real\n",
                "\n",
                "- 2026-02-02 review the migration\n",
            ),
        ),
    ] {
        let (tmp, store) = make_store();
        let _ = tmp;
        write(
            &store,
            &format!("alice/2026-01-01-{name}.md"),
            &format!(
                "---\nnumber: 3\ntitle: \"H\"\nstatus: todo\npriority: medium\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\n{body}"
            ),
        );
        let issue = store.get(crate::storage::IssueSelector::Number(3)).unwrap();
        assert_eq!(
            issue.history.unparsed().len(),
            1,
            "{name}: retained in the section, not demoted — {:?}",
            issue.history.unparsed()
        );
        assert!(
            issue.body.is_empty(),
            "{name}: and nothing moved into the body, got {:?}",
            issue.body
        );
        let findings = collect(&store.config, &store).unwrap();
        assert!(
            findings.iter().any(|f| f.kind == "history"),
            "{name}: and the retention is reported, not silent — {findings:?}"
        );
    }
}

#[test]
fn lint_flags_the_hand_typing_errors_it_exists_to_catch() {
    // The mirror of the test above, and the reason its earlier version was
    // worth little: a negative test alone cannot tell you the diagnostic
    // still works. Every case here is a real way a hand mistypes an entry
    // with ASCII hyphens — including the two forms the previous
    // implementation missed, because it required the literal `" - "` and a
    // bare `- ` marker while the recognition path accepted both.
    for line in [
        // The canonical typo.
        "- 2026-01-01T00:00:00Z - alice - relationship_added - detail",
        // No spaces around the separators: the same mistake without them.
        "- 2026-01-01T00:00:00Z-alice-relationship_added-detail",
        // A date-only timestamp, and a hand-typed zone offset.
        "- 2026-01-01 - alice - relationship_added - detail",
        "- 2026-01-01T00:00:00+02:00 - alice - relationship_added - detail",
        // Extra whitespace after the marker. `HistoryEvent::parse` strips
        // `- ` and then trims each field, so with em-dash separators this is
        // recognised as a real entry — the asymmetry that made its hyphen
        // equivalent silently unreported.
        //
        // A *tab* marker is deliberately absent from this list:
        // `HistoryEvent::parse` requires `- ` too, so `-\t…` is outside the
        // format on the recognition path as well. That is consistent, not
        // asymmetric, and widening it would be a format change.
        "-  2026-01-01T00:00:00Z - alice - relationship_added - detail",
        "   - 2026-01-01T00:00:00Z - alice - relationship_added - detail",
        // Every accepted list marker, not just `- `.
        "* 2026-01-01T00:00:00Z - alice - relationship_added - detail",
        "+ 2026-01-01T00:00:00Z - alice - relationship_added - detail",
        "1. 2026-01-01T00:00:00Z - alice - relationship_added - detail",
    ] {
        assert!(
            crate::model::looks_like_an_unrecognised_entry(line),
            "{line:?} must be reported — it is a mistyped entry"
        );
    }

    // And end to end, so this is not only a predicate test.
    let (tmp, store) = make_store();
    let _ = tmp;
    write(
        &store,
        "alice/2026-01-01-typo.md",
        concat!(
            "---\nnumber: 9\ntitle: \"T\"\nstatus: todo\npriority: medium\n",
            "created: 2026-01-01\nupdated: 2026-01-01\n---\n\n## Notes\n\n",
            "- 2026-01-01T00:00:00Z-alice-relationship_added-detail\n",
        ),
    );
    let findings = collect(&store.config, &store).unwrap();
    assert!(
        findings.iter().any(|f| f.kind == "history"),
        "the no-space form reaches the user: {findings:?}"
    );
}

// ---- WP06 T025/T026: the relationship sweep ----

/// An empty `links` is not a finding — only a *populated* one has data the
/// typed model can no longer read.
///
/// Reporting mere presence made `tix lint` reject every issue file this
/// repository has ever written (they all carry a `links: []` from the old
/// model), with no way to make them valid short of hand-editing every file,
/// because the mission provides no migration for the key.
/// Write one issue file, verbatim, so a test can seed a relationship the
/// write path would refuse to create. That is the whole point: lint observes
/// on-disk data, and the interesting on-disk data is exactly what the command
/// layer rejects.
fn seed(dir: &Store, number: u32, relationships: &str) {
    let block = if relationships.is_empty() {
        String::new()
    } else {
        format!("relationships:\n{relationships}")
    };
    let text = format!(
        "---\nnumber: {number}\ntitle: T{number}\nstatus: todo\npriority: medium\n\
         labels: []\n{block}created: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody {number}.\n"
    );
    fs::write(
        dir.issues_dir.join(format!("2026-01-01-t{number}.md")),
        text,
    )
    .unwrap();
}

fn rel_findings(findings: &[TixIssueFinding]) -> Vec<&TixIssueFinding> {
    findings
        .iter()
        .filter(|f| {
            matches!(
                f.kind.as_str(),
                "self_link"
                    | "missing_target"
                    | "conflicting_edge"
                    | "cycle"
                    | "unknown_kind"
                    | "unknown_relation"
                    | "retired_links_key"
            )
        })
        .collect()
}

/// One seeded case per diagnostic kind that can exist in stored data.
///
/// **Five of the seven, not seven** — and the reason is structural, not an
/// omission. `unknown_kind` and `unknown_relation` are *write-time*
/// diagnostics: a stored edge's kind is deserialised into the closed
/// `RelationKind` vocabulary, so an unknown kind makes the file fail to parse
/// (reported as `parse`, before any graph exists), and a stored relationship
/// has its id by construction so an unresolvable id cannot be stored either.
/// Both are reachable and correctly named on the write path —
/// `tix link 0 1 --type sideways` and `tix link edit rel_NOPE` — and pinning
/// them here would mean asserting something unreachable. T025 step 3 asks for
/// all seven to "surface here"; that is not satisfiable, and saying so is
/// more useful than a test that seeds a fixture the parser cannot load.
#[test]
fn every_storable_relationship_diagnostic_surfaces() {
    let cases: Vec<(&str, &str, &str)> = vec![
        (
            "self_link",
            "  - id: r1\n    from: 1\n    to: 1\n    kind: blocks\n    display: \"x\"\n",
            "cannot block itself",
        ),
        (
            "missing_target",
            "  - id: r1\n    from: 1\n    to: 99\n    kind: blocks\n    display: \"x\"\n",
            "resolves to no issue",
        ),
        (
            "conflicting_edge",
            "  - id: r1\n    from: 1\n    to: 2\n    kind: blocks\n    display: \"x\"\n  \
             - id: r2\n    from: 1\n    to: 2\n    kind: related\n    display: \"y\"\n",
            "refusing to store it as",
        ),
        ("retired_links_key", "", "retired `links:` key"),
    ];
    for (kind, relationships, phrase) in cases.iter() {
        let (tmp, store) = make_store();
        let _ = tmp;
        seed(&store, 1, relationships);
        // Issue 2 must exist, or every edge to it is a *missing target* and
        // the case under test never gets to be the thing that is reported.
        seed(&store, 2, "");
        if *kind == "retired_links_key" {
            let f = store.issues_dir.join("2026-01-01-t1.md");
            let text = fs::read_to_string(&f).unwrap();
            fs::write(
                &f,
                text.replacen("created: ", "links:\n- '2'\ncreated: ", 1),
            )
            .unwrap();
        }
        let findings = collect(&store.config, &store).unwrap();
        let rels = rel_findings(&findings);
        assert!(
            rels.iter().any(|f| f.kind == *kind),
            "{kind} must surface; got {:?}",
            rels.iter().map(|f| f.kind.clone()).collect::<Vec<_>>()
        );
        let hit = rels.iter().find(|f| f.kind == *kind).unwrap();
        assert!(
            hit.message.contains(phrase),
            "{kind}: the message must explain the problem: {}",
            hit.message
        );
        // And the finding points at the file, not at the store root.
        assert_eq!(hit.file, "2026-01-01-t1.md", "{kind} must name its file");
        // …and at the offending **key**, not at the first line of the file.
        // A finding whose `line` is 0 renders as a file-level block with a
        // caret under line 1, which points at nothing in particular — and it
        // is what happens when the contract name (`retired_links_key`) is
        // passed as the key to search for instead of the key the diagnostic
        // names (`links`). The distinction is invisible unless asserted.
        assert!(
            hit.line > 0,
            "{kind} must point at the offending key, not at line 1: {hit:?}"
        );
    }
}

/// A cycle, which cannot be created through the command layer at all —
/// `tix link` refuses it — and so exists only on disk.
#[test]
fn a_cycle_on_disk_is_reported_once() {
    let (tmp, store) = make_store();
    let _ = tmp;
    seed(
        &store,
        1,
        "  - id: r1\n    from: 1\n    to: 2\n    kind: blocks\n    display: \"x\"\n",
    );
    seed(
        &store,
        2,
        "  - id: r2\n    from: 2\n    to: 1\n    kind: blocks\n    display: \"y\"\n",
    );
    let findings = collect(&store.config, &store).unwrap();
    let cycles: Vec<&TixIssueFinding> = rel_findings(&findings)
        .into_iter()
        .filter(|f| f.kind == "cycle")
        .collect();
    assert_eq!(
        cycles.len(),
        1,
        "one cycle, one finding \u{2014} not one per blocked issue: {:?}",
        rel_findings(&findings)
            .iter()
            .map(|f| (f.kind.clone(), f.message.clone()))
            .collect::<Vec<_>>()
    );
    // The message names the whole cycle, so the finding is not misleading
    // about its scope even though it is attributed to one file.
    assert!(
        cycles[0].message.contains("->"),
        "the cycle must be rendered: {}",
        cycles[0].message
    );
}

/// A clean tree says nothing (T026 step 4).
#[test]
fn a_clean_tree_reports_no_relationship_findings() {
    let (tmp, store) = make_store();
    let _ = tmp;
    // `1 blocks 2` and `2 blocks 3`: a legitimate chain, no cycle. Note that
    // `2 related 1` would *not* be a clean fixture — `related` is
    // order-normalised, so it canonicalises to `1 related 2` and collides with
    // the blocks edge, which is a real `conflicting_edge` and not a mistake.
    seed(
        &store,
        1,
        "  - id: r1\n    from: 1\n    to: 2\n    kind: blocks\n    display: \"x\"\n",
    );
    seed(
        &store,
        2,
        "  - id: r2\n    from: 2\n    to: 3\n    kind: blocks\n    display: \"y\"\n",
    );
    seed(&store, 3, "");
    let findings = collect(&store.config, &store).unwrap();
    assert!(
        rel_findings(&findings).is_empty(),
        "a valid graph is silent: {:?}",
        rel_findings(&findings)
    );
}

/// Three distinct problems, three findings — not one, not five (T026 steps 3
/// and 5).
#[test]
fn three_seeded_problems_report_exactly_three_findings() {
    let (tmp, store) = make_store();
    let _ = tmp;
    seed(
        &store,
        1,
        "  - id: r1\n    from: 1\n    to: 1\n    kind: blocks\n    display: \"x\"\n",
    );
    seed(
        &store,
        2,
        "  - id: r2\n    from: 2\n    to: 98\n    kind: blocks\n    display: \"y\"\n",
    );
    seed(
        &store,
        3,
        "  - id: r3\n    from: 3\n    to: 4\n    kind: blocks\n    display: \"z\"\n",
    );
    seed(
        &store,
        4,
        "  - id: r4\n    from: 4\n    to: 3\n    kind: blocks\n    display: \"w\"\n",
    );
    // And a retired key, so the count is not just the three graph rules.
    let f = store.issues_dir.join("2026-01-01-t1.md");
    let text = fs::read_to_string(&f).unwrap();
    fs::write(
        &f,
        text.replacen("created: ", "links:\n- '2'\ncreated: ", 1),
    )
    .unwrap();

    let findings = collect(&store.config, &store).unwrap();
    let rels = rel_findings(&findings);
    let mut kinds: Vec<&str> = rels.iter().map(|f| f.kind.as_str()).collect();
    kinds.sort_unstable();
    assert_eq!(
        kinds,
        vec!["cycle", "missing_target", "retired_links_key", "self_link"],
        "each root cause once, and nothing implied: {kinds:?}"
    );
}

/// The sweep is **one** pass, not one per issue (T026 step 1).
///
/// Asserted structurally rather than by timing: `validate_snapshot` is the
/// only source of relationship findings, it is called exactly once, and the
/// graph it is called on is built from the walk's own output rather than from
/// `Store::list` — which is the thing that would have made this quadratic and
/// would have aborted on a malformed file.
#[test]
fn the_sweep_does_not_re_read_the_tree_through_store_list() {
    let source = concat!(
        include_str!("../collect.rs"),
        include_str!("../validate.rs")
    );
    let body = &source[source.find("fn collect_relationships").unwrap()
        ..source.find("fn collect_for_file").unwrap()];
    assert!(
        !body.contains("store.list()") && !body.contains("graph_source("),
        "the sweep must graph the tolerant walk's output, not re-read the tree"
    );
}

/// A malformed file must not stop the sweep (FR-018).
///
/// This is the regression test for a defect introduced and caught inside this
/// work package: the first version of the sweep called
/// `store.graph_source()`, whose `list()` aborts on the first malformed file,
/// so one broken file made `tix lint` exit 2 with an internal error and
/// reported **no** relationship problem anywhere in the tree.
#[test]
fn a_malformed_file_does_not_stop_the_relationship_sweep() {
    let (tmp, store) = make_store();
    let _ = tmp;
    seed(
        &store,
        1,
        "  - id: r1\n    from: 1\n    to: 1\n    kind: blocks\n    display: \"x\"\n",
    );
    // A file that cannot be parsed at all.
    fs::write(
        store.issues_dir.join("2026-01-01-broken.md"),
        "---\nnumber: 99\ntitle: Broken\nstatus: [not, a, string]\n---\n\nBody.\n",
    )
    .unwrap();

    let findings = collect(&store.config, &store).unwrap();
    assert!(
        findings.iter().any(|f| f.kind == "parse"),
        "the malformed file is still reported as `parse`: {:?}",
        findings.iter().map(|f| f.kind.clone()).collect::<Vec<_>>()
    );
    assert!(
        rel_findings(&findings)
            .iter()
            .any(|f| f.kind == "self_link"),
        "and the sweep still runs, finding the self-link in another file: {:?}",
        rel_findings(&findings)
    );
}

/// Two runs, byte-identical output (T026 step 2, and the acceptance gate).
#[test]
fn two_runs_over_the_same_tree_agree_exactly() {
    let (tmp, store) = make_store();
    let _ = tmp;
    seed(
        &store,
        1,
        "  - id: r1\n    from: 1\n    to: 1\n    kind: blocks\n    display: \"x\"\n",
    );
    seed(
        &store,
        2,
        "  - id: r2\n    from: 2\n    to: 97\n    kind: blocks\n    display: \"y\"\n",
    );
    seed(
        &store,
        3,
        "  - id: r3\n    from: 3\n    to: 4\n    kind: blocks\n    display: \"z\"\n",
    );
    seed(
        &store,
        4,
        "  - id: r4\n    from: 4\n    to: 3\n    kind: blocks\n    display: \"w\"\n",
    );
    let render = |findings: &[TixIssueFinding]| {
        findings
            .iter()
            .map(|f| format!("{}|{}|{}|{}", f.file, f.kind, f.value, f.message))
            .collect::<Vec<_>>()
    };
    let first = render(&collect(&store.config, &store).unwrap());
    let second = render(&collect(&store.config, &store).unwrap());
    assert_eq!(first, second, "two runs must produce identical output");
    assert!(
        !first.is_empty(),
        "and the fixture must actually find something"
    );
}

/// The **rendered** diagnostic points at the offending line.
///
/// The struct fields were already correct, and asserting them proved nothing
/// about what the user sees: `span_for` re-searched the text for a key named
/// after the finding's *kind* — `self_link`, `retired_links_key` — which is
/// not a frontmatter key, so every relationship finding fell through to
/// `0..text.len()` and the CLI underlined the whole file from line 1. The MCP
/// `lint_issues` output was right the whole time, so only the CLI surface was
/// wrong, and only the rendered form showed it.
#[test]
fn a_relationship_finding_underlines_the_offending_line_not_the_file() {
    let (tmp, store) = make_store();
    let _ = tmp;
    seed(
        &store,
        1,
        "  - id: r1\n    from: 1\n    to: 1\n    kind: blocks\n    display: \"x\"\n",
    );
    seed(&store, 2, "");
    let findings = collect(&store.config, &store).unwrap();
    let finding = rel_findings(&findings)
        .into_iter()
        .find(|f| f.kind == "self_link")
        .expect("a self_link finding");
    let text = fs::read_to_string(store.issues_dir.join(&finding.file)).unwrap();
    let span = span_for(finding, &text);
    let line_no = text[..span.start].lines().count().max(1);
    assert_eq!(
        line_no, finding.line,
        "the span must start on the line the finding recorded"
    );
    assert!(
        span.end <= text.len() && span.end > span.start,
        "and must be a real range inside the file: {span:?} of {} bytes",
        text.len()
    );
    // And it must not have degenerated into the whole file.
    assert!(
        span.end < text.len(),
        "the span must not cover the whole file: {span:?}"
    );
    // The span sits on the line that declares the field the finding names.
    // `TixIssueFinding::value` is the *field* name for a relationship
    // diagnostic — that is what the title reads
    // (`invalid self_link value 'to'`) — while the span covers that field's
    // value. So the check is that the underlined line belongs to the named
    // field, not that the two strings are equal.
    let line_start = text[..span.start].rfind('\n').map(|i| i + 1).unwrap_or(0);
    let line = &text[line_start
        ..text[line_start..]
            .find('\n')
            .map(|i| line_start + i)
            .unwrap_or(text.len())];
    assert!(
        line.trim_start()
            .starts_with(&format!("{}:", finding.value)),
        "the underline must be on the line declaring `{}`, got {line:?}",
        finding.value
    );
    assert!(
        !text[span.clone()].trim().is_empty(),
        "and it must cover that field's value: {span:?}"
    );
}

#[test]
fn an_empty_links_key_is_not_a_finding() {
    let (tmp, store) = make_store();
    let _ = tmp;
    for (i, links) in ["[]", "~", "null", ""].iter().enumerate() {
        let n = 10 + i as u32;
        write(
            &store,
            &format!("alice/2026-01-01-empty-{i}.md"),
            &format!(
                "---\nnumber: {n}\ntitle: \"Empty {i}\"\nstatus: todo\npriority: medium\n\
                 links: {links}\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody.\n"
            ),
        );
    }
    let findings = collect(&store.config, &store).unwrap();
    let retired: Vec<&TixIssueFinding> = findings
        .iter()
        .filter(|f| f.kind == "retired_links_key")
        .collect();
    assert!(
        retired.is_empty(),
        "an empty `links` loses nothing, so it is not a finding: {findings:?}"
    );
}

/// A populated `links` is still a finding, in every shape the old model and a
/// hand-edit can produce.
#[test]
fn a_populated_links_key_is_still_a_finding() {
    let (tmp, store) = make_store();
    let _ = tmp;
    for (i, links) in ["\n- '12'", "\n- 12\n- 13", " ['12']", " [12]", "\n- task-7"]
        .iter()
        .enumerate()
    {
        let n = 20 + i as u32;
        write(
            &store,
            &format!("alice/2026-01-01-full-{i}.md"),
            &format!(
                "---\nnumber: {n}\ntitle: \"Full {i}\"\nstatus: todo\npriority: medium\n\
                 links:{links}\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody.\n"
            ),
        );
    }
    let findings = collect(&store.config, &store).unwrap();
    let retired: Vec<&TixIssueFinding> = findings
        .iter()
        .filter(|f| f.kind == "retired_links_key")
        .collect();
    assert_eq!(
        retired.len(),
        5,
        "every populated shape is reported: {findings:?}"
    );
}

#[test]
fn collect_flags_a_retired_links_key() {
    // The retired `links:` key is reported once, as a whole-field finding.
    // Per-entry value checking is gone with the field: the value is never
    // read as typed data (C-001), so there is nothing to validate entry by
    // entry.
    let (tmp, store) = make_store();
    let _ = tmp;
    write(
        &store,
        "alice/2026-01-01-linked.md",
        "---\nnumber: 3\ntitle: \"Linked\"\nstatus: todo\npriority: medium\nlinks:\n- '12'\n- task-7\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody.\n",
    );
    let findings = collect(&store.config, &store).unwrap();
    let retired: Vec<&TixIssueFinding> = findings
        .iter()
        .filter(|f| f.kind == "retired_links_key")
        .collect();
    assert_eq!(
        retired.len(),
        1,
        "one finding for the retired key: {findings:?}"
    );
    assert_eq!(retired[0].value, "links", "the finding names the field");
    assert!(
        retired[0].message.contains("retired"),
        "the message explains why: {}",
        retired[0].message
    );
    assert!(retired[0].line > 0, "the finding is located in the file");
}

#[test]
fn collect_reports_unparseable_file_as_missing_finding() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write(
        &store,
        "alice/2026-01-01-not-frontmatter.md",
        "Just prose, no frontmatter.\n",
    );
    let findings = collect(&store.config, &store).unwrap();
    // Counted over **errors**, not over all findings: WP06 added the safe-default
    // warnings, so `findings.len()` is now 5 rather than 1 and the count was
    // measuring the default board's column count. An earlier version of this
    // assertion failed with `left: 4, right: 1` — the extra findings were the
    // board's four columns, not anything about the unparseable file.
    let errors = errors(&findings);
    assert_eq!(errors.len(), 1, "{findings:#?}");
    assert_eq!(errors[0].kind, "missing");
    assert_eq!(errors[0].file, "alice/2026-01-01-not-frontmatter.md");
}

#[test]
fn collect_flags_unknown_cycle_and_milestone_with_valid_lists() {
    let (tmp, mut store) = make_store();
    let _ = tmp;
    store.config.cycles.insert(
        "Cycle 1".to_string(),
        crate::config::PlanningCycle::default(),
    );
    seed_milestone(&store, "v1.0");
    write(
        &store,
        "alice/2026-01-01-planning.md",
        "---\nnumber: 4\ntitle: \"Planning\"\nstatus: todo\npriority: medium\ncycles:\n- Nope\n- Cycle 1\nmilestones:\n- v2.0\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody.\n",
    );
    let findings = collect(&store.config, &store).unwrap();
    assert!(
        findings.iter().any(|f| f.kind == "cycles"
            && f.value == "Nope"
            && f.message.contains("valid cycles: Cycle 1")),
        "unknown cycle finding must name the valid set, got {findings:?}"
    );
    assert!(
        findings.iter().any(|f| f.kind == "milestones"
            && f.value == "v2.0"
            && f.message.contains("valid milestones: v1.0")),
        "unknown milestone finding must name the valid set, got {findings:?}"
    );
    assert!(
        findings
            .iter()
            .all(|f| f.kind != "cycles" || f.value != "Cycle 1"),
        "a configured cycle must not be flagged, got {findings:?}"
    );
    assert!(
        findings
            .iter()
            .all(|f| f.kind != "milestones" || f.value != "v1.0"),
        "a registered milestone must not be flagged, got {findings:?}"
    );
}

#[test]
fn collect_flags_unknown_milestone_when_registry_empty() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write(
        &store,
        "alice/2026-01-01-orphan.md",
        "---\nnumber: 5\ntitle: \"Orphan\"\nstatus: todo\npriority: medium\nmilestones:\n- nowhere\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody.\n",
    );
    let findings = collect(&store.config, &store).unwrap();
    assert!(
        findings
            .iter()
            .any(|f| f.kind == "milestones"
                && f.message.contains("valid milestones: none configured")),
        "an empty registry must render as none configured, got {findings:?}"
    );
}

#[test]
fn collect_flags_due_before_start_with_frozen_message() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write(
        &store,
        "alice/2026-01-01-dates.md",
        "---\nnumber: 6\ntitle: \"Dates\"\nstatus: todo\npriority: medium\nstart_date: 2026-09-18\ndue_date: 2026-09-07\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody.\n",
    );
    let findings = collect(&store.config, &store).unwrap();
    assert!(
        findings.iter().any(|f| f.kind == "due_date"
            && f.value == "2026-09-07"
            && f.message == "due_date \"2026-09-07\" must be `>= start_date` \"2026-09-18\""),
        "due-before-start must be flagged with the frozen message, got {findings:?}"
    );
    assert!(
        findings.iter().any(|f| f.kind == "due_date" && f.line > 0),
        "the date finding must be located at the due_date line"
    );
}

#[test]
fn collect_flags_malformed_calendar_date() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write(
        &store,
        "alice/2026-01-01-bad-date.md",
        "---\nnumber: 7\ntitle: \"Bad date\"\nstatus: todo\npriority: medium\nstart_date: 2026-13-99\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody.\n",
    );
    let findings = collect(&store.config, &store).unwrap();
    assert!(
        findings.iter().any(|f| f.kind == "start_date"
            && f.value == "2026-13-99"
            && f.message == "start_date \"2026-13-99\" must be a `YYYY-MM-DD` calendar date"),
        "a non-calendar date must be flagged, got {findings:?}"
    );
}

/// #1308: a `## History` section that is not at the front of the body is
/// reclassified as body text, silently.
///
/// The parser is right — `data-model.md` §8 pins the section to the front —
/// and that is what makes the violation dangerous: the section is not
/// rejected, it is demoted. `tix view` then shows the issue with no audit
/// trail, and the next `tix edit --body` replaces the body wholesale, which
/// deletes the section and every event in it. A plain write preserves it, so
/// the loss arrives later and looks unrelated to the hand-edit that caused
/// it.
///
/// Measured, not inferred: each variant below was driven through the real
/// binary and the whole section was destroyed in every case — not only the
/// 3-field entry this was first filed against.
#[test]
fn a_history_section_that_is_not_at_the_front_of_the_body_is_reported() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write(
        &store,
        "2026-01-01-misplaced.md",
        "---\nnumber: 1\ntitle: \"Misplaced\"\nstatus: todo\npriority: medium\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nSome ordinary paragraph.\n\n## History\n\n* 2026-01-01 \u{2014} alice \u{2014} relationship_added\n",
    );
    let findings = collect(&store.config, &store).unwrap();
    let message = findings
        .iter()
        .find(|f| f.file == "2026-01-01-misplaced.md")
        .map(|f| f.message.clone())
        .expect("a misplaced `## History` section must be reported");
    assert!(
        message.contains("must be the first thing in the body"),
        "names the rule: {message}"
    );
    assert!(
        message.contains("tix edit --body"),
        "names the consequence, so the finding is actionable: {message}"
    );
}

/// The diagnostic must not fire on a correctly placed section, or `tix lint`
/// would report every healthy issue.
#[test]
fn a_history_section_at_the_front_of_the_body_is_not_reported() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write(
        &store,
        "2026-01-01-placed.md",
        "---\nnumber: 1\ntitle: \"Placed\"\nstatus: todo\npriority: medium\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\n## History\n\n- 2026-01-01T00:00:00Z \u{2014} alice \u{2014} relationship_added \u{2014} d\n\nSome ordinary paragraph.\n",
    );
    let findings = collect(&store.config, &store).unwrap();
    assert!(
        !findings
            .iter()
            .any(|f| f.message.contains("first thing in the body")),
        "a well-placed section is not a violation: {findings:?}"
    );
}

/// The lint rule and the parser must agree on which lines are headings, or
/// lint reports violations that do not exist while missing ones that do.
/// `## History   ` is a heading; `   ## History` and `## History\r` are not.
#[test]
fn the_heading_test_matches_the_parser_exactly() {
    for (line, expected) in [
        ("## History", true),
        ("## History ", true),
        ("## History\t", true),
        ("## History \t ", true),
        ("   ## History", false),
        ("## History\r", false),
        ("## History extra", false),
        ("## History:", false),
    ] {
        assert_eq!(crate::model::is_history_heading(line), expected, "{line:?}");
    }
}

/// A `## History` inside a fenced code block is a *documented example*, not a
/// misplaced section. Reporting it flagged every issue that describes the
/// History format — this repository's own mission findings did — so the scan
/// is fence-aware.
#[test]
fn a_fenced_history_heading_is_not_a_misplaced_section() {
    let (tmp, store) = make_store();
    let _ = tmp;
    write(
        &store,
        "2026-01-01-fenced.md",
        "---\nnumber: 1\ntitle: \"Fenced\"\nstatus: todo\npriority: medium\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nAn example file:\n\n```markdown\n## History\n\n- 2026-01-01 - alice - relationship_added\n```\n\nThat is how the section looks.\n",
    );
    let findings = collect(&store.config, &store).unwrap();
    assert!(
        !findings.iter().any(|f| f.file == "2026-01-01-fenced.md"),
        "nothing inside a fence is a section or an entry: {findings:?}"
    );
}

/// The diagnostic points at the misplaced heading, not at line 1. The old
/// `value_finding` path searched for a frontmatter key `history`, missed, and
/// underlined the opening `---` — a span that named the wrong line.
#[test]
fn a_misplaced_history_finding_points_at_the_heading() {
    let (tmp, store) = make_store();
    let _ = tmp;
    let text = "---\nnumber: 1\ntitle: \"Misplaced\"\nstatus: todo\npriority: medium\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nSome ordinary paragraph.\n\n## History\n\n* 2026-01-01 \u{2014} alice \u{2014} relationship_added\n";
    write(&store, "2026-01-01-misplaced.md", text);
    let findings = collect(&store.config, &store).unwrap();
    let finding = findings
        .iter()
        .find(|f| f.message.contains("first thing in the body"))
        .expect("the misplaced heading is reported");
    let heading_line = text
        .lines()
        .position(|line| line == "## History")
        .map(|index| index + 1)
        .unwrap();
    assert_eq!(
        finding.line, heading_line,
        "the span names the heading line, not line 1"
    );
    assert!(finding.column >= 1, "column is 1-based: {}", finding.column);
}

/// Every kind the linter can emit carries a `help:` remedy, so no diagnostic
/// dead-ends without telling the reader what to do. The list is the union of
/// the literal kinds and the three diagnostic enums; it is exhaustive on
/// purpose, so adding a check without a remedy fails here.
#[test]
fn every_finding_kind_has_a_help_line() {
    let literals = [
        "status",
        "title",
        "priority",
        "unknown_type",
        "created",
        "updated",
        "estimate",
        "unknown_key",
        "cycles",
        "milestones",
        "start_date",
        "due_date",
        "history",
        "related_issue_empty",
        "related_issue_unresolved",
        "missing",
        "parse",
        "layout_mismatch",
        "duplicate_number",
        "foreign_repo_not_linted",
        "missing_project_reference",
        "missing_epic_reference",
        "missing_issue_reference",
        "missing_milestone_reference",
        "missing_cycle_reference",
    ];
    let relationships = [
        "self_link",
        "missing_target",
        "conflicting_edge",
        "cycle",
        "unknown_kind",
        "unknown_relation",
        "retired_links_key",
    ];
    let hierarchy = [
        "self_parent",
        "unresolved_parent",
        "cycle",
        "unknown_parent",
    ];
    let workflow = crate::workflow::DiagnosticKind::ALL.map(|kind| kind.as_str());
    for kind in literals
        .iter()
        .copied()
        .chain(workflow)
        .chain(relationships)
        .chain(hierarchy)
    {
        assert!(
            diagnostic_help(kind).is_some(),
            "`{kind}` has no `help:` remedy"
        );
    }
}

/// The renderer is rustc-style `annotate-snippets` output: a severity header
/// with the id, and a `help:` footer naming the fix.
#[test]
fn a_rendered_diagnostic_carries_the_id_and_a_help_footer() {
    let finding = TixIssueFinding {
        severity: Severity::Error,
        file: "issues/x.md".into(),
        line: 0,
        column: 0,
        value: "wip".into(),
        kind: "status".into(),
        message: "valid options: todo, in progress, done".into(),
    };
    let rendered = render_diagnostic(std::path::Path::new("/nonexistent-tix-lint"), &finding);
    assert!(rendered.contains("E-tix-lint"), "{rendered}");
    assert!(
        rendered.contains("invalid status value 'wip'"),
        "{rendered}"
    );
    assert!(
        rendered.contains("set `status:` to one of the board's configured columns"),
        "the remedy is attached: {rendered}"
    );

    let warning = TixIssueFinding {
        severity: Severity::Warning,
        ..finding
    };
    let rendered = render_diagnostic(std::path::Path::new("/nonexistent-tix-lint"), &warning);
    assert!(rendered.contains("W-tix-lint"), "{rendered}");
}