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
//! The `[kanban.<name>.wip]` schema: per-column limits, estimate units, and the
//! arithmetic between them (mission `configurable-wip-limits-01M3C6WX`, WP01).
//!
//! # The shape, and why it looks like this
//!
//! ```toml
//! [kanban.default.wip.units]
//! d = 1      # a `d` is one base point
//! w = 5      # a `w` is five
//!
//! [kanban.default.wip.limits."in progress"]
//! max_items = 3
//! max_estimate = 10
//! unit = "d"       # what `max_estimate` counts in
//! policy = "block" # `warn` or `block` — required, never assumed
//! enabled = true   # default; `false` keeps the numbers but enforces nothing
//! ```
//!
//! Three decisions are worth stating, because each one is a door that stays shut:
//!
//! 1. **The column is the key.** A limit cannot name a column that does not exist
//!    and cannot be declared twice; validation then checks the key against the
//!    board's own [`columns`](crate::config::BoardConfiguration::columns).
//! 2. **`policy` is required, not defaulted.** "Warning or blocking behaviour by
//!    configuration" (C-004) is only true if the choice is written down; a limit
//!    that silently warned would be a policy nobody configured. The field is
//!    `Option<LimitPolicy>` so "absent" is distinguishable from "warn" and can be
//!    refused by name.
//! 3. **Units are declarative and the arithmetic is exact.** A board declares named
//!    units and their factor to its base unit; an issue's free-form `estimate`
//!    (`3d`, or a bare `3` which is already in the limit's unit) is converted by
//!    `value × factor(from) ÷ factor(to)`. A unit the board never declared is a
//!    `missing_conversion`, and a conversion that does not divide exactly is an
//!    `ambiguous_conversion` — never a rounded or defaulted count (C-003).
//!
//!    The text may also be a **human duration**: `1 day`, `2 days`,
//!    `3 weeks 2 hours`, `2w`, `1d 30 min` (tix #1724). Each term is converted
//!    through the board's own units and the converted terms are summed, so a
//!    prose estimate never invents a clock ratio the board did not declare:
//!    `3 weeks 2 hours` on a board with `w = 5` and `h = 1` is `17`, not
//!    `506` (C-003 still holds).
//!
//! # What this module does not own
//!
//! The status categories and the completion semantics stay
//! [`crate::workflow`]'s (C-002): nothing here reads a category, decides what
//! "done" means, or interprets `done_column`. Counting issues, deciding a move, and
//! writing an override are the later work packages; this one owns what a limit *is*.

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

use crate::error::TixError;

/// Whether a limit warns or blocks (C-004).
///
/// There is no third behaviour and no "silent": a limit that is not enforced is
/// [`enabled = false`](ColumnLimit::enabled), which is a different statement from
/// "warn" and reads as one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LimitPolicy {
    /// The move proceeds and the violation is reported.
    Warn,
    /// The move is refused unless an authorized override carries it.
    Block,
}

impl LimitPolicy {
    /// The stable spelling every surface prints and `tix.toml` stores.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Warn => "warn",
            Self::Block => "block",
        }
    }
}

/// The `enabled` default: declaring a limit means applying it.
const fn enabled_default() -> bool {
    true
}

/// `serde`'s `skip_serializing_if` takes a `&T` predicate, so the reference is the
/// signature the attribute needs rather than a choice.
#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_enabled_default(enabled: &bool) -> bool {
    *enabled
}

/// One column's limit.
///
/// Both ceilings are optional and independent: a column may cap the *number* of
/// cards, the *estimate* they add up to, or both. An enabled limit with neither is
/// refused, because a limit that limits nothing is a configuration mistake that
/// would otherwise read as an enforced rule.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ColumnLimit {
    /// The most cards the column may hold.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_items: Option<u32>,
    /// The most estimate the column's cards may add up to, counted in [`unit`].
    ///
    /// [`unit`]: ColumnLimit::unit
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_estimate: Option<u32>,
    /// The unit `max_estimate` counts in. Required with `max_estimate`, refused
    /// without it: a unit on an item-count limit would describe nothing.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unit: Option<String>,
    /// `warn` or `block`. Required for an enabled limit (see the module docs).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub policy: Option<LimitPolicy>,
    /// Whether the limit is enforced. `false` keeps the numbers for later without
    /// changing any behaviour today.
    #[serde(
        default = "enabled_default",
        skip_serializing_if = "is_enabled_default"
    )]
    pub enabled: bool,
}

impl Default for ColumnLimit {
    fn default() -> Self {
        Self {
            max_items: None,
            max_estimate: None,
            unit: None,
            policy: None,
            enabled: true,
        }
    }
}

impl ColumnLimit {
    /// A limit capping the column at `max_items` cards, with `policy`.
    pub fn items(max_items: u32, policy: LimitPolicy) -> Self {
        Self {
            max_items: Some(max_items),
            policy: Some(policy),
            ..Self::default()
        }
    }

    /// A limit capping the column at `max_estimate` `unit`s, with `policy`.
    pub fn estimate(max_estimate: u32, unit: impl Into<String>, policy: LimitPolicy) -> Self {
        Self {
            max_estimate: Some(max_estimate),
            unit: Some(unit.into()),
            policy: Some(policy),
            ..Self::default()
        }
    }

