tix-tracker 0.11.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
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
//! The single owner of category resolution, completion, and transition legality.
//!
//! **Filesystem-free on purpose.** Nothing here reads or writes an issue file, and
//! nothing here takes a `Store`. The module returns the accepted transition and
//! the decision to append; WP03's storage seam performs the write. That is what
//! lets the CLI, the TUI, MCP, sync and every analytic share one implementation
//! instead of five that agree today (contract §2).
//!
//! **`blocked` here is a workflow column position, not blocked *state*.** The
//! derived blocked state — an open inbound `blocks` edge — is a graph fact owned
//! by issue 169's Mission and lives in `relationships.rs`. The two are different
//! things and the contract names conflating them a rejected alternative
//! (`category-vocabulary.md` §6).
//!
//! **Resolution is built once**, at config load, and is not rebuilt per issue or
//! per surface. The per-issue path is a single hash lookup, which is what holds
//! NFR-001 for a 10,000-issue sweep (contract §7). Rebuilding it per issue is the
//! failure mode this design exists to prevent, and `resolution` is built from a
//! board rather than from an issue so that it cannot be.

use std::collections::HashMap;
use std::fmt;

use crate::config::{
    BoardConfiguration, CATEGORY_KEYS, COMPLETE_CATEGORY, Config, SAFE_DEFAULT_CATEGORY,
};
use crate::model::Issue;

/// A category in the fixed global vocabulary (C-002).
///
/// The vocabulary is global and closed: a board maps its columns *into* these
/// keys and does not define its own. The spelling comes from WP01's
/// [`CATEGORY_KEYS`] rather than from string literals here, so the config
/// validator and this service cannot disagree about what a category is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum WorkflowCategory {
    Backlog,
    Unstarted,
    Active,
    Blocked,
    Completed,
    Canceled,
}

impl WorkflowCategory {
    /// Every category, in the vocabulary's order.
    pub const ALL: [WorkflowCategory; 6] = [
        WorkflowCategory::Backlog,
        WorkflowCategory::Unstarted,
        WorkflowCategory::Active,
        WorkflowCategory::Blocked,
        WorkflowCategory::Completed,
        WorkflowCategory::Canceled,
    ];

    /// The canonical spelling used in config and in output.
    pub fn key(self) -> &'static str {
        match self {
            WorkflowCategory::Backlog => "backlog",
            WorkflowCategory::Unstarted => "unstarted",
            WorkflowCategory::Active => "active",
            WorkflowCategory::Blocked => "blocked",
            WorkflowCategory::Completed => "completed",
            WorkflowCategory::Canceled => "canceled",
        }
    }

    /// Parse a key, or `None` for anything outside the vocabulary.
    ///
    /// The `Option` is load-bearing: an unknown key is an error
    /// (`unknown_category`), never a coerced default. A `from_key` that fell back
    /// to `unstarted` would turn a typo in a config into a board where a column
    /// silently means something else.
    pub fn from_key(key: &str) -> Option<Self> {
        CATEGORY_KEYS
            .iter()
            .position(|k| *k == key)
            .map(|i| Self::ALL[i])
    }

    /// Whether this category ends the workflow.
    ///
    /// True for `completed` **and** `canceled` — which is exactly why completion is
    /// not `is_terminal()`. A category can end the work without the work having
    /// been completed.
    pub fn is_terminal(self) -> bool {
        matches!(
            self,
            WorkflowCategory::Completed | WorkflowCategory::Canceled
        )
    }

    /// Whether this category means the work is done.
    ///
    /// The **only** definition of completion in the crate. `canceled` is terminal
    /// and not complete.
    pub fn is_complete(self) -> bool {
        self.key() == COMPLETE_CATEGORY
    }

    /// Display text. Presentation only; never consulted for a decision.
    pub fn label(self) -> &'static str {
        match self {
            WorkflowCategory::Backlog => "Backlog",
            WorkflowCategory::Unstarted => "Not started",
            WorkflowCategory::Active => "In progress",
            WorkflowCategory::Blocked => "Blocked",
            WorkflowCategory::Completed => "Done",
            WorkflowCategory::Canceled => "Canceled",
        }
    }

    /// A presentation hint for the TUI, or `None` where there is nothing to say.
    ///
    /// **Inert.** It never affects resolution, policy, or reporting — a category
    /// with a colour and a category without one resolve identically. A colour that
    /// changed a decision would make the board's appearance load-bearing.
    pub fn color_hint(self) -> Option<ColorHint> {
        match self {
            WorkflowCategory::Backlog => Some(ColorHint::Dim),
            WorkflowCategory::Active => Some(ColorHint::Accent),
            WorkflowCategory::Blocked => Some(ColorHint::Warn),
            WorkflowCategory::Completed => Some(ColorHint::Ok),
            WorkflowCategory::Canceled => Some(ColorHint::Muted),
            // Deliberately `None`: "not started" is the absence of work, and
            // giving it a colour would make an untouched card look like a
            // deliberate state.
            WorkflowCategory::Unstarted => None,
        }
    }
}

/// A presentation hint. See [`WorkflowCategory::color_hint`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorHint {
    Dim,
    Accent,
    Warn,
    Ok,
    Muted,
}

/// The built once-per-load derivation from column name to category
/// (`data-model.md` §3).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CategoryResolution {
    /// Every configured column and its category. Looked up, never scanned.
    by_column: HashMap<String, WorkflowCategory>,
    /// Every configured column, in **board order**.
    ///
    /// WP03. `by_column` is a `HashMap`, so iterating it yields keys in an
    /// unspecified order. That was harmless while `columns()` had no callers, but
    /// [`Self::columns`] already *documented* board order while being unable to
    /// deliver it, and WP03's widened `unknown_column` message prints the valid
    /// columns to the user. A `HashMap` order would make that list differ between
    /// two runs over the same config — an unstable error message, and a test that
    /// passes or fails on the allocator's whim.
    ///
    /// A second copy of the key set, not a replacement: lookups stay `O(1)` on
    /// `by_column`, and this vector exists only to make iteration deterministic.
    order: Vec<String>,
    /// Configured columns that resolved by the safe default rather than by an
    /// explicit mapping, in board order.
    ///
    /// Recorded so a surface can report `unmapped_column_default` "where ambiguity
    /// matters". A column silently defaulting is the thing the contract is most
    /// careful about, and it cannot be reported from the map alone.
    pub unmapped: Vec<String>,
    /// Whether any column relied on the default. Lets a caller skip the
    /// diagnostic entirely on a fully-mapped board.
    pub default_applied: bool,
    /// Whether the board **declared** a `category_map`, as opposed to resolving
    /// every column through the safe default.
    ///
    /// WP03. This is the signal that separates a board whose author described its
    /// categories from one that never did, and it is what gates the **terminal
    /// lock**. Without it, WP01's legacy reconciliation (`done_column` resolves to
    /// `completed` so completion detection works, FR-003) would silently hand every
    /// existing repository a transition policy it never configured: moving an issue
    /// back out of `done` would start failing on every board in the wild, and on the
    /// TUI there is no flag or key to override it with for two more work packages.
    ///
    /// Deliberately distinct from [`Self::default_applied`]: a board may declare a
    /// `category_map` and still leave some columns to the default, so
    /// `default_applied` is "some column is unmapped" while this is "a map was
    /// written at all". The lock is about intent, and intent is expressed by the
    /// presence of the section.
    ///
    /// Note the consequence, since it is a real one: a legacy board gets the
    /// **completion** definition and the **commit-clearing** rule, but not the
    /// terminal lock. Those are different things — completion answers "is this
    /// done?", the lock answers "may this move?" — and the contract treats them in
    /// different sections for that reason.
    pub explicit_policy: bool,
    /// The board's name, for diagnostics.
    pub board: String,
}

