tix-tracker 0.8.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
//! 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).
//!
//! # 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)
    }

    /// 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 the free-form `estimate:` frontmatter.
    ///
    /// `<digits>` optionally followed by `<unit>`, where a unit starts with an ASCII
    /// letter and continues with letters, digits, `_` or `-`. Nothing is inferred
    /// from anything else: `3 d`, `3.5`, `-2` and `twenty` are all refused with the
    /// value quoted back, because an estimate nobody can count is worse than none.
    pub fn parse(raw: &str) -> std::result::Result<Self, WipError> {
        let text = raw.trim();
        let digits: String = text.chars().take_while(char::is_ascii_digit).collect();
        let rest = &text[digits.len()..];
        if digits.is_empty() || (!rest.is_empty() && !is_unit_name(rest)) {
            return Err(WipError::single(WipDiagnostic::new(
                WipDiagnosticKind::MalformedEstimate,
                format!("`{text}` is not `<number>` or `<number><unit>`"),
            )));
        }
        let value = digits.parse::<u32>().map_err(|_| {
            WipError::single(WipDiagnostic::new(
                WipDiagnosticKind::MalformedEstimate,
                format!("`{text}` is not a number this board can count"),
            ))
        })?;
        Ok(Self {
            value,
            unit: (!rest.is_empty()).then(|| rest.to_string()),
        })
    }

    /// 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(),
        }
    }
}

/// 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 {
    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())
            }
        );
        for bad in [
            "",
            "twenty",
            "3 d",
            "3.5",
            "-2",
            "d3",
            "3d!",
            "99999999999999",
        ] {
            let error = Estimate::parse(bad).expect_err("refused: {bad}");
            assert_eq!(error.first().kind, WipDiagnosticKind::MalformedEstimate);
        }
    }

    #[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", 5)]),
            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);
    }
}