    /// Whether nothing at all is declared: the state the schema omits on save.
    pub fn is_empty(&self) -> bool {
        self.max_items.is_none()
            && self.max_estimate.is_none()
            && self.unit.is_none()
            && self.policy.is_none()
            && self.enabled == enabled_default()
    }

    /// The policy this limit enforces, when it is enforced at all.
    ///
    /// `None` for a disabled limit *and* for an enabled one that forgot to state a
    /// policy — validation refuses the latter, so a caller that has validated a
    /// config and asked an **enabled** limit for its policy always gets one.
    pub fn resolved_policy(&self) -> Option<LimitPolicy> {
        self.enabled.then_some(self.policy).flatten()
    }
}

/// A board's work-in-progress configuration (`[kanban.<name>.wip]`).
///
/// Omitted **whole** when nothing is declared (`limits` and `units` both empty), so
/// a board that configures no limits gains no key on save — the same rule every
/// other board field follows (#1415).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct WipConfig {
    /// Named estimate units, `name -> factor` to the board's base unit, in
    /// declaration order.
    #[serde(skip_serializing_if = "IndexMap::is_empty")]
    pub units: IndexMap<String, u32>,
    /// `<column> -> limit`, in declaration order.
    #[serde(skip_serializing_if = "IndexMap::is_empty")]
    pub limits: IndexMap<String, ColumnLimit>,
}

impl WipConfig {
    /// The limits, in declaration order.
    pub fn limits(&self) -> impl Iterator<Item = (&str, &ColumnLimit)> {
        self.limits
            .iter()
            .map(|(column, limit)| (column.as_str(), limit))
    }

    /// Whether no limit and no unit is declared: the state that writes nothing.
    pub fn is_empty(&self) -> bool {
        self.units.is_empty() && self.limits.is_empty()
    }

    /// Whether any limit is actually enforced.
    pub fn has_enabled_limits(&self) -> bool {
        self.limits.values().any(|limit| limit.enabled)
    }

    /// The limit **in force** for `column`, if any (T004).
    ///
    /// This is the resolver every surface asks — not the raw map — so "declared but
    /// disabled" cannot be mistaken for "enforced" by one caller and not another.
    /// It decides nothing else: what a violation *means* is the policy layer's, and
    /// what a column *is* stays [`crate::workflow`]'s (C-002).
    pub fn effective_limit(&self, column: &str) -> Option<&ColumnLimit> {
        self.limits
            .get(column)
            .filter(|limit| limit.enabled && !limit.is_empty())
    }

    /// The conversion factor of `unit`, if the board declares it.
    pub fn factor(&self, unit: &str) -> Option<u32> {
        self.units.get(unit).copied()
    }

    /// Convert `estimate` into `target`, using the declared factors (T002).
    ///
    /// A bare estimate is **already** in `target` — the limit names the unit, so
    /// there is nothing to infer. A named one must be declared by the board, and the
    /// arithmetic must divide exactly: a fractional result is refused rather than
    /// rounded, because a count that depends on rounding is a count nobody can
    /// predict.
    pub fn convert(&self, estimate: &Estimate, target: &str) -> std::result::Result<u32, WipError> {
        let target_factor = self.factor(target).ok_or_else(|| {
            WipError::single(WipDiagnostic::new(
                WipDiagnosticKind::UnknownUnit,
                format!("`{target}` is not a declared estimate unit"),
            ))
            .because("declare the unit under `[kanban.<board>.wip.units]`")
        })?;
        let Some(unit) = estimate.unit.as_deref() else {
            // The same unit: nothing to convert, and nothing assumed.
            return Ok(estimate.value);
        };
        if unit == target {
            return Ok(estimate.value);
        }
        let from_factor = self.factor(unit).ok_or_else(|| {
            WipError::single(WipDiagnostic::new(
                WipDiagnosticKind::MissingConversion,
                format!(
                    "`{}` uses estimate unit `{unit}`, which this board does not declare",
                    estimate.render()
                ),
            ))
            .because("a missing conversion is an error, never a zero or a guess (C-003)")
        })?;
        let scaled = (estimate.value as u64) * (from_factor as u64);
        let target_factor = target_factor as u64;
        if scaled % target_factor != 0 {
            return Err(WipError::single(WipDiagnostic::new(
                WipDiagnosticKind::AmbiguousConversion,
                format!(
                    "`{}` is {scaled} base points, which is not a whole number of `{target}` \
                     (a `{target}` is {target_factor})",
                    estimate.render()
                ),
            ))
            .because(
                "declare a unit the arithmetic divides evenly into, or rewrite the estimate",
            ));
        }
        Ok((scaled / target_factor) as u32)
    }