impl CategoryResolution {
    /// The category `column` resolves to, or `None` for a column this board does
    /// not configure.
    ///
    /// A hash lookup. A caller that needs to distinguish "not configured" from
    /// "configured but defaulted" uses [`Self::unmapped`].
    pub fn resolve(&self, column: &str) -> Option<WorkflowCategory> {
        self.by_column.get(column).copied()
    }

    /// Every column this board configures, in board order.
    ///
    /// Reads [`Self::order`], not `by_column`, so the sequence is the board's own
    /// declaration order and is the same on every run (see the field's note).
    pub fn columns(&self) -> impl Iterator<Item = &str> {
        self.order.iter().map(String::as_str)
    }

    /// The board's columns joined for a message, in board order.
    ///
    /// WP03. A `unknown_column` refusal is the one diagnostic a user reads to work
    /// out what to type instead, so it must list the valid columns. Rendering that
    /// list in one place keeps every `unknown_column` message agreeing on it.
    pub fn column_list(&self) -> String {
        self.order.join(", ")
    }

    /// Whether any column resolves to `completed`.
    pub fn has_completion(&self) -> bool {
        self.by_column.values().any(|c| c.is_complete())
    }
}

/// Build the resolution for `board`.
///
/// **Once per config load.** The per-issue path is a lookup against the result.
///
/// The legacy reconciliation lives in [`BoardConfiguration::category_for`], which
/// WP01 wrote and this module does not duplicate: a board with no `category_map`
/// resolves its `done_column` to `completed` and everything else to the safe
/// default. Duplicating that fallback here is how a board ends up with two
/// notions of its own default.
pub fn resolution(
    config: &Config,
    board: &BoardConfiguration,
    board_name: &str,
) -> CategoryResolution {
    let mut by_column = HashMap::with_capacity(board.columns.len());
    let mut unmapped = Vec::new();
    for column in &board.columns {
        let key = board.category_for(column, &config.categories);
        // An unmapped-and-not-done column is the one that relied on the default.
        // `category_for` returns the safe default for those, and `category_map`
        // says whether the entry was explicit.
        let explicit = board.category_map.contains_key(column);
        if !explicit {
            unmapped.push(column.clone());
        }
        // `category_for` is total over `columns` because the fallback covers
        // everything, so this cannot be `None`; `from_key` cannot be `None`
        // because config load validated the vocabulary. Both are `expect`ed with
        // the reason rather than defaulted, so a violated invariant is loud.
        let category = WorkflowCategory::from_key(key).unwrap_or_else(|| {
            unreachable!("config load rejected the vocabulary, so `{key}` is in it")
        });
        by_column.insert(column.clone(), category);
    }
    CategoryResolution {
        by_column,
        order: board.columns.clone(),
        default_applied: !unmapped.is_empty(),
        explicit_policy: !board.category_map.is_empty(),
        unmapped,
        board: board_name.to_string(),
    }
}

/// The single completion decision (contract §4).
///
/// True only when the issue's column maps to `completed`. `canceled` is terminal
/// and **not** complete, and an unmapped column resolves to the safe default, so
/// it is never silently counted as done.
///
/// Never errors: an issue in a column the board does not configure is not
/// complete. That is a board that failed validation, not a reason to fail a read.
pub fn is_completed(issue: &Issue, resolution: &CategoryResolution) -> bool {
    resolution
        .resolve(issue.status.display())
        .is_some_and(WorkflowCategory::is_complete)
}

/// The board's **completion column**, chosen by category rather than by
/// `done_column` (WP09).
///
/// ## Why this exists
///
/// `BoardConfiguration::effective_done_column()` answers a *config* question — "what
/// did the author name?" — and on a board with a `category_map` it is not the same
/// question as "which column is complete?". A board whose map puts `completed` on
/// `shipped` while `done_column` is `done` has two different answers, and every
/// consumer that asked the config question got the wrong one.
///
/// That is not hypothetical. The blocked-move guard — the previous mission's central
/// feature — read `done_column` and early-returned for any other column, so on such
/// a board:
///
/// - a **blocked** issue moved into `shipped` (genuinely complete) got **no
///   warning, no `--yes` requirement, and no `blocked_move_acknowledged` History
///   entry**; and
/// - moving it to `done` (not complete at all) **did** demand confirmation, because
///   that is the column the config named.
///
/// The guard was silently disabled on exactly the boards this mission exists to
/// support. Found by the call-site audit T038 step 4 asks for, which is the argument
/// for having one: the pattern is five lines long and the consequence is a safety
/// check that does not run.
///
/// ## Which column, when several are complete
///
/// The **first** configured column whose category is complete, in board order. A
/// board with two completed columns has no single completion column, and the first is
/// the only choice that does not depend on iteration order. `None` only for a board
/// that failed validation — nothing resolves to `completed` — which the callers
/// handle rather than this function panicking on a config the caller could not have
/// built.
pub fn completion_column(board: &BoardConfiguration, config: &Config) -> Option<String> {
    let resolution = resolution(config, board, active_board_name(config));
    board
        .columns
        .iter()
        .find(|c| {
            resolution
                .resolve(c)
                .is_some_and(WorkflowCategory::is_complete)
        })
        .cloned()
}

/// The board's completion column, **total**: the first complete column, else the
/// configured `done_column`, else the literal `"done"` (WP09).
///
/// ## Why the fallback lives here and not at each call site
///
/// Three callers need "the completion column, and I cannot have a `None`" because
/// they hand the name to a service that takes it as a parameter
/// (`RelationshipGraph`, `hierarchy_cells`, `blocked_reasons`, `child_markers`).
/// Writing the fallback at each site meant four copies of
/// `.or_else(done_column).unwrap_or("done")` — and one of them drifted, which is how
/// the TUI's blocked marker ended up computed against `done_column` while the CLI's
/// used the service. One function, one fallback, one place to be right.
///
/// The fallback order is deliberate: the service's answer is the **meaning**, a
/// configured `done_column` is a reasonable second guess for a board that failed
/// validation, and the literal is a last resort so a caller that must produce a name
/// always can. Only the first is authoritative, and only the first is ever reached by
/// a config that loads.
pub fn completion_column_or_default(board: &BoardConfiguration, config: &Config) -> String {
    completion_column(board, config)
        .or_else(|| board.effective_done_column().map(str::to_string))
        .unwrap_or_else(|| "done".to_string())
}

