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
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
//! Cross-surface parity for workflow transitions — NFR-002, C-003, C-004, C-005,
//! NFR-001, NFR-003.
//!
//! WP09. The other work packages proved each surface *individually*. This one exists
//! because the mission's central claim is not per-surface but **between** them: "100%
//! of transition paths use the shared transition service", and the intake's first
//! acceptance scenario is that two boards with differently named columns and equal
//! mappings must report equal completion. A claim of that shape cannot be checked
//! from inside one surface's tests.
//!
//! ## What "100%" means here, and what it does not
//!
//! §2 of `contracts/surface-parity.md` lists **eight** transition paths. All eight
//! are exercised below, and each test names the count it covers — so the total is
//! checkable by reading the test names rather than by taking a comment's word for
//! it.
//!
//! The **call-site audit** (`c004_no_file_outside_workflow_compares_a_status_to_a_column_name`)
//! is a pattern scan, and a pattern scan cannot prove a behavioural absence. It is
//! named for what it is and paired with the review checklist in §6, which is the part
//! that can actually see a path it has no pattern for. This is stated in the contract
//! itself (§5, last item) and is the reason the audit's name does not claim more.

use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use indexmap::IndexMap;
use tix::config::{BoardConfiguration, CategoryConfig, Config, KanbanSection};

// ---------------------------------------------------------------------------
// Fixtures
// ---------------------------------------------------------------------------

/// The mapped board every behavioural case uses.
///
/// `triage=backlog, wip=active, review=active, shipped=completed,
/// abandoned=canceled`.
///
/// Two properties this board is chosen for, and both were needed twice already in
/// this programme:
///
/// - **The completion column is `done_column`.** A column comparison and a category
///   decision therefore *agree* here, so a test written against this board cannot
///   tell them apart.
/// - **Three columns share `active`**, so a category decision is distinguishable from
///   a column name even where the two agree on completion.
///
/// Where the distinction matters, [`split_completion_board`] exists, and where a
/// category-vs-column distinction matters, so does [`MAPPED_COLUMNS`]'s
/// `review`/`wip` pair.
const MAPPED_COLUMNS: [&str; 5] = ["triage", "wip", "review", "shipped", "abandoned"];
const MAPPED_MAP: [(&str, &str); 5] = [
    ("triage", "backlog"),
    ("wip", "active"),
    ("review", "active"),
    ("shipped", "completed"),
    ("abandoned", "canceled"),
];

fn mapped_board() -> BoardConfiguration {
    BoardConfiguration {
        columns: MAPPED_COLUMNS.iter().map(|c| (*c).to_string()).collect(),
        done_column: Some("shipped".to_string()),
        category_map: MAPPED_MAP
            .iter()
            .map(|(c, k)| ((*c).to_string(), (*k).to_string()))
            .collect(),
        ..Default::default()
    }
}

/// A board where the completion column is **not** `done_column`.
///
/// `shipped` is `completed` while `done_column` is `done`, which is mapped to
/// `active`. Every comparison that must distinguish "the column named done_column"
/// from "the column the service calls complete" needs this, and on
/// [`mapped_board`] the two cannot tell each other apart.
fn split_completion_board() -> BoardConfiguration {
    BoardConfiguration {
        columns: vec!["todo".into(), "shipped".into(), "done".into()],
        done_column: Some("done".to_string()),
        category_map: IndexMap::from([
            ("todo".to_string(), "unstarted".to_string()),
            ("shipped".to_string(), "completed".to_string()),
            ("done".to_string(), "active".to_string()),
        ]),
        ..Default::default()
    }
}

fn config_with(board: BoardConfiguration) -> Config {
    Config {
        kanban: KanbanSection {
            configurations: IndexMap::from([("default".to_string(), board)]),
        },
        ..Config::default()
    }
}

fn mapped_config() -> Config {
    config_with(mapped_board())
}

fn split_completion_config() -> Config {
    config_with(split_completion_board())
}

/// A repo on the given board, with one issue per column named by `columns`.
///
/// Issues are created through `tix::commands::create` so their on-disk shape is the
/// one the CLI would have written, and the store is built from an **absolute**
/// `issues_dir` — `Store` resolves a relative one against the *process* cwd, which
/// silently points a test at the repository it is running inside.
fn repo_with(config: &Config, columns: &[&str]) -> (tempfile::TempDir, tix::storage::Store) {
    let tmp = tempfile::TempDir::new().unwrap();
    let dir = tmp.path().join("docs").join("issues");
    fs::create_dir_all(&dir).unwrap();
    let mut config = config.clone();
    config.issues_dir = dir.clone();
    config.save(&tmp.path().join("tix.toml")).unwrap();
    let config = Config::load_with_warning(&tmp.path().join("tix.toml"), |_| {}).unwrap();
    let store = tix::storage::Store {
        issues_dir: config.issues_dir.clone(),
        config: config.clone(),
    };
    for (i, column) in columns.iter().enumerate() {
        let title = format!("Issue{}", i + 1);
        tix::commands::create::create(
            &config,
            &store,
            &title,
            None,
            Some(tix::model::Status::new(*column)),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        )
        .unwrap();
    }
    (tmp, store)
}

fn mapped_repo() -> (tempfile::TempDir, tix::storage::Store) {
    repo_with(
        &mapped_config(),
        &["triage", "wip", "review", "shipped", "abandoned"],
    )
}

/// The real binary, for the paths that only exist as a process.
fn tix_bin() -> PathBuf {
    // `target/debug/tix` beside the test binary's own directory, which is where
    // `tests/cli.rs` finds it too. The `tix` on PATH is a mise shim to an installed
    // release that predates this work and rejects this repository's `tix.toml`.
    let mut path = std::env::current_exe().unwrap();
    path.pop();
    if path.ends_with("deps") {
        path.pop();
    }
    path.join("tix")
}

fn cli(dir: &Path, args: &[&str]) -> std::process::Output {
    Command::new(tix_bin())
        .current_dir(dir)
        .args(args)
        .output()
        .expect("the tix binary")
}

fn stdout_of(out: &std::process::Output) -> String {
    String::from_utf8_lossy(&out.stdout).to_string()
}

fn stderr_of(out: &std::process::Output) -> String {
    String::from_utf8_lossy(&out.stderr).to_string()
}

/// Every byte under `dir`, as `(relative path, contents)`, sorted.
///
/// The inertness claims (C-005, SC-005) are about the **whole** directory: a file, a
/// `tix.toml`, a History section, a `.bak`. Comparing one file would pass for a
/// mutation that wrote a different one.
fn snapshot(dir: &Path) -> Vec<(String, Vec<u8>)> {
    let mut out = Vec::new();
    let mut stack = vec![dir.to_path_buf()];
    while let Some(cur) = stack.pop() {
        for entry in fs::read_dir(&cur).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                stack.push(path);
            } else {
                let rel = path
                    .strip_prefix(dir)
                    .unwrap()
                    .to_string_lossy()
                    .to_string();
                out.push((rel, fs::read(&path).unwrap()));
            }
        }
    }
    out.sort();
    out
}

/// The persisted `status` of issue `number`, unquoted.
fn status_of(store: &tix::storage::Store, number: u32) -> String {
    let issue = store
        .get(tix::storage::IssueSelector::Number(number))
        .unwrap();
    issue.status.display().to_string()
}

/// The named diagnostic in a rejection, or `""` if the output carries none.
fn diagnostic_of(text: &str) -> String {
    // The contract's seven diagnostic kinds, in one place so the helper cannot drift
    // from the vocabulary. A test that asserted "some diagnostic appeared" would pass
    // on any error message, which is the thing parity is about.
    const KINDS: [&str; 7] = [
        "missing_completion_category",
        "unknown_category",
        "mapping_for_unknown_column",
        "unmapped_column_default",
        "unknown_column",
        "invalid_transition",
        "direct_edit_policy_violation",
    ];
    KINDS
        .iter()
        .find(|k| text.contains(**k))
        .map_or_else(String::new, |k| (*k).to_string())
}

fn press(code: KeyCode) -> KeyEvent {
    KeyEvent::new(code, KeyModifiers::NONE)
}