    /// Convert every term of a parsed estimate and sum them (tix #1724).
    ///
    /// This is the only way a compound duration becomes one number. Each term keeps
    /// its own declared unit, so `3 weeks 2 hours` is `3 × w + 2 × h` in the target
    /// — never a clock-ratio guess. One unconvertible term refuses the whole sum and
    /// names itself, because a partial total would silently undercount.
    pub fn convert_terms(
        &self,
        estimates: &[Estimate],
        target: &str,
    ) -> std::result::Result<u32, WipError> {
        if estimates.is_empty() {
            return Err(Estimate::malformed(
                "an estimate must state at least one term".to_string(),
            ));
        }
        let mut total: u64 = 0;
        for estimate in estimates {
            total += u64::from(self.convert(estimate, target)?);
            if total > u64::from(u32::MAX) {
                return Err(Estimate::malformed(format!(
                    "the estimate terms sum past what this board can count in `{target}`"
                )));
            }
        }
        Ok(total as u32)
    }

    /// Validate the schema against the board it belongs to (T001, T003).
    ///
    /// Every finding is a `tix.toml` error naming the exact key, in the same shape
    /// the neighbouring board checks use. A **disabled** limit is still validated:
    /// it is configuration either way, and a limit aimed at a column that does not
    /// exist is a mistake whether or not it is switched on.
    pub fn validate(&self, board: &str, columns: &[String]) -> std::result::Result<(), TixError> {
        for (name, factor) in &self.units {
            if name.trim().is_empty() {
                return Err(TixError::Config(format!(
                    "`kanban.{board}.wip.units` must not contain a blank unit name"
                )));
            }
            if *factor == 0 {
                return Err(TixError::Config(format!(
                    "`kanban.{board}.wip.units.{name}` must be at least 1"
                )));
            }
        }
        for (column, limit) in &self.limits {
            let key = format!("kanban.{board}.wip.limits.`{column}`");
            if !columns.contains(column) {
                return Err(TixError::Config(format!(
                    "`{key}` names a column that is not in `kanban.{board}.columns`"
                )));
            }
            if limit.max_items == Some(0) {
                return Err(TixError::Config(format!(
                    "`{key}.max_items` must be at least 1"
                )));
            }
            if limit.max_estimate == Some(0) {
                return Err(TixError::Config(format!(
                    "`{key}.max_estimate` must be at least 1"
                )));
            }
            if let Some(unit) = &limit.unit
                && !self.units.contains_key(unit)
            {
                return Err(TixError::Config(format!(
                    "`{key}.unit` (`{unit}`) is not declared in \
                     `kanban.{board}.wip.units`"
                )));
            }
            if limit.max_estimate.is_some() && limit.unit.is_none() {
                return Err(TixError::Config(format!(
                    "`{key}.unit` is required with `max_estimate`: it says what the \
                     ceiling counts"
                )));
            }
            if limit.max_estimate.is_none() && limit.unit.is_some() {
                return Err(TixError::Config(format!(
                    "`{key}.unit` is only meaningful with `max_estimate`"
                )));
            }
            if limit.enabled {
                if limit.max_items.is_none() && limit.max_estimate.is_none() {
                    return Err(TixError::Config(format!(
                        "`{key}` is enabled but declares neither `max_items` nor \
                         `max_estimate`"
                    )));
                }
                if limit.policy.is_none() {
                    return Err(TixError::Config(format!(
                        "`{key}.policy` is required: say whether the limit `warn`s or \
                         `block`s (C-004)"
                    )));
                }
            }
        }
        Ok(())
    }
}

/// An estimate as an issue writes it: a number, and optionally the unit it is in.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Estimate {
    /// The number the issue states.
    pub value: u32,
    /// The unit it is stated in, or `None` when it is already in the limit's unit.
    pub unit: Option<String>,
}

impl Estimate {
    /// Parse one `<number>[<unit>]` term of the free-form `estimate:` frontmatter.
    ///
    /// A unit starts with an ASCII letter and continues with letters, digits, `_` or
    /// `-`; whitespace between the number and the unit is accepted (`1 day`). Human
    /// duration words are folded to the board's conventional symbols (`day`/`days`
    /// → `d`, `week`/`weeks` → `w`, `hour`/`hours` → `h`, `minute`/`minutes` → `m`,
    /// `second`/`seconds` → `s`); a single-letter unit is left exactly as written, so
    /// a board's own `S` or `p` keeps its meaning. Anything else is refused with the
    /// value quoted back, because an estimate nobody can count is worse than none.
    ///
    /// Use [`Estimate::parse_terms`] for a compound duration (`3 weeks 2 hours`).
    pub fn parse(raw: &str) -> std::result::Result<Self, WipError> {
        let text = raw.trim();
        let mut terms = Self::parse_terms(text)?;
        if terms.len() != 1 {
            return Err(Self::malformed(format!(
                "`{text}` states more than one estimate term"
            )));
        }
        Ok(terms.remove(0))
    }