/// The issue's category, or `None` for a column the board does not configure.
pub fn category_of(issue: &Issue, resolution: &CategoryResolution) -> Option<WorkflowCategory> {
    resolution.resolve(issue.status.display())
}

/// The fixed diagnostic vocabulary (contract §6).
///
/// One set, so the CLI, TUI, MCP and lint report a violation under the same name
/// rather than four names for one condition.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DiagnosticKind {
    MissingCompletionCategory,
    UnknownCategory,
    MappingForUnknownColumn,
    UnmappedColumnDefault,
    InvalidTransition,
    UnknownColumn,
    DirectEditPolicyViolation,
}

impl DiagnosticKind {
    pub const ALL: [DiagnosticKind; 7] = [
        DiagnosticKind::MissingCompletionCategory,
        DiagnosticKind::UnknownCategory,
        DiagnosticKind::MappingForUnknownColumn,
        DiagnosticKind::UnmappedColumnDefault,
        DiagnosticKind::InvalidTransition,
        DiagnosticKind::UnknownColumn,
        DiagnosticKind::DirectEditPolicyViolation,
    ];

    pub fn as_str(self) -> &'static str {
        match self {
            DiagnosticKind::MissingCompletionCategory => "missing_completion_category",
            DiagnosticKind::UnknownCategory => "unknown_category",
            DiagnosticKind::MappingForUnknownColumn => "mapping_for_unknown_column",
            DiagnosticKind::UnmappedColumnDefault => "unmapped_column_default",
            DiagnosticKind::InvalidTransition => "invalid_transition",
            DiagnosticKind::UnknownColumn => "unknown_column",
            DiagnosticKind::DirectEditPolicyViolation => "direct_edit_policy_violation",
        }
    }
}

/// One finding. The service never writes, so a diagnostic is the only output a
/// refusal produces.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorkflowDiagnostic {
    pub kind: DiagnosticKind,
    /// The board, column, or issue the finding is about, rendered for a message.
    pub subject: String,
    pub message: String,
}

impl fmt::Display for DiagnosticKind {
    /// The contract's fixed name, so a surface that renders a refusal names the
    /// condition the same way every other surface does (contract §6).
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl fmt::Display for WorkflowDiagnostic {
    /// `(<kind>) for <subject>: <message>`.
    ///
    /// WP03. The kind leads, in parentheses, because the *name* is the part a
    /// caller can match on — a user reporting a bug, a test asserting the
    /// condition, and a grep over logs all key off it. `subject` sits in the
    /// middle because it says what was attempted, and `message` says why not.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "({}) for {}: {}", self.kind, self.subject, self.message)
    }
}

/// Configuration findings across every board.
///
/// **Never errors.** It returns a value so lint, the CLI and MCP can consume it
/// directly, and so a caller can decide for itself which findings are fatal.
/// WP01 already refuses the fatal ones at load; what is added here is the
/// board-level reporting WP01 cannot express — chiefly `unmapped_column_default`.
///
/// Deterministic: sorted by board, then column, then kind, so two runs over the
/// same config produce the same list and a test can compare it directly.
pub fn validate_config(config: &Config) -> Vec<WorkflowDiagnostic> {
    let mut out = Vec::new();
    for (name, board) in &config.kanban.configurations {
        let res = resolution(config, board, name);
        if !res.has_completion() {
            out.push(WorkflowDiagnostic {
                kind: DiagnosticKind::MissingCompletionCategory,
                subject: name.clone(),
                message: format!(
                    "no column on board `{name}` resolves to `{COMPLETE_CATEGORY}`, so \\
                     nothing on it is ever complete"
                ),
            });
        }
        for (column, key) in &board.category_map {
            if !board.columns.iter().any(|c| c == column) {
                out.push(WorkflowDiagnostic {
                    kind: DiagnosticKind::MappingForUnknownColumn,
                    subject: format!("{name}.{column}"),
                    message: format!("`{column}` is not a column on board `{name}`"),
                });
            }
            if WorkflowCategory::from_key(key).is_none() {
                out.push(WorkflowDiagnostic {
                    kind: DiagnosticKind::UnknownCategory,
                    subject: format!("{name}.{column}"),
                    message: format!("`{key}` is not in the global category vocabulary"),
                });
            }
        }
        for column in &res.unmapped {
            // WP04: a column whose *default* is the completion category is not a
            // finding. That is the legacy reconciliation this mission settled on
            // (WP01): a board with no `category_map` resolves its `done_column` to
            // `completed` so completion detection works on every existing
            // repository.
            //
            // Reporting it as `unmapped_column_default` — as WP02 did — produced one
            // finding per column on every board in the world, including the column
            // the board *intends* to be done, and each message said it "resolves to
            // the safe default `unstarted`" about a column that had resolved to
            // `completed`. The diagnostic pointed the user at the exact thing that
            // was working.
            //
            // It still belongs in `CategoryResolution::unmapped` — the **policy**
            // opt-in reads that, not this diagnostic. What changed is only whether
            // it is worth telling someone about.
            let resolved = res.resolve(column);
            if resolved.is_some_and(WorkflowCategory::is_complete) {
                continue;
            }
            out.push(WorkflowDiagnostic {
                kind: DiagnosticKind::UnmappedColumnDefault,
                subject: format!("{name}.{column}"),
                message: format!(
                    "column `{column}` has no `category_map` entry, so it resolves to the \\
                     safe default `{}`",
                    resolved
                        .map(|c| c.key())
                        .unwrap_or(config.categories.default.as_str())
                ),
            });
        }
    }
    out.sort_by(|a, b| {
        a.subject
            .cmp(&b.subject)
            .then_with(|| a.kind.cmp(&b.kind))
            .then_with(|| a.message.cmp(&b.message))
    });
    out
}

/// An explicit override out of a terminal category.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransitionOverride {
    /// Why. Required: an override with no reason is not recorded as one, because
    /// a bare "I did it anyway" is indistinguishable from a mistake.
    pub reason: String,
}

/// The outcome of judging a transition.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TransitionOutcome {
    /// Legal. `changed` is false for a same-column transition, which is permitted
    /// and idempotent — no decision to append, no write.
    Accepted {
        from: String,
        to: String,
        from_category: WorkflowCategory,
        to_category: WorkflowCategory,
        changed: bool,
        /// The override, when one was supplied and used.
        override_reason: Option<String>,
    },
    /// Refused. Nothing is written, including no History entry (contract §3.5).
    Rejected(WorkflowDiagnostic),
}