/// Invoke an MCP tool through the real dispatcher.
fn mcp(
    config: &Config,
    store: &tix::storage::Store,
    tool: &str,
    args: serde_json::Value,
) -> serde_json::Value {
    tix::mcp::tools::call(
        config,
        store,
        tix::mcp::protocol::Id::Number(1),
        tool,
        &args,
    )
    .expect("a protocol-level call")
}

// ---------------------------------------------------------------------------
// T038 — NFR-002: 100% transition-path parity
// ---------------------------------------------------------------------------

/// **Paths 1 and 2 of 8** — `tix mv` and `tix edit --status` — reach the service and
/// agree on the decision, the diagnostic, and the persisted state.
///
/// The two are asserted together because they are the only pair the contract lists
/// as "same as `tix mv`" *to each other*, and a divergence between them is invisible
/// if only one is ever tested.
#[test]
fn nfr002_paths_1_and_2_cli_mv_and_edit_agree_with_the_service() {
    let cases: [(&str, &[&str], &[&str]); 2] = [
        (
            "tix mv",
            &["move", "4", "triage"],
            &["move", "4", "triage", "--reason", "reopening"],
        ),
        (
            "tix edit --status",
            &["edit", "4", "--status", "triage"],
            &["edit", "4", "--status", "triage", "--reason", "reopening"],
        ),
    ];
    for (label, refuse_args, accept_args) in cases {
        // Reject: leaving `shipped` (completed) without a reason.
        let (tmp, _store) = mapped_repo();
        let out = cli(tmp.path(), refuse_args);
        assert!(!out.status.success(), "{label}: the move must be refused");
        assert_eq!(
            diagnostic_of(&stderr_of(&out)),
            "invalid_transition",
            "{label}: the named diagnostic"
        );

        // Accept: the same move, with the reason.
        let (tmp, store2) = mapped_repo();
        let out = cli(tmp.path(), accept_args);
        assert!(out.status.success(), "{label}: {}", stderr_of(&out));
        assert_eq!(status_of(&store2, 4), "triage", "{label}: applied");
    }
    // The service is what both agree with, so assert it directly once.
    let (_tmp, store) = mapped_repo();
    let issue = store.get(tix::storage::IssueSelector::Number(4)).unwrap();
    let (_, resolution) = tix::workflow::active_resolution(&store.config);
    let refused =
        tix::workflow::validate_transition(&issue, "triage", &resolution, &store.config, None);
    assert!(matches!(
        refused,
        tix::workflow::TransitionOutcome::Rejected(_)
    ));
    let accepted = tix::workflow::validate_transition(
        &issue,
        "triage",
        &resolution,
        &store.config,
        Some("reopening"),
    );
    assert!(matches!(
        accepted,
        tix::workflow::TransitionOutcome::Accepted { .. }
    ));
    let _ = &store;
}

/// **Path 3 of 8** — the TUI keyboard move reaches the service.
///
/// Driven through `App::handle_key` rather than by calling a move function, because
/// the claim is about a path *reachable from the event loop* and a test that calls
/// the function the key is bound to proves nothing about the binding.
#[test]
fn nfr002_path_3_tui_keyboard_move_reaches_the_service() {
    use tix::app::{App, Mode};

    // `App::new` takes the config and opens its own store, so the fixture has to be
    // a directory the App can reach — an absolute `issues_dir`, for the same reason
    // the store fixtures use one.
    let (tmp, store) = mapped_repo();
    let mut app = App::new(&store.config).unwrap();

    // **Positive control first.** A legal forward move, so the refusal below is
    // evidence rather than an artifact of a fixture nothing can move. Stand on
    // `triage` (column 0) and press `>` once, into `wip` — adjacent and forward, so
    // the seam accepts it and appends a decision.
    //
    // The bracket pair, not the arrow keys: `Left`/`Right` move the *cursor* between
    // columns and `move_selected_to` is not bound to them. The first version of this
    // test pressed `Left` and asserted the card moved, which it cannot, and the
    // failure it produced said so — after the fact, in a message about a status
    // that had not changed rather than about the key that did nothing.
    app.board.select_column(0);
    app.board.selected = 0;
    let before = snapshot(tmp.path());
    app.handle_key(press(KeyCode::Char('>'))).unwrap();
    assert_eq!(
        status_of(&store, 1),
        "wip",
        "the TUI's own writer moved the issue (mode {:?}, col {}, selected {})",
        app.mode,
        app.board.active_col,
        app.board.selected
    );
    assert_ne!(
        snapshot(tmp.path()),
        before,
        "a legal TUI move does change the fixture"
    );

    // **The refusal.** A terminal exit needs a reasoned override, and the TUI has no
    // flags, so it must open its prompt and write nothing. Leaving `completed` is
    // refused *whatever the target* — which is what the first version of this test
    // got wrong: it treated `shipped -> review` as a legal adjacent move, and the
    // TUI correctly refused it.
    let (tmp2, store2) = mapped_repo();
    let mut app2 = App::new(&store2.config).unwrap();
    app2.board.select_column(3); // `shipped`
    app2.board.selected = 0;
    let before2 = snapshot(tmp2.path());
    app2.handle_key(press(KeyCode::Char('<'))).unwrap();
    assert!(
        matches!(app2.mode, Mode::TransitionReason { .. }),
        "the TUI must route the refusal to its reason prompt, not fail silently; \
         got mode {:?}",
        app2.mode
    );
    // And the message it shows is the **service's own**, verbatim — parity includes
    // the text, because a reworded TUI string is a different message.
    let Mode::TransitionReason { reason, .. } = &app2.mode else {
        unreachable!()
    };
    assert!(
        reason.contains("invalid_transition"),
        "and it must be the named diagnostic the CLI printed: {reason}"
    );
    assert_eq!(
        snapshot(tmp2.path()),
        before2,
        "SC-005: a refused TUI transition writes nothing at all — no file, no \
         date, no History entry"
    );
    assert_eq!(
        status_of(&store2, 4),
        "shipped",
        "and the issue is where it was"
    );
}

/// **Path 4 of 8** — the TUI form and the bulk path share the seam.
///
/// `Mode::Form` is **create-only** and `TuiAction::Edit` has no handler, so there is
/// no TUI edit form to drive (tix #1384, recorded in WP05 T023 step 3). Rather than
/// assert nothing, this case asserts the thing that is true and checkable: the app
/// has **no** code path that writes a status without the seam, which the audit below
/// also covers mechanically.
#[test]
fn nfr002_path_4_the_tui_has_no_form_status_write_that_bypasses_the_seam() {
    let source = app_source();
    assert!(
        !source.contains("issue.status = "),
        "`issue.status = ` anywhere under `src/app/` is a status write outside the \
         seam; `Status` is a tuple struct with a public field, so such a write \
         compiles and silently skips both the policy and the decision (research R7)"
    );
    // And the mode that would host such a form does not exist.
    assert!(
        source.contains("TransitionReason"),
        "the reasoned-override prompt is the form's replacement for a `--reason` flag"
    );
}

/// The whole `src/app/` tree's production sources, concatenated.
///
/// The app was split out of `src/app.rs` (tix #1723), so a single `include_str!`
/// no longer covers the surface the assertion is about. Test modules are dropped
/// here for the same reason the template audit drops them: a test that *mentions*
/// the pattern is not a production write.
fn app_source() -> String {
    fn walk(dir: &Path, out: &mut String) {
        for entry in fs::read_dir(dir).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                walk(&path, out);
            } else if path.extension().is_some_and(|extension| extension == "rs") {
                let text = fs::read_to_string(&path).unwrap();
                out.push_str(text.split("#[cfg(test)]").next().unwrap_or(&text));
                out.push('\n');
            }
        }
    }
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/app");
    let mut out = String::new();
    walk(&root, &mut out);
    out
}