    /// Parse a free-form estimate into its terms, in the order written (tix #1724).
    ///
    /// Accepted: `<number>` (bare, already in the target unit), `<number><unit>`,
    /// decimal numbers and ranges (`0.5 day`, `0.5-1 day`), and one or more
    /// whitespace/comma-separated terms such as `3 weeks 2 hours`. Each term is read
    /// on its own; nothing is summed here, because the sum is only meaningful after
    /// every term has been converted through the board's declared units
    /// ([`WipConfig::convert_terms`]).
    ///
    /// # Pessimistic ranges and fractions
    ///
    /// A fraction and a range are rounded **up** to a whole number in their own
    /// unit, and a range takes its **upper** bound: `0.5 day` is `1d`, and
    /// `0.5-1 day` is `1d`. That is the pessimistic reading the tracker's limits
    /// and capacity calculations count, and it keeps every value a `u32`.
    ///
    /// # Text around the estimate
    ///
    /// A field that holds several comma-separated annotations keeps the segments
    /// that parse and ignores the ones that do not, so `~300 LOC, 0.5-1 day` reads
    /// as `1d`. If no segment parses, the whole value is malformed. A bare number in
    /// a compound statement is still refused (`3 2h` has no unit for the `3`), as
    /// are `-2`, `twenty`, `3d!` and a number that does not fit a `u32`.
    ///
    /// No duration crate is used here by design: `humantime` and `duration-str`
    /// return a single `Duration`, discarding the per-term units that must each go
    /// through the board's own conversion table. Folding the text to seconds would
    /// also invent the clock ratios C-003 forbids.
    pub fn parse_terms(raw: &str) -> std::result::Result<Vec<Self>, WipError> {
        let text = raw.trim();
        match Self::parse_terms_strict(text) {
            Ok(terms) => Ok(terms),
            Err(whole_error) => {
                // A comma is the one separator that may introduce a non-estimate
                // annotation (`~300 LOC, 0.5-1 day`). Keep every segment that parses
                // on its own and drop the rest; if none parses, the value is
                // malformed as a whole.
                if !text.contains(',') {
                    return Err(whole_error);
                }
                let mut terms = Vec::new();
                for segment in text.split(',') {
                    if let Ok(mut parsed) = Self::parse_terms_strict(segment.trim()) {
                        terms.append(&mut parsed);
                    }
                }
                if terms.is_empty() {
                    return Err(whole_error);
                }
                if terms.len() > 1 && terms.iter().any(|term| term.unit.is_none()) {
                    return Err(Self::malformed(format!(
                        "`{text}` mixes a bare number with unit terms"
                    )));
                }
                Ok(terms)
            }
        }
    }

    /// Parse every term in one annotation. Comma-separated terms are part of the
    /// annotation (`1d, 30 min` is two terms); a comma that introduces words is what
    /// makes the whole annotation fail, and [`parse_terms`](Self::parse_terms) then
    /// falls back to per-segment reading.
    fn parse_terms_strict(text: &str) -> std::result::Result<Vec<Self>, WipError> {
        let mut rest = text;
        let mut terms = Vec::new();
        while !rest.is_empty() {
            rest = rest.trim_start_matches(|c: char| c.is_whitespace() || c == ',');
            if rest.is_empty() {
                break;
            }
            let (term, tail) = Self::parse_term(text, rest)?;
            terms.push(term);
            rest = tail;
        }
        if terms.is_empty() {
            return Err(Self::malformed(format!(
                "`{text}` is not `<number>` or `<number><unit>`"
            )));
        }
        if terms.len() > 1 && terms.iter().any(|term| term.unit.is_none()) {
            return Err(Self::malformed(format!(
                "`{text}` mixes a bare number with unit terms"
            )));
        }
        Ok(terms)
    }

    /// Read one `<number>[-<number>][<unit>]` term and return the untouched tail.
    fn parse_term<'a>(text: &str, rest: &'a str) -> std::result::Result<(Self, &'a str), WipError> {
        let (low, mut tail) = Self::parse_decimal(rest).ok_or_else(|| {
            Self::malformed(format!(
                "`{text}` is not a duration such as `<number><unit>` or `<low>-<high><unit>`"
            ))
        })?;
        tail = tail.trim_start_matches([' ', '\t']);
        let mut high = None;
        if let Some(after_dash) = tail.strip_prefix('-') {
            let after_dash = after_dash.trim_start_matches([' ', '\t']);
            let (value, after_high) = Self::parse_decimal(after_dash).ok_or_else(|| {
                Self::malformed(format!("`{text}` starts a range but has no upper bound"))
            })?;
            high = Some(value);
            tail = after_high.trim_start_matches([' ', '\t']);
        }
        let unit: String = tail
            .chars()
            .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-')
            .collect();
        if unit.is_empty() {
            // A bare term is only meaningful when it ends the annotation; a
            // trailing `.`, `!` or another term is refused by the next iteration
            // (or by the compound check).
            if tail.is_empty() || tail.starts_with(',') {
                let value = Self::pessimistic(low, high, text)?;
                return Ok((Self { value, unit: None }, tail));
            }
            return Err(Self::malformed(format!(
                "`{text}` is not `<number>` or `<number><unit>`"
            )));
        }
        if !is_unit_name(&unit) {
            return Err(Self::malformed(format!(
                "`{text}` has an invalid unit `{unit}`"
            )));
        }
        let value = Self::pessimistic(low, high, text)?;
        Ok((
            Self {
                value,
                unit: Some(canonical_unit_word(&unit)),
            },
            &tail[unit.len()..],
        ))
    }

    /// Read a decimal number and return it with the rest of the string.
    fn parse_decimal(rest: &str) -> Option<(f64, &str)> {
        let bytes = rest.as_bytes();
        let mut end = 0;
        while end < bytes.len() && bytes[end].is_ascii_digit() {
            end += 1;
        }
        if end == 0 {
            return None;
        }
        if end < bytes.len() && bytes[end] == b'.' {
            let fraction_start = end + 1;
            let mut fraction_end = fraction_start;
            while fraction_end < bytes.len() && bytes[fraction_end].is_ascii_digit() {
                fraction_end += 1;
            }
            if fraction_end == fraction_start {
                return None;
            }
            end = fraction_end;
        }
        let value = rest.get(..end)?.parse::<f64>().ok()?;
        value.is_finite().then_some((value, &rest[end..]))
    }

    /// The pessimistic whole number for a value or range: the upper bound, rounded
    /// up. Refuses a number no board can count.
    fn pessimistic(low: f64, high: Option<f64>, text: &str) -> std::result::Result<u32, WipError> {
        let value = high.map_or(low, |upper| low.max(upper)).ceil();
        if value > f64::from(u32::MAX) {
            return Err(Self::malformed(format!(
                "`{text}` is not a number this board can count"
            )));
        }
        Ok(value as u32)
    }

    fn malformed(message: String) -> WipError {
        WipError::single(WipDiagnostic::new(
            WipDiagnosticKind::MalformedEstimate,
            message,
        ))
    }

    /// The estimate as it was written, for a message.
    pub fn render(&self) -> String {
        match &self.unit {
            Some(unit) => format!("{}{unit}", self.value),
            None => self.value.to_string(),
        }
    }
}