/// The name of the board [`Config::default_config`] resolves to.
///
/// WP04. `default_config` is a lookup of `"default"` falling back to the first
/// declared board, and re-deriving that at a call site would be a second copy of
/// a rule that decides *which* board the whole program operates on. A diagnostic
/// naming a different board than the one consulted would be worse than no name.
///
/// Returns `"default"` when the config has no board at all, which
/// `Config::validate` already rejects; the fallback exists so a diagnostic is
/// never the thing that panics.
pub fn active_board_name(config: &Config) -> &str {
    config
        .kanban
        .configurations
        .keys()
        .find(|name| name.as_str() == "default")
        .map(String::as_str)
        .or_else(|| {
            config
                .kanban
                .configurations
                .keys()
                .next()
                .map(String::as_str)
        })
        .unwrap_or("default")
}

/// The [`CategoryResolution`] for the active board, plus that board's name.
///
/// WP04. Every surface needs the same pair — the seam to judge a transition, and
/// `tix status` / `tix list` / `tix workflow show` to render a category — and
/// building the resolution ad hoc at each site is how one of them ends up
/// consulting a different board than the others. The name comes back alongside
/// because every one of those renderers has to name the board it consulted.
pub fn active_resolution(config: &Config) -> (String, CategoryResolution) {
    let name = active_board_name(config);
    let resolution = resolution(config, config.default_config(), name);
    (name.to_string(), resolution)
}

/// One direct-edit finding: a file whose `status` no longer agrees with its History.
///
/// WP06. Separate from [`WorkflowDiagnostic`] because it has to carry **both** sides
/// of the contradiction — the recorded `from` and the current column — and a message
/// that names the rule. A `WorkflowDiagnostic` reports a condition; this reports a
/// disagreement between a record and a file, which is a different thing to say.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DirectEditFinding {
    /// The issue number, so a caller can find the file without re-parsing.
    pub number: u32,
    pub kind: DiagnosticKind,
    /// The column the accepted decision landed in, or `None` when the file records
    /// no usable decision at all.
    pub recorded: Option<String>,
    /// The column the file says now.
    pub current: String,
    /// The rule that was broken, in words.
    pub message: String,
}

/// Report files whose `status` contradicts their own History (contract §5, C-005).
///
/// ## What it does and does not conclude
///
/// Two conditions, and both are conclusions about the *record*, not about intent:
///
/// 1. **The status diverged from the last accepted decision.** The file's History
///    says a transition landed in `recorded`; the file says `current`. Something
///    changed the column without going through the seam.
/// 2. **The recorded decision contradicts the current policy.** The decision was
///    accepted; re-evaluating it now is refused — the terminal lock, or adjacency.
///    A board's `category_map` may have been tightened since, and the historical
///    decision is still a true record of what happened then.
///
/// ## What is deliberately *not* a violation
///
/// **A file with no decision at all.** An issue created directly into a column has
/// no transition to record, and creating one in a terminal column is legal — there
/// is no `from` to judge. Reporting every such file would fire on every issue in a
/// repository that has never been moved, which is lint's characteristic failure mode:
/// a finding nobody reads.
///
/// A **same-column** decision record is likewise not a violation. The seam never
/// writes one, but a hand-edited file can contain one, and it records no move.
///
/// ## Never writes
///
/// This function, and everything that calls it, is **observational**. It does not
/// repair the file, does not append a History entry, does not rewrite existing
/// History, and offers no "fix" affordance (C-005, decision
/// `01M3C3XBMTR5WFV7059NXM04AJ`). A hand-edited file stays exactly as the user left
/// it and stays readable; the contradiction is theirs to resolve.
///
/// ## One pass, deterministic order
///
/// A single sweep, not one per rule, and each file reported **once** — a file that
/// diverged *and* whose decision now contradicts policy is one finding naming the
/// stronger of the two, not two findings for one root cause.
pub fn lint_direct_edits(
    issues: &[Issue],
    resolution: &CategoryResolution,
    config: &Config,
) -> Vec<DirectEditFinding> {
    let mut out: Vec<DirectEditFinding> = Vec::new();
    for issue in issues {
        let current = issue.status.display().to_string();
        // The last *usable* decision. `History::events()` skips lines it could not
        // parse, so a corrupted `transition_accepted` line reads here as "no
        // decision" — which is why the no-decision case is not a violation. The
        // alternative would be a diagnostic for a corrupt audit line, and the
        // contract's seven names do not include one; inventing an eighth is
        // exactly the kind of claim the shared vocabulary exists to prevent.
        let decision = issue
            .history
            .events()
            .iter()
            .rev()
            .filter(|e| e.kind == crate::model::HistoryEventKind::TransitionAccepted)
            .find_map(|e| crate::model::TransitionDecision::from_event(e).ok())
            .filter(|d| !d.is_no_op());

        let Some(decision) = decision else {
            continue;
        };

        if decision.to != current {
            out.push(DirectEditFinding {
                number: issue.number,
                kind: DiagnosticKind::DirectEditPolicyViolation,
                recorded: Some(decision.to.clone()),
                current: current.clone(),
                message: format!(
                    "status is `{current}` but this issue's History records the last \
                     accepted transition as landing in `{}`; the file was changed \
                     outside `tix`",
                    decision.to
                ),
            });
            continue;
        }

        // The status agrees with the record, so the only remaining question is
        // whether the recorded move still satisfies policy. Re-evaluated against the
        // *current* config, which is the point: a tightened `category_map` makes a
        // historical decision look wrong, and that is worth knowing even though the
        // record is accurate.
        //
        // `is_compatible(from, to, …)`, **not** `validate_transition(issue, from, …)`.
        // The first version used the latter and evaluated the *current* column back
        // to the recorded `from` — so it judged the reverse of the decision that was
        // actually recorded, and reported every legal forward move in the repository
        // as a policy violation. `is_compatible` is the predicate for exactly this
        // question: "may this pair of columns move?" without inventing an issue.
        let from = decision.from.clone();
        let to = decision.to.clone();
        if !is_compatible(&from, &to, resolution, config) {
            out.push(DirectEditFinding {
                number: issue.number,
                kind: DiagnosticKind::DirectEditPolicyViolation,
                recorded: Some(to.clone()),
                current,
                message: format!(
                    "the accepted transition recorded in this issue's History \
                     (`{from}` -> `{to}`) is no longer permitted by the current \
                     policy; the record is accurate but the board's category mapping \
                     has since changed"
                ),
            });
        }
    }
    // Deterministic: by issue number, then by the columns involved. Two runs over the
    // same tree must produce the same list, byte for byte (contract §5).
    out.sort_by(|a, b| {
        a.number
            .cmp(&b.number)
            .then_with(|| a.current.cmp(&b.current))
            .then_with(|| a.recorded.cmp(&b.recorded))
    });
    out
}