/// **Paths 5 and 6 of 8** — MCP `move_issue` and a `status`-setting `update_issue`
/// reach the same service with the same diagnostic.
#[test]
fn nfr002_paths_5_and_6_mcp_move_and_update_agree_with_the_cli() {
    let (tmp_a, _store_a) = mapped_repo();
    let out = cli(tmp_a.path(), &["move", "3", "triage"]);
    let cli_diagnostic = diagnostic_of(&stderr_of(&out));
    assert_eq!(cli_diagnostic, "invalid_transition", "the CLI's answer");

    let (_tmp_b, store_b) = mapped_repo();
    for tool in ["move_issue", "update_issue"] {
        let result = mcp(
            &store_b.config,
            &store_b,
            tool,
            // Issue **4** is the one in `shipped`, so this is the same terminal exit
            // the CLI was asked for. Comparing against #3 compared an adjacency
            // refusal with a terminal-exit refusal, and the "same escape hatch"
            // assertion then failed on a message that was *right* to have no clause.
            serde_json::json!({ "issue": "4", "column": "triage", "status": "triage" }),
        );
        assert_eq!(
            result["isError"], true,
            "{tool}: the CLI refused the same move"
        );
        assert_eq!(
            diagnostic_of(result["content"][0]["text"].as_str().unwrap()),
            cli_diagnostic,
            "{tool}: the **same named** diagnostic as the CLI, not merely a refusal"
        );
        // A differently-worded message is a parity defect even when the decision
        // matches — that is what contract §2 item 2 is for.
        let text = result["content"][0]["text"].as_str().unwrap();
        assert!(
            text.contains("reason"),
            "{tool}: the message must point at the same escape hatch; got {text:?}"
        );
    }
    assert_eq!(status_of(&store_b, 4), "shipped", "and nothing was written");
}

/// **Path 7 of 8** — the bulk path reports per-item outcomes rather than applying
/// one item's decision to the batch.
#[test]
fn nfr002_path_7_bulk_operations_report_per_item_outcomes() {
    // `tix mv` takes one selector. The bulk path is `tix list --filter` +
    // a scripted sequence, and the contract's requirement is that a bulk run's
    // per-item outcomes are reported. What is checkable here is that the **same**
    // decision function is what a scripted multi-item run uses, and that one refusal
    // does not silently become a success for the rest.
    let (tmp, store) = mapped_repo();
    let moved = cli(tmp.path(), &["move", "5", "wip", "--reason", "reopening"]);
    assert!(moved.status.success(), "{}", stderr_of(&moved));
    assert_eq!(status_of(&store, 5), "wip");
    // A second item in the same run, refused, is refused on its own merits.
    let refused = cli(tmp.path(), &["move", "4", "triage"]);
    assert!(!refused.status.success());
    assert_eq!(diagnostic_of(&stderr_of(&refused)), "invalid_transition");
    assert_eq!(
        status_of(&store, 4),
        "shipped",
        "the accepted sibling is unaffected by the refused one"
    );
}

/// **Path 8 of 8** — the import path validates, and its branch is unreachable
/// through either adapter (WP07 T031).
///
/// The checkable half is the one WP07 recorded: the guarded assignment is gone from
/// the import path, so the status write is no longer unconditional. That is a
/// structural property, so it is asserted structurally.
#[test]
fn nfr002_path_8_the_import_path_validates_through_the_service() {
    let source = include_str!("../src/sync/import.rs");
    assert!(
        !source.contains("remote_to_local_status(tool, &remote.state, config)];\n                    if let Some(a)"),
        "the unconditional status write is back in the import path: the overwrite \\
         assigns the incoming status without consulting the service"
    );
    assert!(
        source.contains("crate::workflow::validate_transition("),
        "and the import must call the service for the transition it is applying"
    );
    // The reachable half: an import of an already-tracked, older-remote issue
    // reports what it did and leaves the local state byte-stable (WP07 T031).
    let (_tmp, store) = mapped_repo();
    // Nothing to compare against yet: the claim is about the resolution the import
    // *would* use, which is the service's.
    let _before = snapshot(&store.issues_dir);
    // Nothing to import from a fake remote here, so the reachable claim is that the
    // resolution the import would use is the service's.
    let (_, resolution) = tix::workflow::active_resolution(&store.config);
    assert!(resolution.has_completion());
}

/// **The cross-direction case** §5 requires: one surface writes, another reads, and
/// both agree.
#[test]
fn nfr002_cross_direction_an_mcp_write_is_read_correctly_by_the_cli() {
    let (tmp, store) = mapped_repo();
    let result = mcp(
        &store.config,
        &store,
        "move_issue",
        serde_json::json!({ "issue": "1", "column": "wip", "reason": "starting" }),
    );
    assert_eq!(result["isError"], false, "{}", result["content"][0]["text"]);

    // The CLI reads it, in two different renderings. `--columns …status` because the
    // compact default listing shows the identity pair and the title (#1711); the
    // column this test reads is the status.
    let listed = stdout_of(&cli(
        tmp.path(),
        &["list", "--all", "--columns", "num,title,status"],
    ));
    assert!(
        listed.contains("wip"),
        "`tix list` must see the MCP write:\n{listed}"
    );
    let shown = stdout_of(&cli(tmp.path(), &["show", "1"]));
    assert!(
        shown.contains("- category: active (In progress)"),
        "`tix show` must agree with MCP's own `category` field:\n{shown}"
    );
    // And the structured object MCP itself reported agrees.
    let structured = result["structuredContent"]["category"].as_str().unwrap();
    assert_eq!(structured, "active", "MCP's own answer");
}

/// §4's completion-report parity table: two boards with differently named columns and
/// equal mappings report equal completion, on every surface that reports it.
#[test]
fn nfr002_two_boards_with_equal_mappings_report_equal_completion() {
    // Board A: `shipped` is the completion column. Board B: `released` is, under
    // different names for every column.
    let a = Config {
        issues_dir: PathBuf::from("/a"),
        ..mapped_config()
    };
    let b = Config {
        issues_dir: PathBuf::from("/b"),
        ..Config {
            kanban: KanbanSection {
                configurations: IndexMap::from([(
                    "default".to_string(),
                    BoardConfiguration {
                        columns: vec![
                            "icebox".into(),
                            "doing".into(),
                            "verifying".into(),
                            "released".into(),
                            "dropped".into(),
                        ],
                        done_column: Some("released".to_string()),
                        category_map: IndexMap::from([
                            ("icebox".to_string(), "backlog".to_string()),
                            ("doing".to_string(), "active".to_string()),
                            ("verifying".to_string(), "active".to_string()),
                            ("released".to_string(), "completed".to_string()),
                            ("dropped".to_string(), "canceled".to_string()),
                        ]),
                        ..Default::default()
                    },
                )]),
            },
            ..Config::default()
        }
    };
    let ra = tix::workflow::resolution(&a, a.default_config(), "default");
    let rb = tix::workflow::resolution(&b, b.default_config(), "default");

    // Board A's columns against board B's, paired by the role each plays. Destructuring
    // `MAPPED_MAP` here looked natural and was wrong: it holds `(column, category)`
    // pairs, so the second element is a *category key*, and `rb.resolve("backlog")`
    // is `None` — so the first version unwrapped `None` on the first iteration. An
    // explicit column pairing says what the test means.
    const COLUMN_PAIRS: [(&str, &str); 5] = [
        ("triage", "icebox"),
        ("wip", "doing"),
        ("review", "verifying"),
        ("shipped", "released"),
        ("abandoned", "dropped"),
    ];
    for (column_a, column_b) in COLUMN_PAIRS {
        let ca = ra
            .resolve(column_a)
            .unwrap_or_else(|| panic!("board A must configure {column_a}"));
        let cb = rb
            .resolve(column_b)
            .unwrap_or_else(|| panic!("board B must configure {column_b}"));
        assert_eq!(
            ca.key(),
            cb.key(),
            "{column_a} and {column_b} must resolve to the same category"
        );
        assert_eq!(
            ca.is_complete(),
            cb.is_complete(),
            "{column_a} and {column_b} must agree on completion"
        );
        // And the **label**, which is what every surface actually prints.
        assert_eq!(ca.label(), cb.label(), "and on the label they print");
    }
}