/// Fold a human duration word to the symbol a board's unit table uses.
///
/// Only **words** are folded; a one-letter unit is returned verbatim, so `S`, `M`
/// and `L` keep whatever meaning the board gave them.
fn canonical_unit_word(unit: &str) -> String {
    if unit.chars().count() == 1 {
        return unit.to_string();
    }
    match unit.to_ascii_lowercase().as_str() {
        "day" | "days" => "d",
        "week" | "weeks" | "wk" | "wks" => "w",
        "hour" | "hours" | "hr" | "hrs" => "h",
        "minute" | "minutes" | "min" | "mins" => "m",
        "second" | "seconds" | "sec" | "secs" => "s",
        _ => unit,
    }
    .to_string()
}

/// Whether `text` names a unit the schema accepts.
fn is_unit_name(text: &str) -> bool {
    let mut chars = text.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    first.is_ascii_alphabetic() && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
}

/// What a WIP finding is about (C-003, C-007).
///
/// The kind is the machine-readable half, so `tix lint` and a surface can branch on
/// the condition while the sentence beside it stays a sentence.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum WipDiagnosticKind {
    /// An estimate is not `<number>` or `<number><unit>`.
    MalformedEstimate,
    /// An estimate names a unit the board never declared.
    MissingConversion,
    /// A conversion that is not a whole number of the target unit.
    AmbiguousConversion,
    /// A unit reference the board does not declare.
    UnknownUnit,
    /// A declared limit is over its ceiling.
    OverLimit,
    /// A limit violation that an override carried through.
    OverrideApplied,
    /// The blocking limit needs an authorized override to be passed.
    OverrideRequired,
    /// The override was not confirmed explicitly.
    UnconfirmedOverride,
    /// The override is missing the actor, the timestamp or the reason.
    MissingOverrideField,
    /// The override was authorized against a limit that has since changed.
    StaleOverrideLimit,
    /// #183's transition policy refused the move; WIP was never reached.
    RejectedTransition,
}

impl WipDiagnosticKind {
    /// The stable spelling every surface prints.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::MalformedEstimate => "malformed_estimate",
            Self::MissingConversion => "missing_conversion",
            Self::AmbiguousConversion => "ambiguous_conversion",
            Self::UnknownUnit => "unknown_unit",
            Self::OverLimit => "over_limit",
            Self::OverrideApplied => "override_applied",
            Self::OverrideRequired => "override_required",
            Self::UnconfirmedOverride => "unconfirmed_override",
            Self::MissingOverrideField => "missing_override_field",
            Self::StaleOverrideLimit => "stale_override_limit",
            Self::RejectedTransition => "rejected_transition",
        }
    }
}

/// One WIP finding: what it is, where it is, and what to do about it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WipDiagnostic {
    /// What is wrong.
    pub kind: WipDiagnosticKind,
    /// One sentence saying what to do about it.
    pub message: String,
    /// A second sentence, when the first is not enough.
    pub because: Option<String>,
}

impl WipDiagnostic {
    /// A finding with its message.
    pub fn new(kind: WipDiagnosticKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            message: message.into(),
            because: None,
        }
    }

    /// Add the sentence that says what to do about it.
    pub fn because(mut self, because: impl Into<String>) -> Self {
        self.because = Some(because.into());
        self
    }

    /// Render through the crate's one diagnostic renderer.
    pub fn render(&self) -> String {
        let mut pairs = vec![(self.kind.as_str(), self.message.as_str())];
        if let Some(because) = self.because.as_deref() {
            pairs.push((self.kind.as_str(), because));
        }
        crate::error::render_diagnostics("E-tix-wip", pairs)
    }
}