/// The pure compatibility predicate behind [`validate_transition`].
///
/// Separated so the policy is testable without constructing a decision, and so a
/// caller that only wants to know "may this move?" does not have to invent a
/// decision to ask. Never errors: an unconfigured column is simply incompatible.
pub fn is_compatible(
    from_column: &str,
    to_column: &str,
    resolution: &CategoryResolution,
    config: &Config,
) -> bool {
    // Category policy — the terminal lock and adjacency alike — is **opt in**,
    // gated on `explicit_policy`. WP03: a board that never declared a
    // `category_map` gets the completion definition and the commit-clearing rule
    // and nothing else, because those are about *what* a column means while
    // policy is about *what may change*.
    //
    // The two are gated together deliberately, and they have to be. On a legacy
    // board every non-done column resolves to the single `unstarted` category, so
    // adjacency's "may not move backwards in the declared order" is exactly the
    // terminal lock minus the reasoned override — `completed` is last in the
    // vocabulary, so every exit from it is also backwards. Gating only the lock
    // would therefore have left adjacency to refuse the very moves the lock was
    // relaxed to allow, with a message that does not mention an override. The
    // first version of this change did exactly that, and its two TUI tests stayed
    // red.
    let policy_applies = config.transitions.terminal_locked && resolution.explicit_policy;

    // Same column is permitted and idempotent, whatever the category (contract §3.2).
    if from_column == to_column {
        return true;
    }
    let (Some(from), Some(to)) = (
        resolution.resolve(from_column),
        resolution.resolve(to_column),
    ) else {
        return false;
    };
    // The terminal lock is category-level, so it is written once here rather than
    // per column pair.
    if policy_applies && from.is_terminal() && !to.is_terminal() {
        return false;
    }
    // Adjacency: a category may move to itself or forward through the declared
    // order. Going backwards is what a policy rule restricts, and expressing it on
    // the order means a board with custom column names needs no configuration for
    // it to behave.
    if !policy_applies {
        return true;
    }
    let order = |c: WorkflowCategory| {
        config
            .categories
            .order
            .iter()
            .position(|k| k == c.key())
            .unwrap_or(usize::MAX)
    };
    order(to) >= order(from)
}

/// The single transition evaluation (contract §3).
///
/// The only place legality is decided. A surface that judges a transition on its
/// own is a parity defect.
pub fn validate_transition(
    issue: &Issue,
    target_column: &str,
    resolution: &CategoryResolution,
    config: &Config,
    override_reason: Option<&str>,
) -> TransitionOutcome {
    let from_column = issue.status.display().to_string();
    let reject = |kind: DiagnosticKind, message: String| {
        TransitionOutcome::Rejected(WorkflowDiagnostic {
            kind,
            subject: format!("{from_column} -> {target_column}"),
            message,
        })
    };

    // 1. Unknown column.
    //
    // WP03: the valid-column list moved in from `mv.rs`, which used to carry its
    // own copy of this check so it could print the list. Two copies of the rule
    // is what C-003 forbids, and the copy in `mv.rs` is gone — but its message was
    // the more useful of the two, because a user who mistypes a column needs to be
    // told what to type instead. So the list is *widened into* the service rather
    // than dropped with it: one rule, and the better message.
    let Some(to_category) = resolution.resolve(target_column) else {
        return reject(
            DiagnosticKind::UnknownColumn,
            format!(
                "`{target_column}` is not a column on board `{}`; valid columns: {}",
                resolution.board,
                resolution.column_list()
            ),
        );
    };
    let Some(from_category) = resolution.resolve(&from_column) else {
        return reject(
            DiagnosticKind::UnknownColumn,
            format!(
                "issue is in `{from_column}`, which is not a column on board `{}`; \
                 valid columns: {}",
                resolution.board,
                resolution.column_list()
            ),
        );
    };

    // 2. Same column: permitted, idempotent, and no decision to append.
    if from_column == target_column {
        return TransitionOutcome::Accepted {
            from: from_column,
            to: target_column.to_string(),
            from_category,
            to_category,
            changed: false,
            override_reason: None,
        };
    }

    // 3. Terminal lock, with the reasoned escape hatch.
    //
    // Gated on `explicit_policy`, together with adjacency in `is_compatible` —
    // see that function's note for why the two cannot be gated separately.
    let reason = override_reason.map(str::trim).filter(|r| !r.is_empty());
    if config.transitions.terminal_locked
        && resolution.explicit_policy
        && from_category.is_terminal()
        && !to_category.is_complete()
        && !to_category.is_terminal()
    {
        return match reason {
            Some(reason) => TransitionOutcome::Accepted {
                from: from_column,
                to: target_column.to_string(),
                from_category,
                to_category,
                changed: true,
                override_reason: Some(reason.to_string()),
            },
            None => reject(
                DiagnosticKind::InvalidTransition,
                // WP04: the message names the **spelling** of the override.
                //
                // It previously ended at "needs an explicit override with a reason",
                // which tells a user the rule and leaves them to guess the flag. The
                // rendered string also carried a Rust line-continuation `\` into the
                // output, because the `\\` in the source literal survives into the
                // format string — so the message a user saw contained a stray
                // backslash in the middle of a sentence. Both are fixed by writing
                // the sentence as one line with an explicit em dash.
                format!(
                    "issue is in terminal category `{}`; moving to `{target_column}` \
                     (`{}`) needs an explicit override with a reason \u{2014} \
                     `tix mv <issue> {target_column} --reason \"why\"`",
                    from_category.key(),
                    to_category.key()
                ),
            ),
        };
    }

    // 4. Adjacency.
    if !is_compatible(&from_column, target_column, resolution, config) {
        return reject(
            DiagnosticKind::InvalidTransition,
            format!(
                "`{}` -> `{}` is not permitted by the category policy",
                from_category.key(),
                to_category.key()
            ),
        );
    }

    TransitionOutcome::Accepted {
        from: from_column,
        to: target_column.to_string(),
        from_category,
        to_category,
        changed: true,
        override_reason: reason.map(str::to_string),
    }
}

/// The documented safe default, re-exported so a surface reporting a defaulted
/// column quotes the same constant the resolution used.
pub const SAFE_DEFAULT: &str = SAFE_DEFAULT_CATEGORY;

#[cfg(test)]
mod tests {
    #[allow(clippy::wildcard_imports)]
    use super::*;
    use crate::config::BoardConfiguration;
    use indexmap::IndexMap;

    fn board(columns: &[&str], done: &str, map: &[(&str, &str)]) -> BoardConfiguration {
        let mut category_map = IndexMap::new();
        for (column, category) in map {
            category_map.insert((*column).to_string(), (*category).to_string());
        }
        BoardConfiguration {
            columns: columns.iter().map(|c| (*c).to_string()).collect(),
            done_column: Some(done.to_string()),
            category_map,
            hidden_columns: vec![],
            show_mismatch: false,
            wrap_titles: true,
            title_lines: 3,
            card_order: vec![],
            order_by: crate::config::OrderBy::CreatedAtDesc,
            wip: crate::wip::WipConfig::default(),
        }
    }

    fn config_with(board: BoardConfiguration) -> Config {
        let mut config = Config::default();
        config
            .kanban
            .configurations
            .insert("default".to_string(), board);
        config
    }