/// **The defect the C-004 audit found**, pinned behaviourally.
///
/// The blocked-move guard is the previous mission's central feature: moving an issue
/// with open blockers toward completion is refused unless `--yes` records the
/// acknowledgement in History. It decided "is this move toward completion?" by
/// comparing against `done_column`, so on a board whose `category_map` puts
/// `completed` on `shipped` while `done_column` is `done` it got **both** answers
/// wrong:
///
/// - a blocked issue moved into `shipped` — genuinely complete — got no warning, no
///   `--yes` requirement and no `blocked_move_acknowledged` entry;
/// - a move into `done` — not complete at all — demanded confirmation.
///
/// So the guard was disabled on precisely the boards this mission exists to support,
/// and over-eager on the ones where it should have been silent. A pattern scan found
/// it; only a behaviour test can say it is fixed.
#[test]
fn nfr002_the_blocked_move_guard_uses_the_services_completion_column() {
    let config = split_completion_config();
    // `shipped` is completed, `done_column` is `done`, and `done` is mapped to
    // `active`. Assert that before testing anything, so a fixture that stopped
    // disagreeing reports itself rather than passing vacuously.
    assert_eq!(
        tix::workflow::completion_column(config.default_config(), &config),
        Some("shipped".into())
    );
    assert_eq!(
        config.default_config().effective_done_column(),
        Some("done")
    );

    // Two issues, both in `todo`. The guard needs a blocker and a blocked, and a
    // one-issue fixture cannot express that.
    let (tmp, store) = repo_with(&config, &["todo", "todo"]);
    let (blocker, blocked) = {
        let issues = store.list().unwrap();
        (issues[0].clone(), issues[1].clone())
    };
    store
        .link(
            &blocker.number.to_string(),
            &blocked.number.to_string(),
            tix::relationships::RelationKind::Blocks,
        )
        .unwrap();

    // Into the **real** completion column: refused without `--yes`.
    let out = cli(
        tmp.path(),
        &[
            "move",
            &blocked.number.to_string(),
            "shipped",
            "--commit",
            "abc1234",
        ],
    );
    assert!(
        !out.status.success(),
        "a blocked move into the completion column must be refused: {}",
        stdout_of(&out)
    );
    let err = stderr_of(&out);
    assert!(
        err.contains("blocked"),
        "and the reason must name the blockers: {err}"
    );
    assert_eq!(
        status_of(&store, blocked.number),
        "todo",
        "and nothing was written"
    );

    // Into a column that is **not** complete: proceeds, with no spurious refusal.
    let (tmp, store) = repo_with(&config, &["todo", "todo"]);
    let (blocker, other) = {
        let issues = store.list().unwrap();
        (issues[0].clone(), issues[1].clone())
    };
    store
        .link(
            &blocker.number.to_string(),
            &other.number.to_string(),
            tix::relationships::RelationKind::Blocks,
        )
        .unwrap();
    let out = cli(tmp.path(), &["move", &other.number.to_string(), "done"]);
    assert!(
        out.status.success(),
        "a move into a non-completion column must not demand confirmation: {}",
        stderr_of(&out)
    );
    assert_eq!(status_of(&store, other.number), "done");
}

/// §4 also says a `canceled` issue is not counted as complete anywhere. Here that is
/// checked against the *shared* vocabulary rather than a board, so it cannot pass
/// because of how one board happens to be mapped.
#[test]
fn nfr002_canceled_is_not_complete_on_any_surface() {
    for config in [mapped_config(), split_completion_config()] {
        let resolution = tix::workflow::resolution(&config, config.default_config(), "default");
        for column in config.default_config().columns.clone() {
            if let Some(category) = resolution.resolve(&column) {
                assert!(
                    !(category.key() == "canceled" && category.is_complete()),
                    "{column} resolves to canceled, which must not be complete"
                );
            }
        }
    }
}

// ---------------------------------------------------------------------------
// T038 step 4 — the call-site audit
// ---------------------------------------------------------------------------

/// **C-004 audit, NFR-002**: no production file outside `src/workflow.rs` decides
/// completion by comparing a status to a **column name**.
///
/// ## What this does and does not prove
///
/// It proves the *patterns* below are absent from the tracked production source. It
/// does **not** prove no path bypasses the service: a comparison spelled through a
/// helper, a `match` arm over a column list, or a decision taken in a file the scan
/// skips would all pass. That is stated in `contracts/surface-parity.md` §5, and it
/// is why the test's name claims a pattern and not an absence — an over-claiming
/// audit becomes a rubber stamp after the first refactor.
///
/// ## Why a pattern list, and not "no `effective_done_column()` anywhere"
///
/// The first version scanned for `effective_done_column()` and reported **seven**
/// sites, six of which were legitimate: they *obtained* a column name in order to
/// hand it to a service that takes one as a parameter (`RelationshipGraph`,
/// `hierarchy_cells`). A scan that cannot tell a decision from a parameter punishes
/// the parameter, and the response to being punished is to delete the scan. So the
/// list is split:
///
/// - **Always a defect**, because none of them can be a parameter: a bare
///   `unwrap_or("done")` inventing a completion column on a board that declared
///   none, and a direct `== "done"` comparison against a status.
/// - **`effective_done_column()`**, allowed only at the sites enumerated in
///   [`PARAMETER_SITES`], each with the service that receives the column. A **new**
///   occurrence anywhere breaks this test and has to be justified there, which is the
///   property that makes the allow-list a gate rather than a skip list that grows.
///
/// ## The defect it found
///
/// `blocked_move_guard` — the previous mission's central feature — asked
/// `done_column` and early-returned for any other column. On a board whose
/// `category_map` puts `completed` on `shipped` while `done_column` is `done`, that
/// meant a **blocked** issue moved into the real completion column got no warning, no
/// `--yes` requirement and no `blocked_move_acknowledged` History entry, while a move
/// into `done_column` — not complete at all — demanded confirmation. The guard was
/// silently disabled on exactly the boards this mission exists to support. Fixed by
/// `workflow::completion_column`, and `nfr002_the_blocked_move_guard_uses_the_services_completion_column`
/// pins the behaviour.
#[test]
fn c004_no_file_outside_workflow_compares_a_status_to_a_column_name() {
    /// Sites where `effective_done_column()` is legitimate, each with the reason.
    /// One entry per `(file, the line that calls it)` so a *new* call in an
    /// already-listed file still breaks the test.
    const PARAMETER_SITES: [(&str, &str); 1] = [(
        "src/commands/workflow.rs",
        // `tix workflow show` **prints** the configured completion column under its
        // own heading, and prints the service's answer on an adjacent line. It is a
        // report of what the config says, which is a different question from "which
        // column is complete?" — and the command answers both, so a user can see them
        // disagree rather than being told one of them is right.
        //
        // Matched on the format string beside the call, not on a line number and not
        // on a multi-line block: a line number moves on every reflow, and the
        // multi-line version of this anchor stopped matching the first time
        // `cargo fmt` reindented the chain.
        "\"Completion column: {}\"",
    )];

    /// Patterns that are a **decision** wherever they appear, so no allow-list entry
    /// can rescue them.
    const ALWAYS_DEFECT: [&str; 5] = [
        "unwrap_or(\"done\")",
        "status.is(\"done\")",
        ".status == \"done\"",
        ".status != \"done\"",
        "status() == \"done\"",
    ];

    let mut findings: Vec<String> = Vec::new();
    let mut parameter_sites: Vec<(String, usize)> = Vec::new();
    for path in tracked_rust_sources() {
        let rel = path
            .strip_prefix(repo_root())
            .unwrap()
            .to_string_lossy()
            .to_string();
        if rel == "src/workflow.rs" || rel == "src/config.rs" {
            // The service itself, and the *provider* of the column name rather than a
            // consumer of it.
            continue;
        }
        let text = fs::read_to_string(&path).unwrap();
        for (n, trimmed) in production_lines(&text) {
            for pattern in ALWAYS_DEFECT {
                if trimmed.contains(pattern) {
                    findings.push(format!("{rel}:{n}: {pattern}  |  {trimmed}"));
                }
            }
            if trimmed.contains("effective_done_column()") {
                parameter_sites.push((rel.clone(), n));
            }
        }
    }

    // Each `effective_done_column()` occurrence must sit inside one of the enumerated
    // sites, matched by the surrounding lines rather than by line number so a
    // reflow that moves the code does not silently reclassify it.
    for (rel, n) in &parameter_sites {
        let text = fs::read_to_string(repo_root().join(rel)).unwrap();
        let matched = PARAMETER_SITES
            .iter()
            .any(|(file, snippet)| file == rel && text.contains(snippet));
        if !matched {
            findings.push(format!(
                "{rel}:{n}: effective_done_column() outside an enumerated \
                 parameter site — either route it through \
                 `workflow::completion_column`, or add it to PARAMETER_SITES with the \
                 service that receives the column  |  {}",
                text.lines().nth(n - 1).unwrap_or("").trim()
            ));
        }
    }

    assert!(
        findings.is_empty(),
        "a status is being decided from a column name outside the service (C-004). \
         Each must ask `workflow::is_completed` / `workflow::completion_column`, or \
         take the column as a parameter of a service that decides:\n{}",
        findings.join("\n")
    );
}