/// A set of WIP findings, reported together.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WipError {
    diagnostics: Vec<WipDiagnostic>,
}

impl WipError {
    /// Wrap the findings.
    pub fn new(diagnostics: Vec<WipDiagnostic>) -> Self {
        Self { diagnostics }
    }

    /// A single finding.
    pub fn single(diagnostic: WipDiagnostic) -> Self {
        Self {
            diagnostics: vec![diagnostic],
        }
    }

    /// The findings, in the order they were found.
    pub fn diagnostics(&self) -> &[WipDiagnostic] {
        &self.diagnostics
    }

    /// The first finding.
    pub fn first(&self) -> &WipDiagnostic {
        self.diagnostics
            .first()
            .expect("a WipError carries at least one diagnostic")
    }

    /// Add a sentence to this error's **first** finding, when it is alone.
    pub fn because(self, because: impl Into<String>) -> Self {
        let mut diagnostics = self.diagnostics;
        if let Some(first) = diagnostics.first_mut() {
            first.because = Some(because.into());
        }
        Self { diagnostics }
    }

    /// Every finding as one rendered block.
    pub fn render(&self) -> String {
        self.diagnostics
            .iter()
            .map(WipDiagnostic::render)
            .collect::<Vec<_>>()
            .join("\n")
    }
}

impl std::fmt::Display for WipError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.render())
    }
}