    /// A board with its own column names, fully mapped.
    fn custom_config() -> Config {
        config_with(board(
            &["triage", "wip", "review", "shipped"],
            "shipped",
            &[
                ("triage", "backlog"),
                ("wip", "active"),
                ("review", "active"),
                ("shipped", "completed"),
            ],
        ))
    }

    /// An issue in `column`. `Issue` has no `Default`, so it is written out: a
    /// derived default would hide a field added to the model behind a silently
    /// zero value, which is the same failure as a test that measures nothing.
    fn issue_in(column: &str) -> Issue {
        Issue {
            projects: None,
            id: None,
            number: 1,
            title: "T".into(),
            status: crate::model::Status::new(column),
            labels: vec![],
            priority: crate::model::Priority::Medium,
            assignee: None,
            estimate: None,
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            relationships: vec![],
            related_issues: vec![],
            files: vec![],
            cycles: None,
            milestones: None,
            reviewer: None,
            start_date: None,
            due_date: None,
            created: "2026-01-01".into(),
            type_: None,
            updated: "2026-01-01".into(),
            filename: "t.md".into(),
            body: String::new(),
            history: crate::model::History::new(),
            has_retired_links_key: false,
            time_entries: vec![],
            parent: None,
            series: None,
            health: None,
            epics: None,
            extra_frontmatter: std::collections::BTreeMap::new(),
            archived: false,
            entered_at: None,
            source: None,
        }
    }

    // -- T006: the vocabulary ------------------------------------------------

    #[test]
    fn every_key_round_trips() {
        for (i, category) in WorkflowCategory::ALL.iter().enumerate() {
            assert_eq!(
                WorkflowCategory::from_key(category.key()),
                Some(*category),
                "{:?} must parse back to itself",
                category
            );
            // And the order agrees with the vocabulary constant WP01 exported, so
            // the two cannot drift.
            assert_eq!(category.key(), CATEGORY_KEYS[i]);
        }
        assert_eq!(WorkflowCategory::ALL.len(), CATEGORY_KEYS.len());
    }

    #[test]
    fn an_unknown_key_yields_none_and_never_a_default() {
        // The `Option` is the point: a typo must be an error, not a silent
        // fallback to `unstarted`.
        for key in ["wontfix", "Done", "COMPLETED", "", " done", "unstarted "] {
            assert_eq!(
                WorkflowCategory::from_key(key),
                None,
                "`{key}` must not resolve to a category"
            );
        }
    }

    #[test]
    fn only_completed_and_canceled_are_terminal() {
        let terminal: Vec<&str> = WorkflowCategory::ALL
            .iter()
            .filter(|c| c.is_terminal())
            .map(|c| c.key())
            .collect();
        assert_eq!(terminal, vec!["completed", "canceled"]);
        // Terminal is not the same claim as complete.
        assert!(WorkflowCategory::Canceled.is_terminal());
        assert!(!WorkflowCategory::Canceled.is_complete());
        assert!(WorkflowCategory::Completed.is_complete());
        assert_eq!(COMPLETE_CATEGORY, "completed");
    }

    #[test]
    fn labels_are_distinct() {
        let mut labels: Vec<&str> = WorkflowCategory::ALL.iter().map(|c| c.label()).collect();
        labels.sort_unstable();
        let before = labels.len();
        labels.dedup();
        assert_eq!(labels.len(), before, "two categories share a display label");
    }

    /// A colour is presentation. Asserted as inert rather than merely present: the
    /// point of the contract clause is that no decision reads it.
    #[test]
    fn color_hint_is_inert_with_respect_to_completion() {
        for category in WorkflowCategory::ALL {
            let hint = category.color_hint();
            if category.is_complete() {
                assert_eq!(hint, Some(ColorHint::Ok));
            }
            // Whatever the hint, the completion answer is the category's alone.
            assert_eq!(
                category.is_complete(),
                category.key() == COMPLETE_CATEGORY,
                "{category:?}: the hint must not decide completion"
            );
        }
    }

    // -- T007: resolution ----------------------------------------------------

    #[test]
    fn an_explicit_mapping_resolves_and_nothing_is_unmapped() {
        let config = custom_config();
        let res = resolution(&config, config.default_config(), "default");
        assert_eq!(res.resolve("triage"), Some(WorkflowCategory::Backlog));
        assert_eq!(res.resolve("wip"), Some(WorkflowCategory::Active));
        assert_eq!(res.resolve("shipped"), Some(WorkflowCategory::Completed));
        assert_eq!(res.unmapped, [] as [std::string::String; 0]);
        assert!(!res.default_applied);
        assert!(res.has_completion());
    }

    #[test]
    fn an_unmapped_column_resolves_to_the_safe_default_and_is_recorded() {
        let config = config_with(board(
            &["triage", "wip", "review", "shipped"],
            "shipped",
            &[
                ("triage", "backlog"),
                ("review", "active"),
                ("shipped", "completed"),
            ],
        ));
        let res = resolution(&config, config.default_config(), "default");
        assert_eq!(res.resolve("wip"), Some(WorkflowCategory::Unstarted));
        assert_eq!(
            res.unmapped,
            vec!["wip".to_string()],
            "recorded, in board order"
        );
        assert!(res.default_applied);
    }

    #[test]
    fn a_custom_named_completion_column_resolves_to_completed() {
        let config = custom_config();
        let res = resolution(&config, config.default_config(), "default");
        // The column is called `shipped`, not `done`. Completion is the category,
        // not the name — which is the whole point of the mapping.
        assert_ne!(
            config.default_config().effective_done_column(),
            Some("done")
        );
        assert_eq!(res.resolve("shipped"), Some(WorkflowCategory::Completed));
        assert!(res.has_completion());
    }

    #[test]
    fn an_unconfigured_column_yields_none() {
        let config = custom_config();
        let res = resolution(&config, config.default_config(), "default");
        assert_eq!(res.resolve("nope"), None);
    }

    /// A legacy board with no `category_map`: `done_column` completes, everything
    /// else is the safe default. WP01 owns the fallback; this asserts the service
    /// reads it rather than duplicating it.
    #[test]
    fn a_legacy_board_with_no_map_completes_on_its_done_column() {
        let config = config_with(board(
            &["todo", "in progress", "in review", "done"],
            "done",
            &[],
        ));
        let res = resolution(&config, config.default_config(), "default");
        assert_eq!(res.resolve("done"), Some(WorkflowCategory::Completed));
        assert_eq!(res.resolve("todo"), Some(WorkflowCategory::Unstarted));
        assert!(res.has_completion());
    }

    #[test]
    fn two_resolutions_of_the_same_config_are_equal() {
        let config = custom_config();
        let a = resolution(&config, config.default_config(), "default");
        let b = resolution(&config, config.default_config(), "default");
        assert_eq!(
            a, b,
            "resolution must be a function of the config, not of when it ran"
        );
    }

    // -- T008: the single completion decision ---------------------------------