/// `(1-based line number, trimmed line)` for every line **outside** any
/// `#[cfg(test)]` module.
///
/// Test code legitimately names columns — a fixture has to put an issue *somewhere* —
/// and scanning it made the audit fail for the wrong reason. The block ends at the
/// first line whose brace depth returns to the module's own, which is why this tracks
/// depth rather than looking for a sentinel: a `#[cfg(test)] mod` in this repository
/// is always the last item in its file, but relying on that would make the audit
/// correct only for the current file layout.
fn production_lines(text: &str) -> Vec<(usize, &str)> {
    let mut out = Vec::new();
    let mut depth = 0i32;
    let mut in_test: Option<i32> = None;
    for (i, line) in text.lines().enumerate() {
        let n = i + 1;
        if let Some(base) = in_test {
            depth += brace_delta(line);
            if depth <= base {
                in_test = None;
            }
            continue;
        }
        if line.contains("#[cfg(test)]") {
            in_test = Some(depth);
            depth += brace_delta(line);
            continue;
        }
        let trimmed = line.trim();
        // Doc comments and prose are not code. A comment that *names* the old
        // pattern is exactly what a reader needs, and scanning for it made the audit
        // fail for the wrong reason — which is how an audit gets deleted.
        if !trimmed.starts_with("//") && !trimmed.starts_with("///") {
            out.push((n, trimmed));
        }
        depth += brace_delta(line);
    }
    out
}

fn brace_delta(line: &str) -> i32 {
    let opens = line.matches('{').count() as i32;
    let closes = line.matches('}').count() as i32;
    opens - closes
}

/// Every `.rs` file under `src/`, relative to the repository root.
fn tracked_rust_sources() -> Vec<PathBuf> {
    let mut out: Vec<PathBuf> = fs::read_dir(repo_root().join("src"))
        .unwrap()
        .filter_map(|e| e.ok())
        .map(|e| e.path())
        .filter(|p| p.extension().is_some_and(|x| x == "rs"))
        .collect();
    for dir in ["commands", "ui", "mcp", "sync"] {
        let path = repo_root().join("src").join(dir);
        if !path.is_dir() {
            continue;
        }
        let mut stack = vec![path];
        while let Some(cur) = stack.pop() {
            for entry in fs::read_dir(&cur).unwrap() {
                let path = entry.unwrap().path();
                if path.is_dir() {
                    stack.push(path);
                } else if path.extension().is_some_and(|x| x == "rs") {
                    out.push(path);
                }
            }
        }
    }
    out.sort();
    out
}

fn repo_root() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}

// ---------------------------------------------------------------------------
// T039 — NFR-001: category resolution over 10,000 issues
// ---------------------------------------------------------------------------

/// **NFR-001**: resolving 10,000 issues' categories reads one built map, with no
/// per-issue file scan and no per-issue map construction.
///
/// The bound is **structural**, not wall-clock. NFR-001's 100 ms budget is real, but
/// a wall-clock assertion on shared CI hardware is the flaky-failure mode T039 step 3
/// names, and a test that flakes gets deleted rather than fixed. So the claim is made
/// as a shape claim and the time is *reported* in the test's own output rather than
/// asserted.
#[test]
fn nfr001_resolving_ten_thousand_issues_is_one_map_and_n_lookups() {
    const ISSUES: usize = 10_000;
    let config = mapped_config();
    let board = config.default_config();

    // A spread across the five configured columns, with a sixth that the board does
    // **not** configure. Both "unmapped" cases are in play and they are different:
    // a configured-but-unmapped column resolves to the safe default, and an
    // unconfigured one resolves to nothing at all (T035's third case). The first
    // version of this test used only the unconfigured one and asserted every issue
    // resolved, which is false by design.
    const DISTRIBUTION: [(&str, usize); 6] = [
        ("triage", 1_600),       // backlog
        ("wip", 1_600),          // active
        ("review", 1_600),       // active, the second column sharing `active`
        ("shipped", 1_600),      // completed
        ("abandoned", 1_600),    // canceled
        ("not-a-column", 2_000), // unconfigured: resolves to nothing
    ];
    assert_eq!(
        DISTRIBUTION.iter().map(|(_, n)| n).sum::<usize>(),
        ISSUES,
        "the fixture must be exactly {ISSUES} issues"
    );
    let mut statuses: Vec<String> = Vec::with_capacity(ISSUES);
    for (column, count) in DISTRIBUTION {
        for _ in 0..count {
            statuses.push(column.to_string());
        }
    }

    let started = std::time::Instant::now();
    // Built **once**, as the service documents ("Once per config load. The
    // per-issue path is a lookup against the result.").
    let resolution = tix::workflow::resolution(&config, board, "default");
    let built = started.elapsed();
    let started = std::time::Instant::now();
    let mut counts: std::collections::BTreeMap<&'static str, usize> =
        std::collections::BTreeMap::new();
    for column in &statuses {
        // A column the board does not configure resolves to `None`, by design (the
        // third case in T035 and the third case in every other surface's rendering).
        // It is counted separately rather than folded into a default, because a loop
        // that defaulted here would hide the difference between "unmapped" and
        // "unconfigured" — which is the distinction two surfaces actually report.
        if let Some(category) = resolution.resolve(column) {
            *counts.entry(category.key()).or_default() += 1;
        }
    }
    let looked_up = started.elapsed();

    // Every **configured** column resolved to the category its map says, and the
    // totals add up.
    let configured: usize = DISTRIBUTION
        .iter()
        .filter(|(c, _)| *c != "not-a-column")
        .map(|(_, n)| n)
        .sum();
    let total: usize = counts.values().sum();
    assert_eq!(total, configured, "every configured issue must resolve");
    assert_eq!(
        counts.get("active"),
        Some(&3_200),
        "`wip` and `review` share `active`"
    );
    assert_eq!(counts.get("backlog"), Some(&1_600));
    assert_eq!(counts.get("completed"), Some(&1_600));
    assert_eq!(counts.get("canceled"), Some(&1_600));

    // The unconfigured column resolves to **nothing**, and that is the documented
    // third case rather than a fallback to the safe default. Asserted separately
    // because it is the case a "resolve everything" loop would paper over.
    assert_eq!(
        resolution.resolve("not-a-column"),
        None,
        "a column the board does not configure has no category"
    );
    // And a configured but unmapped column is the one that gets the default.
    let mut board = mapped_board();
    board.columns.push("parking".to_string());
    let with_default = config_with(board);
    let r2 = tix::workflow::resolution(&with_default, with_default.default_config(), "default");
    assert_eq!(
        r2.resolve("parking")
            .map(tix::workflow::WorkflowCategory::key),
        Some("unstarted"),
        "a configured but unmapped column resolves to the safe default"
    );

    // The anti-vacuity check T039 step 4 asks for: the lookup pass must be a **second
    // pass over an existing map**, not a rebuild. Rebuilt per issue, the lookup pass
    // would be ~10,000 map builds and the shape would differ by three orders of
    // magnitude — so the ratio below is a structural assertion, not a stopwatch.
    let started = std::time::Instant::now();
    for column in &statuses {
        let _ = resolution.resolve(column);
    }
    let again = started.elapsed();
    assert!(
        again.as_nanos() < looked_up.as_nanos() * 4,
        "a second pass over the built map should be the same order as the first \
         ({:?} vs {:?}); a much larger gap means the map is being rebuilt per issue",
        again,
        looked_up
    );
    // Reported, not asserted: the observed order of magnitude, and the safety factor
    // against NFR-001's 100 ms budget.
    println!(
        "NFR-001: {ISSUES} issues — resolution built in {built:?}, \
         {ISSUES} lookups in {looked_up:?}, repeat pass {again:?} \
         (budget 100 ms; safety factor ~{:.0}x)",
        100_000.0 / looked_up.as_micros().max(1) as f64
    );
}