impl std::error::Error for WipError {}

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

    fn board_columns() -> Vec<String> {
        ["todo", "in progress", "in review", "done"]
            .into_iter()
            .map(String::from)
            .collect()
    }

    fn units(pairs: &[(&str, u32)]) -> IndexMap<String, u32> {
        pairs
            .iter()
            .map(|(name, factor)| ((*name).to_string(), *factor))
            .collect()
    }

    /// A board with `d`/`w` declared and one blocked limit on `in progress`.
    fn configured() -> WipConfig {
        WipConfig {
            units: units(&[("d", 1), ("w", 5)]),
            limits: IndexMap::from([(
                "in progress".to_string(),
                ColumnLimit {
                    max_items: Some(3),
                    max_estimate: Some(10),
                    unit: Some("d".to_string()),
                    policy: Some(LimitPolicy::Block),
                    enabled: true,
                },
            )]),
        }
    }

    #[test]
    fn wip_config_absent_limits_are_absent() {
        let empty = WipConfig::default();
        assert!(empty.is_empty());
        assert!(!empty.has_enabled_limits());
        assert!(empty.effective_limit("in progress").is_none());
        let toml = toml::to_string(&empty).expect("an empty section serializes");
        assert_eq!(toml.trim(), "", "an empty section writes no keys: {toml:?}");
        assert!(ColumnLimit::default().is_empty());
    }

    #[test]
    fn wip_config_round_trips_through_toml() {
        let config = configured();
        config.validate("default", &board_columns()).expect("valid");
        let text = toml::to_string(&config).expect("serializes");
        let back: WipConfig = toml::from_str(&text).expect("deserializes");
        assert_eq!(back, config, "round trip: {text}");
        assert!(back.has_enabled_limits());
    }

    #[test]
    fn wip_config_omits_defaults_on_save() {
        // A hand-written limit with neither `enabled` nor a unit it does not need
        // must come back byte-identical: no default key materializes.
        let text = "[limits.\"in progress\"]\nmax_items = 3\npolicy = \"warn\"\n";
        let config: WipConfig = toml::from_str(text).expect("loads");
        assert!(config.limits["in progress"].enabled, "default on");
        assert_eq!(toml::to_string(&config).expect("saves"), text);
    }

    #[test]
    fn wip_config_rejects_an_unknown_column() {
        let mut config = configured();
        config.limits.insert(
            "shipped".to_string(),
            ColumnLimit::items(1, LimitPolicy::Warn),
        );
        let error = config
            .validate("default", &board_columns())
            .expect_err("an unknown column is refused")
            .to_string();
        assert!(
            error.contains("kanban.default.wip.limits.`shipped`"),
            "{error}"
        );
        assert!(error.contains("columns"), "{error}");
    }

    #[test]
    fn wip_config_rejects_an_enabled_limit_that_limits_nothing() {
        let mut config = configured();
        config.limits.insert(
            "in review".to_string(),
            ColumnLimit {
                policy: Some(LimitPolicy::Warn),
                ..ColumnLimit::default()
            },
        );
        let error = config
            .validate("default", &board_columns())
            .expect_err("an enabled empty limit is refused")
            .to_string();
        assert!(
            error.contains("neither `max_items` nor `max_estimate`"),
            "{error}"
        );
    }

    #[test]
    fn wip_config_requires_a_policy_and_a_unit() {
        let mut missing_policy = configured();
        missing_policy.limits["in progress"].policy = None;
        let error = missing_policy
            .validate("default", &board_columns())
            .expect_err("a policy is required")
            .to_string();
        assert!(error.contains("policy` is required"), "{error}");

        let mut missing_unit = configured();
        missing_unit.limits["in progress"].unit = None;
        let error = missing_unit
            .validate("default", &board_columns())
            .expect_err("a unit is required with max_estimate")
            .to_string();
        assert!(error.contains("is required with `max_estimate`"), "{error}");

        let mut unit_without_estimate = configured();
        unit_without_estimate.limits["in progress"].max_estimate = None;
        let error = unit_without_estimate
            .validate("default", &board_columns())
            .expect_err("a unit without an estimate is refused")
            .to_string();
        assert!(
            error.contains("only meaningful with `max_estimate`"),
            "{error}"
        );
    }

    #[test]
    fn wip_config_rejects_undeclared_units_and_zero_factors() {
        let mut undeclared = configured();
        undeclared.limits["in progress"].unit = Some("q".to_string());
        let error = undeclared
            .validate("default", &board_columns())
            .expect_err("an undeclared unit is refused")
            .to_string();
        assert!(error.contains("`q`"), "{error}");
        assert!(error.contains("wip.units"), "{error}");

        let mut zero = configured();
        zero.units.insert("z".to_string(), 0);
        let error = zero
            .validate("default", &board_columns())
            .expect_err("a zero factor is refused")
            .to_string();
        assert!(error.contains("wip.units.z"), "{error}");
    }

    #[test]
    fn wip_config_zero_ceilings_are_refused() {
        for key in ["max_items", "max_estimate"] {
            let mut config = configured();
            let limit = config.limits.get_mut("in progress").expect("the limit");
            match key {
                "max_items" => limit.max_items = Some(0),
                _ => limit.max_estimate = Some(0),
            }
            let error = config
                .validate("default", &board_columns())
                .expect_err("a zero ceiling is refused")
                .to_string();
            assert!(error.contains(key), "{error}");
            assert!(error.contains("at least 1"), "{error}");
        }
    }

    #[test]
    fn wip_config_disabled_limit_is_validated_but_not_effective() {
        let mut config = configured();
        config.limits["in progress"].enabled = false;
        config.limits["in progress"].policy = None;
        config
            .validate("default", &board_columns())
            .expect("a disabled limit may state no policy");
        assert!(config.effective_limit("in progress").is_none());
        assert!(!config.has_enabled_limits());
        assert!(
            config.limits.contains_key("in progress"),
            "the numbers stay for later"
        );
    }

    #[test]
    fn wip_config_estimate_parsing_is_strict_but_total() {
        assert_eq!(
            Estimate::parse(" 3d ").expect("a unit"),
            Estimate {
                value: 3,
                unit: Some("d".to_string())
            }
        );
        assert_eq!(
            Estimate::parse("12").expect("a bare number"),
            Estimate {
                value: 12,
                unit: None
            }
        );
        assert_eq!(
            Estimate::parse("5story-points").expect("a hyphenated unit"),
            Estimate {
                value: 5,
                unit: Some("story-points".to_string())
            }
        );
        assert_eq!(
            Estimate::parse("1 day").expect("a prose unit"),
            Estimate {
                value: 1,
                unit: Some("d".to_string())
            }
        );
        assert_eq!(
            Estimate::parse("2 DAYS").expect("case-insensitive prose"),
            Estimate {
                value: 2,
                unit: Some("d".to_string())
            }
        );
        assert_eq!(
            Estimate::parse("3S").expect("a one-letter unit keeps its case"),
            Estimate {
                value: 3,
                unit: Some("S".to_string())
            }
        );
        assert_eq!(
            Estimate::parse("3.5").expect("a fraction rounds up"),
            Estimate {
                value: 4,
                unit: None
            }
        );
        for bad in [
            "",
            "twenty",
            "-2",
            "d3",
            "3d!",
            "3 2h",
            "1 day 2",
            "99999999999999",
        ] {
            let error = Estimate::parse(bad).expect_err("refused: {bad}");
            assert_eq!(error.first().kind, WipDiagnosticKind::MalformedEstimate);
        }
    }

    #[test]
    fn wip_config_estimate_parses_compound_durations_term_by_term() {
        let terms = Estimate::parse_terms("3 weeks 2 hours").expect("two terms");
        assert_eq!(
            terms,
            vec![
                Estimate {
                    value: 3,
                    unit: Some("w".to_string())
                },
                Estimate {
                    value: 2,
                    unit: Some("h".to_string())
                },
            ]
        );
        assert_eq!(
            Estimate::parse_terms("1d, 30 min").expect("comma-separated"),
            vec![
                Estimate {
                    value: 1,
                    unit: Some("d".to_string())
                },
                Estimate {
                    value: 30,
                    unit: Some("m".to_string())
                },
            ]
        );
        assert!(
            Estimate::parse("3 weeks 2 hours").is_err(),
            "the single-term entry point still names one term"
        );
    }

    #[test]
    fn wip_config_estimate_ranges_are_pessimistic() {
        assert_eq!(
            Estimate::parse("0.5-1 day").expect("a range"),
            Estimate {
                value: 1,
                unit: Some("d".to_string())
            }
        );
        assert_eq!(
            Estimate::parse("0.5 day").expect("a fraction rounds up"),
            Estimate {
                value: 1,
                unit: Some("d".to_string())
            }
        );
        assert_eq!(
            Estimate::parse("2.1-2.2d").expect("the upper bound, rounded up"),
            Estimate {
                value: 3,
                unit: Some("d".to_string())
            }
        );
        assert_eq!(
            Estimate::parse("2-1 day").expect("the larger bound wins"),
            Estimate {
                value: 2,
                unit: Some("d".to_string())
            }
        );
    }

    #[test]
    fn wip_config_estimate_ignores_unreadable_comma_annotations() {
        assert_eq!(
            Estimate::parse_terms("~300 LOC, 0.5-1 day").expect("the estimate segment"),
            vec![Estimate {
                value: 1,
                unit: Some("d".to_string())
            }]
        );
        assert_eq!(
            Estimate::parse_terms("3d, best guess").expect("the first segment"),
            vec![Estimate {
                value: 3,
                unit: Some("d".to_string())
            }]
        );
        assert!(
            Estimate::parse_terms("~300 LOC").is_err(),
            "no readable segment means malformed"
        );
    }

    #[test]
    fn wip_config_sums_compound_estimates_through_the_board_units() {
        let config = WipConfig {
            units: units(&[("h", 1), ("d", 8), ("w", 40)]),
            limits: IndexMap::new(),
        };
        let terms = Estimate::parse_terms("3 weeks 2 hours").expect("parses");
        assert_eq!(
            config.convert_terms(&terms, "h").expect("exact"),
            3 * 5 * 8 + 2,
            "a prose estimate is board-relative, never a clock-ratio guess"
        );
        // One unconvertible term refuses the whole sum; nothing is dropped.
        let terms = Estimate::parse_terms("1 day 30 fortnights").expect("parses");
        let error = config
            .convert_terms(&terms, "h")
            .expect_err("the second unit is undeclared");
        assert_eq!(error.first().kind, WipDiagnosticKind::MissingConversion);
    }

    #[test]
    fn wip_config_converts_between_declared_units() {
        let config = configured();
        let weeks = Estimate {
            value: 1,
            unit: Some("w".to_string()),
        };
        assert_eq!(config.convert(&weeks, "d").expect("1w is 5d"), 5);
        assert_eq!(
            config
                .convert(&Estimate::parse("10d").expect("parses"), "d")
                .expect("same unit"),
            10
        );
        assert_eq!(
            config
                .convert(&Estimate::parse("7").expect("parses"), "w")
                .expect("bare means the target unit"),
            7
        );
        let half_weeks = Estimate {
            value: 5,
            unit: Some("w".to_string()),
        };
        assert_eq!(
            config.convert(&half_weeks, "w").expect("same unit"),
            5,
            "5w is 5w"
        );
        assert_eq!(config.convert(&half_weeks, "d").expect("25 points"), 25);
    }

    #[test]
    fn wip_config_refuses_a_missing_conversion() {
        let config = configured();
        let points = Estimate {
            value: 3,
            unit: Some("p".to_string()),
        };
        let error = config.convert(&points, "d").expect_err("undeclared unit");
        assert_eq!(error.first().kind, WipDiagnosticKind::MissingConversion);
        let rendered = error.render();
        assert!(rendered.contains("missing_conversion"), "{rendered}");
        assert!(rendered.contains("`3p`"), "{rendered}");

        let error = config
            .convert(&Estimate::parse("3").expect("parses"), "q")
            .expect_err("an undeclared target unit");
        assert_eq!(error.first().kind, WipDiagnosticKind::UnknownUnit);
    }

    #[test]
    fn wip_config_refuses_a_fractional_conversion() {
        // A board whose base is `h`: `d` is 8, so 3d is 24h; counting that in `w`
        // (a 5-hour unit) is not a whole number and must not be rounded.
        let config = WipConfig {
            units: units(&[("h", 1), ("d", 8), ("w", 40)]),
            limits: IndexMap::new(),
        };
        let error = config
            .convert(&Estimate::parse("3d").expect("parses"), "w")
            .expect_err("24 is not a whole number of 5");
        assert_eq!(error.first().kind, WipDiagnosticKind::AmbiguousConversion);
        let rendered = error.render();
        assert!(rendered.contains("ambiguous_conversion"), "{rendered}");
        assert!(rendered.contains("24 base points"), "{rendered}");
        // …and the same estimate in `h` is exact.
        assert_eq!(
            config
                .convert(&Estimate::parse("3d").expect("parses"), "h")
                .expect("24h"),
            24
        );
    }

    #[test]
    fn wip_config_policy_spellings_are_stable() {
        assert_eq!(LimitPolicy::Warn.as_str(), "warn");
        assert_eq!(LimitPolicy::Block.as_str(), "block");
        let limit = configured().limits["in progress"].clone();
        assert_eq!(limit.resolved_policy(), Some(LimitPolicy::Block));
        let disabled = ColumnLimit {
            enabled: false,
            ..limit
        };
        assert_eq!(disabled.resolved_policy(), None);
    }
}