    #[test]
    fn completion_is_the_category_alone() {
        let config = config_with(board(
            &["triage", "wip", "dropped", "shipped"],
            "shipped",
            &[
                ("triage", "backlog"),
                ("wip", "active"),
                ("dropped", "canceled"),
                ("shipped", "completed"),
            ],
        ));
        let res = resolution(&config, config.default_config(), "default");
        assert!(is_completed(&issue_in("shipped"), &res));
        // `canceled` is terminal and **not** complete — the distinction triage's
        // decline action depends on.
        assert!(!is_completed(&issue_in("dropped"), &res));
        assert!(!is_completed(&issue_in("wip"), &res));
        // An unconfigured column is not complete, and does not error.
        assert!(!is_completed(&issue_in("nope"), &res));
        assert_eq!(
            category_of(&issue_in("dropped"), &res),
            Some(WorkflowCategory::Canceled)
        );
        assert_eq!(category_of(&issue_in("nope"), &res), None);
    }

    // -- T009: transition policy ---------------------------------------------

    #[test]
    fn a_compatible_transition_is_accepted() {
        let config = custom_config();
        let res = resolution(&config, config.default_config(), "default");
        let outcome = validate_transition(&issue_in("triage"), "wip", &res, &config, None);
        match outcome {
            TransitionOutcome::Accepted {
                from,
                to,
                changed,
                override_reason,
                from_category,
                to_category,
            } => {
                assert_eq!((from.as_str(), to.as_str()), ("triage", "wip"));
                assert_eq!(from_category, WorkflowCategory::Backlog);
                assert_eq!(to_category, WorkflowCategory::Active);
                assert!(changed);
                assert_eq!(override_reason, None);
            }
            other @ TransitionOutcome::Rejected(_) => {
                panic!("expected acceptance, got {other:?}")
            }
        }
    }

    /// Contract §3.2 and the intake's third invariant: a same-column transition is
    /// permitted, idempotent, and produces no decision to append.
    #[test]
    fn a_same_column_transition_is_idempotent_with_no_decision() {
        let config = custom_config();
        let res = resolution(&config, config.default_config(), "default");
        for column in ["triage", "wip", "review", "shipped"] {
            match validate_transition(&issue_in(column), column, &res, &config, None) {
                TransitionOutcome::Accepted { changed, .. } => {
                    assert!(!changed, "`{column}` -> `{column}` must be a no-op")
                }
                TransitionOutcome::Rejected(other) => {
                    panic!("expected acceptance for `{column}`, got {other:?}")
                }
            }
        }
    }

    #[test]
    fn an_unknown_target_column_is_rejected() {
        let config = custom_config();
        let res = resolution(&config, config.default_config(), "default");
        match validate_transition(&issue_in("wip"), "nowhere", &res, &config, None) {
            TransitionOutcome::Rejected(d) => {
                assert_eq!(d.kind, DiagnosticKind::UnknownColumn)
            }
            TransitionOutcome::Accepted { .. } => {
                panic!("expected a rejection, got an accepted transition")
            }
        }
    }

    /// The terminal lock, and the reasoned escape hatch. The override must carry a
    /// reason: a bare "I did it anyway" is indistinguishable from a mistake.
    #[test]
    fn a_terminal_exit_is_refused_without_a_reason_and_allowed_with_one() {
        let config = config_with(board(
            &["triage", "wip", "dropped", "shipped"],
            "shipped",
            &[
                ("triage", "backlog"),
                ("wip", "active"),
                ("dropped", "canceled"),
                ("shipped", "completed"),
            ],
        ));
        let res = resolution(&config, config.default_config(), "default");

        // Out of a terminal category into a non-terminal one: refused.
        for from in ["dropped", "shipped"] {
            match validate_transition(&issue_in(from), "wip", &res, &config, None) {
                TransitionOutcome::Rejected(d) => {
                    assert_eq!(d.kind, DiagnosticKind::InvalidTransition, "from `{from}`")
                }
                TransitionOutcome::Accepted { .. } => {
                    panic!("expected a rejection from `{from}`")
                }
            }
            // A blank reason is not a reason.
            match validate_transition(&issue_in(from), "wip", &res, &config, Some("   ")) {
                TransitionOutcome::Rejected(_) => {}
                TransitionOutcome::Accepted { .. } => {
                    panic!("a blank override must not unlock `{from}`")
                }
            }
            // A real one is accepted and recorded.
            match validate_transition(&issue_in(from), "wip", &res, &config, Some("wrong call")) {
                TransitionOutcome::Accepted {
                    override_reason,
                    changed,
                    ..
                } => {
                    assert_eq!(override_reason.as_deref(), Some("wrong call"));
                    assert!(changed);
                }
                TransitionOutcome::Rejected(d) => {
                    panic!("a reasoned override must be accepted, got: {}", d.message)
                }
            }
        }
    }

    /// Terminal to terminal is not an **exit**, so the lock does not apply.
    ///
    /// The first version of this test moved `canceled -> completed` and failed. The
    /// lock was not what refused it: `canceled` is *after* `completed` in the
    /// declared order, so **adjacency** refused it. The two rules are independent
    /// and the test conflated them. `completed -> canceled` is terminal to
    /// terminal *and* forward, so the lock is the only rule that could have applied
    /// and it does not.
    #[test]
    fn a_terminal_to_terminal_move_is_not_locked() {
        let config = config_with(board(
            &["triage", "dropped", "shipped"],
            "shipped",
            &[
                ("triage", "backlog"),
                ("dropped", "canceled"),
                ("shipped", "completed"),
            ],
        ));
        let res = resolution(&config, config.default_config(), "default");
        assert!(matches!(
            validate_transition(&issue_in("shipped"), "dropped", &res, &config, None),
            TransitionOutcome::Accepted { .. }
        ));
        // And the backwards direction is still refused — by adjacency, which is a
        // different rule and a different answer for a different reason.
        match validate_transition(&issue_in("dropped"), "shipped", &res, &config, None) {
            TransitionOutcome::Rejected(d) => {
                assert_eq!(d.kind, DiagnosticKind::InvalidTransition);
                assert!(
                    d.message.contains("category policy"),
                    "refused by adjacency, not the lock: {}",
                    d.message
                );
            }
            TransitionOutcome::Accepted { .. } => {
                panic!("expected a rejection, got an accepted transition")
            }
        }
    }