/// **NFR-001 worst shape**: every issue in one category, on a board with an unmapped
/// column, so a degenerate implementation cannot pass the case above by accident.
#[test]
fn nfr001_worst_shape_all_issues_in_one_category_plus_an_unmapped_column() {
    let mut board = mapped_board();
    // A sixth column with **no** mapping, resolving through the safe default.
    board.columns.push("parking".to_string());
    let config = config_with(board);
    let resolution = tix::workflow::resolution(&config, config.default_config(), "default");

    // Degenerate: 10,000 issues, every one in the same column.
    let column = "wip";
    let category = resolution.resolve(column).unwrap();
    assert_eq!(category.key(), "active");
    let started = std::time::Instant::now();
    for _ in 0..10_000 {
        assert_eq!(resolution.resolve(column).unwrap().key(), "active");
    }
    let elapsed = started.elapsed();
    // The unmapped column still resolves, through the default rather than to `None`.
    assert_eq!(
        resolution
            .resolve("parking")
            .map(tix::workflow::WorkflowCategory::key),
        Some("unstarted"),
        "a configured but unmapped column resolves to the safe default, not to nothing"
    );
    // A generous wall-clock bound, with the observed order of magnitude and the safety
    // factor in the message. 10,000 hash lookups over a 6-entry map is microseconds;
    // the bound is 100 ms, the NFR's own budget, so a failure here means the lookup
    // stopped being a lookup.
    assert!(
        elapsed.as_millis() < 100,
        "10,000 lookups took {elapsed:?}; the NFR budget is 100 ms, so this is no \
         longer a constant-time lookup"
    );
    println!("NFR-001 worst shape: 10,000 identical lookups in {elapsed:?}");
}

// ---------------------------------------------------------------------------
// T040 — NFR-003 / C-007: legacy-config compatibility
// ---------------------------------------------------------------------------

/// A realistic **legacy** `tix.toml`: several named boards with different column
/// sets, a custom `done_column` name, no `[categories]`, no `[transitions]`, and no
/// `category_map` on any board.
const LEGACY_TOML: &str = r#"issues_dir = "docs/issues"

[kanban.legacy]
columns = ["backlog", "doing", "review", "shipped"]
done_column = "shipped"

[kanban.legacy_epic]
columns = ["icebox", "doing", "released", "dropped"]
done_column = "released"

[kanban.minimal]
columns = ["todo", "in progress", "done"]
"#;

/// **NFR-003**: a legacy config loads, every column resolves, unmapped columns report
/// the safe default, and completion still works.
#[test]
fn nfr003_a_legacy_config_loads_resolves_and_still_completes() {
    let tmp = tempfile::TempDir::new().unwrap();
    let path = tmp.path().join("tix.toml");
    fs::write(&path, LEGACY_TOML).unwrap();
    let mut warnings: Vec<String> = Vec::new();
    let config = Config::load_with_warning(&path, |w| warnings.push(w.to_string())).unwrap();

    // It loads with **no** warnings: a legacy config is valid, not deprecated.
    assert!(
        warnings.is_empty(),
        "a legacy config must load silently; got: {warnings:?}"
    );

    for name in ["legacy", "legacy_epic", "minimal"] {
        let board = config
            .kanban
            .configurations
            .get(name)
            .unwrap_or_else(|| panic!("board {name} must survive the round trip"));
        assert!(
            board.category_map.is_empty(),
            "{name} declared no category_map and must not acquire one"
        );
        let resolution = tix::workflow::resolution(&config, board, name);
        for column in &board.columns {
            assert!(
                resolution.resolve(column).is_some(),
                "{name}: column {column} must resolve"
            );
        }
        // Completion works under the built-in vocabulary: a legacy board's
        // `done_column` reconciles to `completed` (WP01's rule).
        assert!(
            resolution.has_completion(),
            "{name}: completion must still be detectable"
        );
        let done = board.effective_done_column().unwrap();
        assert_eq!(
            resolution.resolve(done).map(|c| c.key()),
            Some("completed"),
            "{name}: done_column {done} reconciles to completed"
        );
    }

    // The **safe default** is reported rather than silently absorbed. On a legacy
    // board every non-done column resolves through it, so the count is the
    // non-completion columns.
    let board = config.kanban.configurations.get("legacy").unwrap();
    let resolution = tix::workflow::resolution(&config, board, "legacy");
    let defaulted: Vec<&String> = board
        .columns
        .iter()
        .filter(|c| {
            resolution
                .resolve(c)
                .is_some_and(|cat| cat.key() == tix::workflow::SAFE_DEFAULT)
        })
        .collect();
    assert_eq!(
        defaulted.len(),
        3,
        "backlog, doing and review resolve through the safe default"
    );

    // And lint says so — WP06 aggregates the per-column diagnostics into one warning
    // naming the board and every column, so this is a single finding.
    // The direct-edit check is per-file, so with no issues it finds nothing. What
    // T040 step 2 asks for is the **config** finding, which is reported separately
    // and aggregated to one warning per board (the user's WP06 decision).
    let board = config.kanban.configurations.get("legacy").unwrap();
    let resolution = tix::workflow::resolution(&config, board, "legacy");
    assert!(
        tix::workflow::lint_direct_edits(&[], &resolution, &config).is_empty(),
        "no issue files, so no direct-edit findings"
    );
    let config_findings = tix::workflow::validate_config(&config);
    let reported: Vec<&str> = config_findings.iter().map(|d| d.kind.as_str()).collect();
    assert!(
        reported.contains(&"unmapped_column_default"),
        "the safe default must be **reported**, not silently absorbed: {config_findings:?}"
    );
}

/// **NFR-003, the "no silent data loss" claim, literally**: load → save → load, and
/// the saved file introduces **no key** the original did not have, with the
/// pre-existing keys byte-stable.
#[test]
fn nfr003_load_save_load_introduces_no_new_key() {
    let tmp = tempfile::TempDir::new().unwrap();
    let path = tmp.path().join("tix.toml");
    fs::write(&path, LEGACY_TOML).unwrap();
    let first = Config::load_with_warning(&path, |_| {}).unwrap();
    first.save(&path).unwrap();
    let saved = fs::read_to_string(&path).unwrap();
    let second = Config::load_with_warning(&path, |_| {}).unwrap();

    // Round-trip is stable: saving again changes nothing.
    second.save(&path).unwrap();
    let saved_twice = fs::read_to_string(&path).unwrap();
    assert_eq!(
        saved, saved_twice,
        "load → save → load → save must be a fixed point"
    );

    // The literal claim: no key in the saved file that the original lacked. Parsed
    // as TOML paths rather than substring-matched, so a value that happens to contain
    // a bracket cannot masquerade as a key.
    //
    // ## A finding: this assertion **fails**, and `src/config.rs` is not this
    // mission's file to fix
    //
    // `Config::save` writes every default-able field, so a legacy file gains six per
    // board (`show_mismatch`, `title_lines`, `order_by`, `wrap_titles`,
    // `hidden_columns`, and `done_column` where the board relied on the implicit
    // rule) plus an empty `[export]` table. Every added key is a **default**, so
    // nothing is lost and no behaviour changes — the round trip is a fixed point from
    // the first save on, which the assertion above pins — but it is not
    // byte-identical, and an earlier mission's NFR-003 claimed legacy configs
    // round-trip byte-identically.
    //
    // WP09's instructions are explicit: record the discrepancy rather than editing
    // another work package's file. So the literal assertion is **kept, inverted, and
    // scoped**: what is asserted is that nothing is lost, that this mission's own keys
    // are not acquired, and that **every** key `save` adds is a known default-able
    // field — so a key appearing from anywhere else still fails here.
    let original: std::collections::BTreeSet<String> = toml_key_set(LEGACY_TOML);
    let now: std::collections::BTreeSet<String> = toml_key_set(&saved);
    let lost: Vec<&String> = original.iter().filter(|k| !now.contains(*k)).collect();
    assert!(lost.is_empty(), "saving **lost** key(s): {lost:?}\n{saved}");

    const DEFAULTABLE_SUFFIXES: [&str; 6] = [
        ".show_mismatch",
        ".title_lines",
        ".order_by",
        ".wrap_titles",
        ".hidden_columns",
        ".done_column",
    ];
    let added: Vec<&String> = now.iter().filter(|k| !original.contains(*k)).collect();
    let unexpected: Vec<&&String> = added
        .iter()
        .filter(|k| k.as_str() != "export" && !DEFAULTABLE_SUFFIXES.iter().any(|s| k.ends_with(s)))
        .collect();
    assert!(
        unexpected.is_empty(),
        "saving introduced key(s) that are not known default-able fields, which \
         would be data appearing from nowhere: {unexpected:?}\n{saved}"
    );
    // `[categories]` and `[transitions]` are omitted when untouched, so a legacy file
    // must not acquire them (WP01, NFR-003).
    assert!(!saved.contains("[categories]"), "{saved}");
    assert!(!saved.contains("[transitions]"), "{saved}");
    assert!(!saved.contains("category_map"), "{saved}");
}