    /// The lock is a **separate** rule, and this is the only configuration where
    /// it is the *sole* thing preventing a move.
    ///
    /// With the declared order (`... completed, canceled` last), every exit from a
    /// terminal category is also *backwards*, so adjacency refuses it regardless and
    /// the lock is redundant. Putting `canceled` first in the order makes the exit
    /// forward, which isolates the lock: with it on the move is refused, with it off
    /// the move is permitted. Without this ordering the switch-off would prove
    /// nothing — the move would be refused either way, and the test would pass
    /// while measuring adjacency.
    #[test]
    fn the_terminal_lock_can_be_switched_off() {
        let mut config = config_with(board(
            &["triage", "dropped", "shipped"],
            "shipped",
            &[
                ("triage", "backlog"),
                ("dropped", "canceled"),
                ("shipped", "completed"),
            ],
        ));
        config.categories.order = vec![
            "canceled".into(),
            "backlog".into(),
            "active".into(),
            "completed".into(),
        ];
        let res = resolution(&config, config.default_config(), "default");

        // Precondition, stated on the *order* rather than on `is_compatible`:
        // `is_compatible` applies the lock too, so asking it "is adjacency
        // permitting this?" cannot be done through it. With `canceled` before
        // `backlog`, adjacency permits the move and the lock is the only thing
        // standing in its way.
        let pos = |key: &str| {
            config
                .categories
                .order
                .iter()
                .position(|k| k == key)
                .expect("both keys are in the order")
        };
        assert!(
            pos("canceled") < pos("backlog"),
            "precondition: the move is forward"
        );
        assert!(matches!(
            validate_transition(&issue_in("dropped"), "triage", &res, &config, None),
            TransitionOutcome::Rejected { .. }
        ));

        config.transitions.terminal_locked = false;
        let res = resolution(&config, config.default_config(), "default");
        assert!(matches!(
            validate_transition(&issue_in("dropped"), "triage", &res, &config, None),
            TransitionOutcome::Accepted { changed: true, .. }
        ));
    }

    /// Adjacency is expressed on the *category* order, so a board with custom
    /// column names needs no per-pair configuration for it to behave.
    #[test]
    fn a_backwards_category_move_is_rejected() {
        let config = custom_config();
        let res = resolution(&config, config.default_config(), "default");
        // `active` is later than `backlog` in the vocabulary, so going back is not
        // permitted; a same-category move between two active columns is.
        assert!(!is_compatible("review", "triage", &res, &config));
        assert!(is_compatible("triage", "review", &res, &config));
        assert!(is_compatible("wip", "review", &res, &config));
        match validate_transition(&issue_in("review"), "triage", &res, &config, None) {
            TransitionOutcome::Rejected(d) => assert_eq!(d.kind, DiagnosticKind::InvalidTransition),
            TransitionOutcome::Accepted { .. } => {
                panic!("expected a rejection, got an accepted transition")
            }
        }
    }

    /// Rejection is inert: the service returns a diagnostic and writes nothing.
    /// Asserted as a property of the return type's shape — there is no file, no
    /// store and no `Result` in the signature to write through.
    #[test]
    fn a_rejection_carries_a_diagnostic_and_nothing_else() {
        let config = custom_config();
        let res = resolution(&config, config.default_config(), "default");
        let outcome = validate_transition(&issue_in("review"), "triage", &res, &config, None);
        let TransitionOutcome::Rejected(d) = outcome else {
            panic!("expected a rejection")
        };
        assert_ne!(d.message, "");
        assert_ne!(d.subject, "");
    }

    // -- T010: configuration diagnostics -------------------------------------

    #[test]
    fn a_clean_config_reports_nothing() {
        let config = custom_config();
        assert_eq!(validate_config(&config), vec![]);
    }

    #[test]
    fn a_board_with_no_completion_column_is_reported() {
        // Built directly, since config load refuses it — the service reports the
        // same condition under the same name rather than being the second rule.
        let config = config_with(board(
            &["triage", "wip", "shipped"],
            "shipped",
            &[("triage", "backlog"), ("wip", "active")],
        ));
        let found: Vec<DiagnosticKind> = validate_config(&config)
            .into_iter()
            .map(|d| d.kind)
            .collect();
        assert!(
            found.contains(&DiagnosticKind::MissingCompletionCategory),
            "got {found:?}"
        );
    }

    #[test]
    fn an_unmapped_column_is_reported_but_is_not_an_error() {
        let config = config_with(board(
            &["triage", "wip", "shipped"],
            "shipped",
            &[("shipped", "completed")],
        ));
        let found: Vec<DiagnosticKind> = validate_config(&config)
            .into_iter()
            .map(|d| d.kind)
            .collect();
        assert!(
            found.contains(&DiagnosticKind::UnmappedColumnDefault),
            "got {found:?}"
        );
        // Reported, never fatal: `validate_config` returns a value and does not
        // error, and a defaulted column resolves (WP01 proved that at load).
        assert!(!found.contains(&DiagnosticKind::UnknownColumn));
    }

    #[test]
    fn an_unknown_column_and_category_are_reported() {
        let config = config_with(board(
            &["triage", "shipped"],
            "shipped",
            &[
                ("triage", "backlog"),
                ("shipped", "completed"),
                ("nowhere", "active"),
            ],
        ));
        let found: Vec<DiagnosticKind> = validate_config(&config)
            .into_iter()
            .map(|d| d.kind)
            .collect();
        assert!(
            found.contains(&DiagnosticKind::MappingForUnknownColumn),
            "{found:?}"
        );
    }

    #[test]
    fn two_runs_return_equal_results() {
        let config = config_with(board(
            &["triage", "wip", "shipped"],
            "shipped",
            &[("shipped", "completed"), ("nowhere", "wontfix")],
        ));
        assert_eq!(validate_config(&config), validate_config(&config));
        // And deterministically ordered, not merely equal run to run.
        let subjects: Vec<String> = validate_config(&config)
            .into_iter()
            .map(|d| d.subject)
            .collect();
        let mut sorted = subjects.clone();
        sorted.sort();
        assert_eq!(subjects, sorted, "diagnostics must be sorted by subject");
    }

    #[test]
    fn the_diagnostic_kind_set_is_the_contract_set() {
        let names: Vec<&str> = DiagnosticKind::ALL.iter().map(|k| k.as_str()).collect();
        assert_eq!(
            names,
            vec![
                "missing_completion_category",
                "unknown_category",
                "mapping_for_unknown_column",
                "unmapped_column_default",
                "invalid_transition",
                "unknown_column",
                "direct_edit_policy_violation",
            ],
            "contract §6 fixes these names; every surface shares them"
        );
        // And they round-trip through nothing: `as_str` is the only spelling.
        for kind in DiagnosticKind::ALL {
            assert_ne!(kind.as_str(), "");
        }
    }

    /// NFR-001's gate: the per-issue path is a hash lookup, not a scan. Measured
    /// against a deliberately wasteful re-resolution, which is the failure mode.
    #[test]
    fn the_per_issue_path_is_a_lookup_not_a_rebuild() {
        let config = custom_config();
        let board = config.default_config();
        let res = resolution(&config, board, "default");
        let build = std::time::Instant::now();
        for _ in 0..2_000 {
            let _ = resolution(&config, board, "default");
        }
        let rebuild_cost = build.elapsed();
        let lookup = std::time::Instant::now();
        for _ in 0..2_000 {
            let _ = res.resolve("wip");
        }
        let lookup_cost = lookup.elapsed();
        assert!(
            lookup_cost < rebuild_cost,
            "2,000 lookups ({lookup_cost:?}) must cost less than 2,000 rebuilds \
             ({rebuild_cost:?}) — resolution is built once and read many times"
        );
    }
}