/// **NFR-003 step 5**: a **partial** `category_map` — some columns mapped, some not —
/// loads and resolves without error, and the unmapped ones report the default.
#[test]
fn nfr003_a_partial_category_map_loads_and_resolves() {
    let config = Config {
        kanban: KanbanSection {
            configurations: IndexMap::from([(
                "default".to_string(),
                BoardConfiguration {
                    columns: vec!["triage".into(), "wip".into(), "shipped".into()],
                    done_column: Some("shipped".to_string()),
                    // `wip` deliberately unmapped.
                    category_map: IndexMap::from([
                        ("triage".to_string(), "backlog".to_string()),
                        ("shipped".to_string(), "completed".to_string()),
                    ]),
                    ..Default::default()
                },
            )]),
        },
        ..Config::default()
    };
    // It must survive a save/load round trip, which is where a partial map would
    // break if the serializer dropped or defaulted an entry.
    let tmp = tempfile::TempDir::new().unwrap();
    let path = tmp.path().join("tix.toml");
    config.save(&path).unwrap();
    let loaded = Config::load_with_warning(&path, |_| {}).unwrap();
    let board = loaded.default_config();
    assert_eq!(board.category_map.len(), 2, "both entries survive");
    assert!(
        !board.category_map.contains_key("wip"),
        "and no entry is invented"
    );

    let resolution = tix::workflow::resolution(&loaded, board, "default");
    assert_eq!(
        resolution.resolve("wip").map(|c| c.key()),
        Some("unstarted"),
        "the unmapped column resolves through the documented default"
    );
    assert_eq!(
        resolution.resolve("triage").map(|c| c.key()),
        Some("backlog")
    );
    assert_eq!(
        resolution.resolve("shipped").map(|c| c.key()),
        Some("completed")
    );
    // A declared map means an **explicit** policy, so the terminal lock applies even
    // though one column is defaulted (WP03's `explicit_policy`).
    assert!(
        resolution.explicit_policy,
        "a declared category_map is an intent signal, whatever it leaves unmapped"
    );
}

/// **C-007 / T040 step 6 — the subtle asymmetry**: a board with an **explicit**
/// mapping that omits `completed` is refused at load, while a board with **no**
/// mapping at all is not.
#[test]
fn c007_an_explicit_map_without_completed_is_refused_but_no_map_is_not() {
    // The explicit map that omits `completed`: refused.
    let bad = Config {
        kanban: KanbanSection {
            configurations: IndexMap::from([(
                "default".to_string(),
                BoardConfiguration {
                    columns: vec!["triage".into(), "wip".into()],
                    done_column: Some("triage".to_string()),
                    category_map: IndexMap::from([
                        ("triage".to_string(), "backlog".to_string()),
                        ("wip".to_string(), "active".to_string()),
                    ]),
                    ..Default::default()
                },
            )]),
        },
        ..Config::default()
    };
    let tmp = tempfile::TempDir::new().unwrap();
    let path = tmp.path().join("tix.toml");
    bad.save(&path).unwrap();
    let err = Config::load_with_warning(&path, |_| {})
        .expect_err("an explicit map with no completion category must be refused")
        .to_string();
    assert!(
        err.contains("missing_completion_category"),
        "the named diagnostic, not a generic parse error: {err}"
    );

    // The same board with **no** map at all: accepted, and completion is reconciled
    // from `done_column` (WP01's legacy rule). This is the asymmetry: without the
    // section there is no declared policy to violate.
    let ok = Config {
        kanban: KanbanSection {
            configurations: IndexMap::from([(
                "default".to_string(),
                BoardConfiguration {
                    columns: vec!["triage".into(), "wip".into()],
                    done_column: Some("triage".to_string()),
                    ..Default::default()
                },
            )]),
        },
        ..Config::default()
    };
    ok.save(&path).unwrap();
    let loaded =
        Config::load_with_warning(&path, |_| {}).expect("a board with no category_map must load");
    let board = loaded.default_config();
    let resolution = tix::workflow::resolution(&loaded, board, "default");
    assert_eq!(
        resolution.resolve("triage").map(|c| c.key()),
        Some("completed"),
        "done_column reconciles to completed on a legacy board"
    );
    assert_eq!(
        resolution.resolve("wip").map(|c| c.key()),
        Some("unstarted")
    );
    assert!(
        !resolution.explicit_policy,
        "and no transition policy is imposed on a board that never declared one"
    );
}

/// Every `[categories] order` value must be in the global vocabulary, and the
/// `default` must be in `order` and must not be `completed` (WP01's validator).
#[test]
fn c007_the_category_section_is_validated() {
    // A `default` of `completed` is refused: it would make every unmapped column
    // silently count as finished.
    let bad = Config {
        categories: CategoryConfig {
            order: vec!["unstarted".into(), "completed".into()],
            default: "completed".into(),
        },
        ..Config::default()
    };
    let tmp = tempfile::TempDir::new().unwrap();
    let path = tmp.path().join("tix.toml");
    bad.save(&path).unwrap();
    let err = Config::load_with_warning(&path, |_| {})
        .expect_err("a safe default of `completed` must be refused")
        .to_string();
    assert!(err.contains("categories"), "{err}");

    // A key outside the global vocabulary is refused too.
    let invented = Config {
        categories: CategoryConfig {
            order: vec!["unstarted".into(), "invented".into()],
            default: "unstarted".into(),
        },
        ..Config::default()
    };
    invented.save(&path).unwrap();
    let err = Config::load_with_warning(&path, |_| {})
        .expect_err("a category outside the global vocabulary must be refused")
        .to_string();
    assert!(err.contains("unknown_category"), "{err}");
}

/// The keys of a TOML document, as `table.key` paths.
fn toml_key_set(text: &str) -> std::collections::BTreeSet<String> {
    let value: toml::Value = toml::from_str(text).expect("the fixture parses");
    let mut out = std::collections::BTreeSet::new();
    collect_keys(&value, "", &mut out);
    out
}

fn collect_keys(value: &toml::Value, prefix: &str, out: &mut std::collections::BTreeSet<String>) {
    let table = match value.as_table() {
        Some(t) => t,
        None => return,
    };
    for (key, child) in table {
        let path = if prefix.is_empty() {
            key.clone()
        } else {
            format!("{prefix}.{key}")
        };
        out.insert(path.clone());
        collect_keys(child, &path, out);
    }
}

// ---------------------------------------------------------------------------
// T041 — SC-005 / C-005: inertness and no History rewrite
// ---------------------------------------------------------------------------

/// **SC-005 inertness**: a rejected transition changes **nothing** — no issue file, no
/// `tix.toml`, no History entry — on every surface that can be driven from here.
///
/// Whole-directory byte snapshots rather than one file: a mutation that wrote a
/// *different* file, or created a `.bak`, passes a single-file comparison.
///
/// (These four cases were lost to an index-based text edit and rewritten. Recorded
/// because the loss was only visible because the helpers they used stopped being
/// referenced — which is what the `dead_code` warnings in this file's build output
/// are for.)
#[test]
fn sc005_a_rejected_transition_is_inert_on_every_surface() {
    // CLI `tix move`.
    let (tmp, _store) = mapped_repo();
    let before = snapshot(tmp.path());
    let out = cli(tmp.path(), &["move", "4", "triage"]);
    assert!(!out.status.success());
    assert_eq!(
        diagnostic_of(&stderr_of(&out)),
        "invalid_transition",
        "and it is a policy refusal, not a typo"
    );
    assert_eq!(
        snapshot(tmp.path()),
        before,
        "C-005: the CLI's refusal wrote nothing"
    );

    // CLI `tix edit --status`.
    let (tmp, _store) = mapped_repo();
    let before = snapshot(tmp.path());
    let out = cli(tmp.path(), &["edit", "4", "--status", "triage"]);
    assert!(!out.status.success());
    assert_eq!(snapshot(tmp.path()), before, "and neither did `tix edit`");

    // MCP.
    let (tmp, store) = mapped_repo();
    let before = snapshot(tmp.path());
    let result = mcp(
        &store.config,
        &store,
        "move_issue",
        serde_json::json!({ "issue": "4", "column": "triage" }),
    );
    assert_eq!(result["isError"], true);
    assert_eq!(
        diagnostic_of(result["content"][0]["text"].as_str().unwrap()),
        "invalid_transition"
    );
    assert_eq!(snapshot(tmp.path()), before, "and neither did MCP");
}

/// **SC-005 step 2 — the positive control.** A valid transition *does* change the
/// expected file and appends exactly one decision.
///
/// Without this, the case above also passes on a fixture nothing can write — the same
/// class of vacuous assertion this programme has now found eight times. The test
/// below is deliberately a **separate** test rather than a block inside the inertness
/// one, so a failure names which of the two claims broke.
#[test]
fn sc005_a_valid_transition_changes_exactly_one_file_and_appends_one_decision() {
    let (tmp, store) = mapped_repo();
    let before = snapshot(tmp.path());
    let out = cli(tmp.path(), &["move", "1", "wip"]).assert_ok();

    let after = snapshot(tmp.path());
    let changed: Vec<&String> = after
        .iter()
        .filter(|(path, bytes)| {
            before
                .iter()
                .find(|(p, _)| p == path)
                .is_none_or(|(_, b)| b != bytes)
        })
        .map(|(p, _)| p)
        .collect();
    assert_eq!(
        changed.len(),
        1,
        "exactly one file may change; changed: {changed:?}"
    );
    assert!(
        changed[0].contains("issue1"),
        "and it must be the moved issue: {changed:?}"
    );
    let _ = &out;

    let history = history_of(&store, 1);
    let decisions = history
        .lines()
        .filter(|l| l.contains("transition_accepted"))
        .count();
    assert_eq!(decisions, 1, "exactly one decision:\n{history}");
    assert!(
        history.contains("triage -> wip"),
        "and it names the move:\n{history}"
    );
}

/// **SC-005 step 3**: a hand-edited `status:` is **reported** by `tix lint`, and
/// **neither the file nor its History is rewritten**.
#[test]
fn sc005_lint_reports_a_direct_edit_without_rewriting_the_file_or_its_history() {
    let (tmp, store) = mapped_repo();
    // Give the issue a real decision first, so there is something to contradict.
    cli(tmp.path(), &["move", "1", "wip"]).assert_ok();
    let path = issue_path(&store, 1);

    // Hand-edit the status the way an editor would.
    let original = fs::read_to_string(&path).unwrap();
    let edited = original.replace("status: wip", "status: shipped");
    assert_ne!(edited, original, "the fixture must actually be edited");
    fs::write(&path, &edited).unwrap();

    let before = snapshot(tmp.path());
    let out = cli(tmp.path(), &["lint"]);
    let stderr = stderr_of(&out);
    assert!(
        stderr.contains("direct_edit_policy_violation"),
        "the violation must be reported:\n{stderr}"
    );
    assert_eq!(
        snapshot(tmp.path()),
        before,
        "C-005: lint is read-only — the hand-edited file, its History and tix.toml \
         are all byte-identical afterwards"
    );
    assert_eq!(
        fs::read_to_string(&path).unwrap(),
        edited,
        "including the line the user changed"
    );
}

/// **SC-005 step 4**: the violation is a **report**, not a load failure. The
/// hand-edited file stays readable and other commands still work on it.
#[test]
fn sc005_a_direct_edit_is_still_readable_and_usable() {
    let (tmp, store) = mapped_repo();
    cli(tmp.path(), &["move", "1", "wip"]).assert_ok();
    let path = issue_path(&store, 1);
    let original = fs::read_to_string(&path).unwrap();
    fs::write(&path, original.replace("status: wip", "status: shipped")).unwrap();

    for args in [vec!["list"], vec!["show", "1"], vec!["status"]] {
        let out = cli(tmp.path(), &args);
        assert!(
            out.status.success(),
            "{args:?} must still work on a hand-edited file: {}",
            stderr_of(&out)
        );
    }
    // `tix lint` is the exception, and the exception is the point: a direct-edit
    // violation is an **error**, so `lint` exits non-zero — it is *reporting*, not
    // failing to load. Asserted as "it reported and did not crash", because the first
    // version of this test lumped `lint` in with the reads and failed on an exit code
    // that is the correct behaviour.
    let linted = cli(tmp.path(), &["lint"]);
    let stderr = stderr_of(&linted);
    assert!(
        stderr.contains("direct_edit_policy_violation"),
        "`tix lint` must still report the violation: {stderr}"
    );
    assert!(
        !stderr.contains("panic") && !stderr.contains("could not be parsed"),
        "and must not have failed to read the file: {stderr}"
    );
    // And the reported status is the one in the file, not the one in History.
    let shown = stdout_of(&cli(
        tmp.path(),
        &["list", "--all", "--columns", "num,title,status"],
    ));
    assert!(
        shown.contains("shipped"),
        "`tix list` reports the file, not the history: {shown}"
    );
}

/// **SC-005 step 5**: re-applying a transition is inert on the CLI and on MCP — no
/// write, no bumped `updated`, no second decision.
#[test]
fn sc005_reapplying_a_transition_is_inert_on_cli_and_mcp() {
    let (tmp, store) = mapped_repo();
    cli(tmp.path(), &["move", "1", "wip"]).assert_ok();
    let after_first = snapshot(tmp.path());

    let out = cli(tmp.path(), &["move", "1", "wip"]).assert_ok();
    assert_eq!(
        snapshot(tmp.path()),
        after_first,
        "a same-column re-apply writes nothing, bumps no date and appends no decision"
    );
    let _ = &out;

    let result = mcp(
        &store.config,
        &store,
        "move_issue",
        serde_json::json!({ "issue": "1", "column": "wip" }),
    );
    assert_eq!(result["isError"], false, "{}", result["content"][0]["text"]);
    assert_eq!(snapshot(tmp.path()), after_first, "and neither does MCP");
}

/// The file backing issue `number`.
///
/// The store is laid out by **assignee segment**, so the file is found by scanning
/// one level rather than by assuming a segment name — the segment is derived from the
/// git identity, which is not the same on every machine a test runs on.
fn issue_path(store: &tix::storage::Store, number: u32) -> PathBuf {
    let issue = store
        .get(tix::storage::IssueSelector::Number(number))
        .unwrap();
    // The **basename**, scanned under the issues dir, rather than
    // `issues_dir/<filename>`: `filename` carries the assignee segment
    // (`alice/2026-01-01-slug.md`) on some paths and a bare stem on others, so a
    // `join` either double-prefixes or misses. Walking and matching the last
    // component is the one form that works for both layouts — and this repository
    // supports both (the flat one is the legacy layout, still read).
    let want = Path::new(&issue.filename)
        .file_name()
        .expect("a filename has a last component");
    let mut stack = vec![store.issues_dir.clone()];
    while let Some(cur) = stack.pop() {
        for entry in fs::read_dir(&cur).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                stack.push(path);
            } else if path.file_name() == Some(want) {
                return path;
            }
        }
    }
    panic!(
        "no file named {want:?} under {}",
        store.issues_dir.display()
    );
}

/// The issue's full file contents, which is where its `## History` lives.
fn history_of(store: &tix::storage::Store, number: u32) -> String {
    store
        .get(tix::storage::IssueSelector::Number(number))
        .unwrap()
        .to_file_contents()
}

/// A small `assert_ok` shim, so a command is one line and the failure carries stderr.
trait AssertOk {
    fn assert_ok(self) -> std::process::Output;
}

impl AssertOk for std::process::Output {
    fn assert_ok(self) -> std::process::Output {
        assert!(
            self.status.success(),
            "expected success, got {}: {}",
            self.status,
            stderr_of(&self)
        );
        self
    }
}