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
//! `[capacity]`: capacity ceilings, and the scopes they belong to (WP01).
//!
//! # The shape
//!
//! ```toml
//! [capacity.zulu]                 # the key is only a handle for the record
//! cycle = "Cycle 1"               # …and exactly one of these says which scope
//! capacity = 20
//! unit = "d"                      # declared on the board the calculation runs under
//!
//! [capacity.platform]
//! team = "Platform"
//! capacity = 15
//! unit = "d"
//!
//! [capacity.ada]
//! assignee = "Ada Lovelace <ada@example.com>"
//! capacity = 3
//! unit = "w"
//! ```
//!
//! Five decisions, and each one closes a door rather than opening one:
//!
//! 1. **The scope is a field, and there is exactly one of it.** `cycle`, `team` and
//!    `assignee` are three mutually exclusive keys: naming none is refused
//!    (`` `capacity.<id>.scope` `` must name one) and naming two is refused as
//!    ambiguous. A shape that derived the scope from *where* the entry sits would make
//!    "which dimension is this?" unstateable, and C-003 refuses implicit scope
//!    inheritance outright — so the entry says it, once.
//! 2. **The unit is named, and the board the calculation runs under must declare it.**
//!    `[kanban.<board>.wip.units]` is the unit registry (the WIP mission's — reused, never
//!    re-declared here), and a capacity entry has no board of its own, so the board the
//!    arithmetic actually converts under is the one that has to know the unit. An entry
//!    counting in a unit only *another* board declares is refused at load, naming that
//!    board and the table to declare it in — otherwise it would load clean, refuse to
//!    calculate, and print a remedy for a unit the user had already declared, and a unit
//!    two boards declare with different factors would silently convert under the wrong one.
//!    A capacity with no unit is refused by name; it is *not* defaulted, and no new unit is
//!    ever invented (C-004).
//! 3. **`capacity` is an integer at or above zero.** An enabled entry must state one.
//!    A disabled entry keeps the scope without a ceiling, which is the "omit or disable
//!    without deleting history" case the data model asks for.
//! 4. **One ceiling per scope.** Two entries whose scope **resolves to** one
//!    cycle/team/assignee are refused — including two spellings of one cycle (its name and
//!    its stable id) or of one handle (`ada` and `@ada`) — because two answers to "how much
//!    is this allowed to commit?" is a question with no answer.
//! 5. **Nothing is required to be present.** The section is omitted whole when empty, so
//!    a capacity-free `tix.toml` gains no key and round-trips byte-identically (C-001),
//!    and each entry preserves unknown metadata verbatim so a newer `tix` can add a
//!    field this build carries rather than drops.
//!
//! # Cycle references resolve through the crate's one adapter, over the records
//!
//! A cycle scope reference is what the entry's `cycle` key holds, and it is resolved by
//! [`resolve_cycle`] over a [`ScheduleIndex`] the caller built from the cycle **records**:
//! [`ScheduleIndex::resolve`] for the name half (the same adapter an issue's `cycles`
//! value goes through), [`GeneratedCycleId::parse`] plus [`ScheduleIndex::cycle`] for the
//! stable `\<schedule-id\>:\<sequence\>` id half. The records matter: `Config::cycles` is
//! name-keyed and narrows each record to `PlanningCycle`, which carries no
//! `schedule_id`/`sequence`/`state`, so an index built from those keys alone would see
//! every cycle as hand-written. Feeding the records — `docs/cycles/`, or the legacy
//! `[cycles.<name>]` tables when there is no store, which is the loader's own rule in
//! [`cycle_records`] — makes a generated cycle's **name** classify as
//! [`CycleReference::Generated`] with its id, exactly as
//! [`crate::cycle_schedule::registry::load_index`] answers. There is deliberately no
//! second name resolver in this module: the string that identifies a cycle is
//! issue-181's, not capacity's.
//!
//! # Which half of the validation lives where, and why it must not move
//!
//! The section is checked by **two** halves, and the split is deliberate:
//!
//! * [`validate`] is **rootless** — it reads no file — and is called by
//!   [`crate::config::Config::validate`], i.e. by every *validate-then-save* path in the
//!   crate (`tix wip unit --remove`, the schedule registry, the MCP write tools, planning).
//!   It covers what the configuration alone decides: the entry handle, the extensions
//!   shadow check, exactly one scope with a non-blank unpadded reference, a team label that
//!   exists, an assignee identity the model parses, the ceiling (enabled ⇒ present and
//!   non-negative), the unit (enabled ⇒ present, not blank, **declared by a board**), and a
//!   scope no other entry already took. The declared-unit check belongs here beyond
//!   argument: `tix wip unit --remove` drops a unit and then validates the *same in-memory*
//!   config before writing, so without it the command would persist a file whose next load
//!   refuses — a repository nobody could read again.
//! * [`validate_cycle_references`] needs a **project root**, and is called by the two gates
//!   that have one: [`crate::config::Config::load_with_warning`] (every hand-edited file)
//!   and [`set_capacity`] (every programmatic change). It resolves each cycle reference
//!   against the cycle **records** — `docs/cycles/`, whose generated identities are the only
//!   place a generated cycle's name can be told from a hand-written one — and unifies two
//!   spellings of one cycle into one ceiling. Its validity rule is provenance-independent:
//!   a reference is valid when it resolves through the records **or** when it names a
//!   `[cycles.<name>]` entry in the configuration (which, after a load, holds every stored
//!   cycle's reference name too), so the same entry is accepted whether or not the caller
//!   happened to read a cycle store.
//!
//! Moving the declared-unit check into the records' half (or dropping it from the rootless
//! one) is the failure this split exists to prevent; moving the *record* resolution into
//! the rootless half is impossible, because `Config::validate` has no root. Anything added
//! here should go to the half whose inputs it actually reads.
//!
//! # Closed cycles: what this package guarantees, and what it leaves to WP04
//!
//! A closed cycle's capacity is **historical evidence** (C-008). WP01 guarantees two
//! things and no more:
//!
//! * **No-op.** This section holds no snapshot state, so validating and saving a
//!   `tix.toml` cannot rewrite a snapshot: there is nothing in the record to rewrite.
//!   A change to a *current or future* scope is therefore applied and the closed cycle's
//!   evidence file is left byte-identical — asserted end to end.
//! * **Refusal, on the write path.** [`set_capacity`] is the one way this package changes
//!   capacity, and it calls [`ensure_cycle_editable`] before it writes anything: an
//!   ordinary [`CapacityEdit::Configure`] aimed at a terminal cycle — closed, whose
//!   snapshot is the record, or skipped, which was never generated — is refused, leaving
//!   both the in-memory section and `tix.toml` as they were. The one way through is
//!   [`CapacityEdit::Reopen`], which carries the audit reason of the explicit append-only
//!   `History` event.
//!
//! WP04 owns the other half: capturing the snapshot at close, storing it, and appending
//! the reopen/edit event. This module knows none of that — it only refuses to be a
//! second way in.

use std::collections::HashMap;
use std::path::Path;

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

use crate::config::Config;
use crate::cycle_schedule::identity::{
    CycleReference, GeneratedCycle, GeneratedCycleId, GeneratedCycleState, ScheduleIndex,
};
use crate::cycle_store::{CycleRecord, CycleStore};
use crate::error::{Result, TixError};

/// The scope dimension a capacity ceiling belongs to (C-003, data-model §1).
///
/// `cycle`, `team` and `assignee` are the three the contract names and there is no
/// fourth: "unsupported or implicit scope inheritance is an escalation trigger", so a
/// variant that swept several issues together would be a new semantic rather than a new
/// spelling. The variants serialize as the entry keys of the same name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CapacityScopeKind {
    /// One cycle, by the name the registry/records answer to or by generated id.
    Cycle,
    /// One configured team, by its `[teams.<label>]` label.
    Team,
    /// One assignee identity, in the shape an issue's `assignee` field tolerates.
    Assignee,
}

impl CapacityScopeKind {
    /// The stable spelling every surface prints and `tix.toml` stores.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Cycle => "cycle",
            Self::Team => "team",
            Self::Assignee => "assignee",
        }
    }

    /// Every scope kind, in the order a diagnostic lists them.
    #[must_use]
    pub const fn all() -> [Self; 3] {
        [Self::Cycle, Self::Team, Self::Assignee]
    }
}

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

/// Metadata this build does not interpret, preserved verbatim.
///
/// The same guarantee the sibling registries give their records
/// ([`crate::cycle_schedule::config::CycleScheduleExtensions`],
/// [`crate::roadmap::registry::InitiativeExtensions`]): a key a newer `tix` adds must
/// survive an edit-and-save round trip instead of being dropped. The one rule it cannot
/// break is that a preserved key must not **shadow** a built-in field — a file can never
/// deliver such a key (serde matches the known field first), but the public write path
/// could inject one, and `toml` serializes duplicate table keys without complaining, so
/// the write would appear to succeed while the next load failed on a duplicate key.
/// [`validate`] refuses it instead.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct CapacityExtensions(toml::Table);

impl CapacityExtensions {
    /// Whether no unknown metadata is present.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// The number of preserved keys.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Look up a preserved key.
    #[must_use]
    pub fn get(&self, key: &str) -> Option<&toml::Value> {
        self.0.get(key)
    }

    /// The preserved keys, in canonical order.
    pub fn keys(&self) -> impl Iterator<Item = &str> {
        self.0.keys().map(String::as_str)
    }

    /// Iterate the preserved `(key, value)` pairs in canonical order.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &toml::Value)> {
        self.0.iter().map(|(k, v)| (k.as_str(), v))
    }

    /// The underlying table, for a caller that must serialize it whole.
    #[must_use]
    pub fn table(&self) -> &toml::Table {
        &self.0
    }

    /// Preserve one `(key, value)` pair, returning the previous value if any.
    pub fn insert(&mut self, key: impl Into<String>, value: toml::Value) -> Option<toml::Value> {
        self.0.insert(key.into(), value)
    }
}

impl PartialEq for CapacityExtensions {
    fn eq(&self, other: &Self) -> bool {
        // Compared through the rendered value, so two maps that hold the same keys and
        // values compare equal whatever order they were built in.
        toml::Value::Table(self.0.clone()).to_string()
            == toml::Value::Table(other.0.clone()).to_string()
    }
}

impl Eq for CapacityExtensions {}

impl From<toml::Table> for CapacityExtensions {
    fn from(table: toml::Table) -> Self {
        Self(table)
    }
}

/// Indexing by handle, so a caller that has validated a config reads
/// `config.capacity["zulu"]` the way it reads any other registry in `tix.toml`.
///
/// Panics on an unknown handle, exactly as indexing an `IndexMap` does: a missing entry
/// is a programming error by the time a caller has a handle, and [`CapacityConfig::get`]
/// is the total alternative.
impl std::ops::Index<&str> for CapacityConfig {
    type Output = CapacityEntry;

    fn index(&self, id: &str) -> &Self::Output {
        &self.0[id]
    }
}

/// The fields [`CapacityEntry`] reads as typed values.
///
/// This is the set serde treats as **known** for the record — the fields that survive
/// through the typed struct rather than being swept into the preserved
/// [`extensions`](CapacityEntry::extensions) table. It must stay in step with the
/// struct: add a field there and add it here, or the shadow check would let the new name
/// through and the next load would fail on a duplicate key.
pub const CAPACITY_ENTRY_KNOWN_FIELDS: &[&str] =
    &["cycle", "team", "assignee", "capacity", "unit", "enabled"];

/// One capacity ceiling, for exactly one scope.
///
/// The three scope keys are `Option<String>` on purpose: "absent" has to be
/// distinguishable from "set", because an entry that names no scope is refused by name
/// (C-003) rather than guessed from the surrounding table. `capacity` is `i64` rather
/// than an unsigned integer so that a negative number is *refused with its field path*
/// instead of failing in the TOML parser, where no diagnostic could name the record.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct CapacityEntry {
    /// The cycle this ceiling belongs to: the name a `[cycles.<name>]` record answers
    /// to, or a generated cycle's stable id. See [`resolve_cycle`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cycle: Option<String>,
    /// The team this ceiling belongs to: a `[teams.<label>]` key.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub team: Option<String>,
    /// The assignee this ceiling belongs to: an identity in the shape an issue's
    /// `assignee` field tolerates (a handle, or `Name <email>`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub assignee: Option<String>,
    /// The ceiling itself, at or above zero, counted in [`unit`](Self::unit).
    ///
    /// Required for an enabled entry; a **disabled** entry may omit it, which is how a
    /// scope stays configured without a ceiling in force.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub capacity: Option<i64>,
    /// The estimate unit [`capacity`](Self::capacity) counts in. Required for an enabled
    /// entry, refused when blank, and refused when no board declares it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unit: Option<String>,
    /// Whether the ceiling is in force. `false` keeps the numbers for later without
    /// changing today's calculations.
    #[serde(
        default = "crate::config::default_true",
        skip_serializing_if = "crate::config::is_true"
    )]
    pub enabled: bool,
    /// Unknown metadata, preserved verbatim.
    #[serde(flatten)]
    pub extensions: CapacityExtensions,
}

impl Default for CapacityEntry {
    fn default() -> Self {
        Self {
            cycle: None,
            team: None,
            assignee: None,
            capacity: None,
            unit: None,
            enabled: true,
            extensions: CapacityExtensions::default(),
        }
    }
}

impl CapacityEntry {
    /// The `(kind, reference)` this entry names, in scope-kind order.
    ///
    /// Zero entries means "no scope", more than one means "ambiguous"; both are refused
    /// by [`validate`]. A caller that has validated a config always gets exactly one.
    pub fn scopes(&self) -> impl Iterator<Item = (CapacityScopeKind, &str)> {
        [
            (CapacityScopeKind::Cycle, self.cycle.as_deref()),
            (CapacityScopeKind::Team, self.team.as_deref()),
            (CapacityScopeKind::Assignee, self.assignee.as_deref()),
        ]
        .into_iter()
        .filter_map(|(kind, reference)| reference.map(|reference| (kind, reference)))
    }

    /// The scope kind this entry names, when it names exactly one.
    #[must_use]
    pub fn scope_kind(&self) -> Option<CapacityScopeKind> {
        let mut scopes = self.scopes();
        let first = scopes.next()?;
        scopes.next().is_none().then_some(first.0)
    }

    /// The scope reference this entry names, when it names exactly one.
    #[must_use]
    pub fn scope_id(&self) -> Option<&str> {
        let mut scopes = self.scopes();
        let first = scopes.next()?;
        scopes.next().is_none().then_some(first.1)
    }

    /// Whether the ceiling is in force: enabled, with a value and a unit.
    ///
    /// The resolver every surface should ask, so "declared but disabled" cannot be read
    /// as "enforced" by one caller and not another — the same rule
    /// [`crate::wip::config::WipConfig::effective_limit`] follows for limits.
    #[must_use]
    pub fn effective(&self) -> bool {
        self.enabled && self.capacity.is_some() && self.unit.is_some()
    }
}

/// The `[capacity]` section: capacity entries keyed by a handle, in declaration order.
///
/// Serialized transparently as the TOML table `[capacity.<entry-id>]` and omitted whole
/// when empty, so a repository that configures no capacity gains no key on save and a
/// legacy `tix.toml` round-trips byte-identically (C-001).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct CapacityConfig(IndexMap<String, CapacityEntry>);

impl CapacityConfig {
    /// An empty section.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Whether no capacity is configured: the state that writes nothing.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// How many entries are configured.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// One entry by its handle.
    #[must_use]
    pub fn get(&self, id: &str) -> Option<&CapacityEntry> {
        self.0.get(id)
    }

    /// One entry by its handle, mutably.
    #[must_use]
    pub fn get_mut(&mut self, id: &str) -> Option<&mut CapacityEntry> {
        self.0.get_mut(id)
    }

    /// The entries, in declaration order.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &CapacityEntry)> {
        self.0.iter().map(|(id, entry)| (id.as_str(), entry))
    }

    /// The entries as a map, for a caller that must serialize or compare them whole.
    #[must_use]
    pub fn entries(&self) -> &IndexMap<String, CapacityEntry> {
        &self.0
    }

    /// The entries mutably, for the declaration-order restoration the loader performs.
    #[must_use]
    pub fn entries_mut(&mut self) -> &mut IndexMap<String, CapacityEntry> {
        &mut self.0
    }

    /// Preserve one entry, returning the previous one if the handle was already used.
    pub fn insert(&mut self, id: impl Into<String>, entry: CapacityEntry) -> Option<CapacityEntry> {
        self.0.insert(id.into(), entry)
    }

    /// Restore the declaration order the `toml` parser loses (it sorts table keys) from
    /// the `[capacity.<entry-id>]` headers in the source document.
    pub fn restore_declaration_order(&mut self, contents: &str) {
        crate::config::restore_section_order(&mut self.0, contents, "capacity");
    }
}

/// Whether the board capacity calculations run under declares `unit`.
///
/// A unit is declared by a board under `[kanban.<board>.wip.units]`; that map is the one
/// owner of "what units exist and how they convert" (`configurable-wip-limits-01M3C6WX`),
/// and capacity reuses it rather than restating it.
///
/// The check is against **that one board** — [`Config::default_config`], the registry the
/// calculation converts under — and not against the union of every board's units. The
/// union was wrong in two ways, and neither showed up until a project declared more than
/// one board:
///
/// * an entry counting in a unit only *another* board declares was accepted at load and
///   could never be calculated: the conversion under the calculation board answers
///   `UnknownUnit`, and the remedy it printed ("declare the unit under
///   `[kanban.<board>.wip.units]`") pointed at a unit the user had already declared;
/// * a unit two boards declare with **different factors** was accepted and then converted
///   under the calculation board's factor — a wrong number, with no diagnostic at all.
///
/// Checking here, where the refusing happens, closes both: an accepted entry counts in a
/// unit the arithmetic can actually resolve, and the factor it resolves to is the one this
/// gate looked at. A capacity entry has no board of its own — a scope names a cycle, a team,
/// or an assignee — so there is no other board it could honestly be judged against.
fn declared_unit(config: &Config, unit: &str) -> bool {
    config.default_config().wip.units.contains_key(unit)
}

/// The cycle records a capacity reference resolves against.
///
/// [`crate::cycle_store::CycleStore::list`] is the canonical reader — the store's records
/// when `docs/cycles/` exists, the implicit `Default` cycle when it does not. The second
/// half is the loader's own fallback: with no store, `Config::cycles` **is** this project's
/// cycle registry (the legacy `[cycles.<name>]` tables the loader keeps), so those names
/// are added as the name-only records they are. An index built from the store alone would
/// call every legacy cycle unknown, which is why the fallback is here and not at the call
/// site.
fn cycle_records(config: &Config, root: &Path) -> Result<Vec<CycleRecord>> {
    let store = CycleStore::new(root);
    let mut records = store.list()?;
    if !store.exists() {
        records.extend(config.cycles.keys().map(|name| CycleRecord {
            name: name.clone(),
            ..CycleRecord::default()
        }));
    }
    Ok(records)
}

/// The [`ScheduleIndex`] a capacity reference resolves against.
///
/// Built from [`cycle_records`]: `CycleStore::list()`'s records — the same input
/// [`crate::cycle_schedule::registry::load_index`] feeds its index — plus, when there is no
/// store, the legacy `[cycles.<name>]` names a store cannot see. So with a store present it
/// *is* `load_index`'s index, and without one it is a strict superset of it: a caller
/// holding either may pass it to [`resolve_cycle`], and both answer `Generated` or `Legacy`
/// identically for anything the store contains. They differ only on a store-less project's
/// legacy names, where the store-only index answers `Unknown` — which is why
/// [`validate_cycle_references`] decides validity by *records or configuration*, never by
/// which provenance the caller happens to have.
pub fn schedule_index(config: &Config, root: &Path) -> Result<ScheduleIndex> {
    Ok(ScheduleIndex::build(config, &cycle_records(config, root)?))
}

/// The stored record a scope reference names, when one exists.
///
/// A generated cycle's stable id names its record directly; a name is the record's own
/// `name`, whatever kind of cycle it belongs to. `None` means the record is not on this
/// project's disk — a legacy `[cycles.<name>]` table, or the implicit `Default` cycle —
/// which is also the answer "no lifecycle state to consult".
fn cycle_record<'a>(
    index: &ScheduleIndex,
    records: &'a [CycleRecord],
    reference: &str,
) -> Option<&'a CycleRecord> {
    if let Ok(id) = GeneratedCycleId::parse(reference)
        && let Some(cycle) = index.cycle(&id)
    {
        return records.iter().find(|record| record.name == cycle.name);
    }
    records.iter().find(|record| record.name == reference)
}

/// Resolve a cycle scope reference through the crate's one cycle identity adapter.
///
/// The reference is the name a cycle record answers to — hand-written or generated — or
/// a generated cycle's stable `<schedule-id>:<sequence>` id. Names are decided by
/// [`ScheduleIndex::resolve`]; ids by [`GeneratedCycleId::parse`] plus an existence check
/// through [`ScheduleIndex::cycle`], because `by_reference` is keyed by name. Both halves
/// answer with the same three-answer [`CycleReference`] vocabulary, and an unknown
/// reference stays unknown rather than being rebound to whatever cycle is nearby.
/// Neither rewrites an issue reference or a cycle date.
///
/// `index` is the caller's, built from the cycle records — everything
/// [`ScheduleIndex::build`] reads. [`crate::cycle_schedule::registry::load_index`] builds
/// exactly that from a project root.
#[must_use]
pub fn resolve_cycle(index: &ScheduleIndex, reference: &str) -> CycleReference {
    let resolved = index.resolve(reference);
    if !matches!(resolved, CycleReference::Unknown { .. }) {
        return resolved;
    }
    let Ok(id) = GeneratedCycleId::parse(reference) else {
        return resolved;
    };
    let Some(cycle) = index.cycle(&id) else {
        return resolved;
    };
    CycleReference::Generated {
        name: cycle.name.clone(),
        id,
        schedule_id: cycle.schedule_id.clone(),
    }
}

/// The authorization a capacity change carries (T004, C-008).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CapacityEdit<'a> {
    /// An ordinary configuration change: it applies to current and future calculations
    /// only.
    Configure,
    /// The explicit reopen path — the append-only `History` event — carrying the reason
    /// the audit trail stores.
    Reopen {
        /// Why the closed cycle is being reopened. Required, and never blank.
        reason: &'a str,
    },
}

/// The closed-cycle boundary every capacity change goes through (T004, C-008).
///
/// A closed generated cycle's capacity is the historical record: WP04 captures it as an
/// immutable snapshot at close, and this function is how a configuration change is kept
/// away from it. The state is read from the cycle **record** — through
/// [`GeneratedCycle::from_record`], the crate's one parser for it — rather than from a
/// caller-supplied flag, and a partial generated identity is propagated as the finding
/// it is instead of being treated as open.
///
/// * [`CapacityEdit::Configure`] is refused for a terminal cycle: `closed` has a
///   snapshot that must not be rewritten, and `skipped` was never generated, so it has
///   no capacity to configure.
/// * [`CapacityEdit::Reopen`] is the one way through, and it refuses a blank reason
///   because the event it produces is auditable.
///
/// A hand-written cycle carries no lifecycle state at all, so it is always editable.
pub fn ensure_cycle_editable(record: &CycleRecord, edit: &CapacityEdit<'_>) -> Result<()> {
    match edit {
        CapacityEdit::Reopen { reason } => {
            if reason.trim().is_empty() {
                return Err(TixError::Config(
                    "`reopen.reason` must not be blank: a reopen is auditable, and its reason is \
                     stored with the append-only `History` event"
                        .into(),
                ));
            }
            Ok(())
        }
        CapacityEdit::Configure => match GeneratedCycle::from_record(record)? {
            Some(cycle) if cycle.state == GeneratedCycleState::Closed => {
                Err(TixError::Config(format!(
                    "`cycles.{}` is closed; its capacity (`{}`) is the historical record captured \
                     at close, and a configuration change applies to current and future \
                     calculations only — reopen it through the explicit `History` event instead",
                    record.name, cycle.id
                )))
            }
            Some(cycle) if cycle.state == GeneratedCycleState::Skipped => {
                Err(TixError::Config(format!(
                    "`cycles.{}` is skipped; a skipped sequence was never generated, so it has no \
                     capacity to configure",
                    record.name
                )))
            }
            _ => Ok(()),
        },
    }
}

/// Validate the `[capacity]` section against the rest of `config` (FR-001, C-001,
/// C-003, C-004) — **without** a project root.
///
/// This is the half every *validate-then-save* path already calls, because
/// [`Config::validate`](crate::config::Config::validate) is what they validate with:
/// `tix wip unit --remove`, the schedule registry, the MCP write tools, planning. It
/// covers exactly what the configuration alone decides, and nothing that needs
/// `docs/cycles/`:
///
/// * the entry's handle (non-blank, unpadded, no `.`),
/// * a preserved key that would shadow a built-in field,
/// * exactly one scope, with a non-blank, unpadded reference,
/// * a team label that exists in `[teams.*]`,
/// * an assignee identity the model's own parser accepts,
/// * an enabled entry's ceiling (present, not negative) and unit (present, not blank,
///   **declared by a board**) — the check that keeps a change like "remove the unit a
///   ceiling names" from writing a file the next load refuses,
/// * one ceiling per scope, on the identity this gate can see.
///
/// A cycle reference is accepted here when `config.cycles` names it — that is the legacy
/// registry, and after a load it also holds every stored cycle's reference name — and is
/// otherwise **deferred**, not refused: whether a generated cycle answers to a reference
/// is a question for the records, which this gate has no root to read. Deferring is what
/// keeps the verdict provenance-independent: a valid file is never refused because the
/// caller happened to be a save path rather than the loader.
///
/// Nothing here reads a file, which is why a capacity-free section returning immediately
/// makes a repository that configures no capacity provably unaffected.
pub fn validate(capacity: &CapacityConfig, config: &Config) -> Result<()> {
    if capacity.is_empty() {
        return Ok(());
    }
    let mut claimed: HashMap<(CapacityScopeKind, String), String> = HashMap::new();
    for (id, entry) in capacity.iter() {
        let path = format!("capacity.{id}");
        validate_entry_id(id)?;
        check_extensions(&path, &entry.extensions)?;
        let (kind, reference) = validate_scope(&path, entry)?;
        let identity = scope_identity(&path, config, None, kind, &reference)?;
        if let Some(first) = claimed.insert((kind, identity.canonical.clone()), id.to_string()) {
            return Err(duplicate_scope(&path, kind, &reference, &identity, &first));
        }
        validate_ceiling(&path, entry, config)?;
    }
    Ok(())
}

/// The records' half of the section's validation: resolve every cycle reference, and
/// treat two spellings of one cycle as one ceiling (FR-001, C-003).
///
/// Called by the two gates that have a project root —
/// [`Config::load_with_warning`](crate::config::Config::load_with_warning) for every
/// hand-edited file and [`set_capacity`] for every programmatic change — because the
/// records are the only place a generated cycle's identity lives. It is the *extra* half,
/// not a replacement for [`validate`]: a caller runs both. A section with no cycle scope
/// returns without touching the filesystem.
///
/// The validity rule is deliberately provenance-independent: a reference is valid when it
/// resolves through the records **or** when it names a `[cycles.<name>]` entry in the
/// configuration, so a store-less project's legacy table is accepted whether or not the
/// caller read a cycle store (the crate's store-only
/// [`crate::cycle_schedule::registry::load_index`] answers `Unknown` for those names,
/// while [`schedule_index`] adds them). Only a reference that neither resolves nor names a
/// configured cycle is refused — and the message says so, rather than telling a user to
/// add a table their file already has.
pub fn validate_cycle_references(
    capacity: &CapacityConfig,
    config: &Config,
    root: &Path,
) -> Result<()> {
    if !capacity.iter().any(|(_, entry)| entry.cycle.is_some()) {
        return Ok(());
    }
    validate_cycle_identities(capacity, config, &schedule_index(config, root)?)
}

/// The cycle scopes of a section, resolved against an index.
fn validate_cycle_identities(
    capacity: &CapacityConfig,
    config: &Config,
    index: &ScheduleIndex,
) -> Result<()> {
    let mut claimed: HashMap<String, String> = HashMap::new();
    for (id, entry) in capacity.iter() {
        let Some((CapacityScopeKind::Cycle, reference)) = entry.scopes().next() else {
            continue;
        };
        let path = format!("capacity.{id}");
        let identity = scope_identity(
            &path,
            config,
            Some(index),
            CapacityScopeKind::Cycle,
            reference,
        )?;
        if let Some(first) = claimed.insert(identity.canonical.clone(), id.to_string()) {
            return Err(duplicate_scope(
                &path,
                CapacityScopeKind::Cycle,
                reference,
                &identity,
                &first,
            ));
        }
    }
    Ok(())
}

/// Set one capacity ceiling, through the closed-cycle boundary (T004, C-008).
///
/// This is the write path this package exposes, and the call site of
/// [`ensure_cycle_editable`]. A caller hands over the entry it wants and the edit it
/// believes it is making; the change happens only if
///
/// 1. the boundary allows it — an ordinary [`CapacityEdit::Configure`] aimed at a closed
///    cycle (whose ceiling is the historical record) or a skipped one is refused before
///    anything is written, and
/// 2. the whole section still validates with the entry in place — a scope that resolves
///    nowhere, a second ceiling for a scope another entry already holds, or a missing
///    unit leaves both `config` and `tix.toml` exactly as they were.
///
/// `root` is the project root: the cycle records that decide the boundary and the
/// resolution are read from `docs/cycles/` there (the legacy `[cycles.<name>]` tables when
/// there is no store), and the file is written atomically by [`Config::save`]. The change
/// is staged on a copy and committed only once both gates pass, so a refusal cannot leave
/// a half-applied section behind — the shape the other registries' commit boundaries use.
pub fn set_capacity(
    config: &mut Config,
    id: &str,
    entry: CapacityEntry,
    edit: &CapacityEdit<'_>,
    root: &Path,
) -> Result<()> {
    let records = cycle_records(config, root)?;
    let index = ScheduleIndex::build(config, &records);
    if let Some((CapacityScopeKind::Cycle, reference)) = entry.scopes().next()
        && let Some(record) = cycle_record(&index, &records, reference)
    {
        ensure_cycle_editable(record, edit)?;
    }
    let mut candidate = config.clone();
    candidate.capacity.insert(id, entry);
    // Both halves: what the configuration alone decides, and what the records decide.
    validate(&candidate.capacity, &candidate)?;
    validate_cycle_identities(&candidate.capacity, &candidate, &index)?;
    candidate.save(&root.join("tix.toml"))?;
    *config = candidate;
    Ok(())
}

/// The entry handle is a real key: non-blank, unpadded, and free of the one character
/// that would read as a nested table in a header or in a diagnostic path.
///
/// Unlike the stable-id registries this handle is not an identity — nothing points at a
/// capacity entry — so it is free-form otherwise: a user names it whatever reads best in
/// their file.
fn validate_entry_id(id: &str) -> Result<()> {
    if id.trim().is_empty() {
        return Err(TixError::Config(
            "`capacity` must not contain an entry with a blank id".into(),
        ));
    }
    if id.trim() != id {
        return Err(TixError::Config(format!(
            "`capacity` entry id `{id}` has leading or trailing whitespace"
        )));
    }
    if id.contains('.') {
        return Err(TixError::Config(format!(
            "`capacity` entry id `{id}` contains `.`; a dot reads as a nested table in \
             `[capacity.<id>]` and in a diagnostic path"
        )));
    }
    Ok(())
}

/// Refuse a preserved key that would shadow a built-in field.
fn check_extensions(path: &str, extensions: &CapacityExtensions) -> Result<()> {
    for key in extensions.keys() {
        if CAPACITY_ENTRY_KNOWN_FIELDS.contains(&key) {
            return Err(TixError::Config(format!(
                "`{path}.{key}` collides with a built-in field; rename the extension key"
            )));
        }
    }
    Ok(())
}

/// Exactly one of `cycle`, `team`, `assignee`: the entry's scope.
fn validate_scope(path: &str, entry: &CapacityEntry) -> Result<(CapacityScopeKind, String)> {
    let named: Vec<(CapacityScopeKind, &str)> = entry.scopes().collect();
    match named.len() {
        0 => Err(TixError::Config(format!(
            "`{path}.scope` must name exactly one scope: set `cycle`, `team`, or `assignee`"
        ))),
        1 => {
            let (kind, reference) = named[0];
            if reference.trim().is_empty() {
                return Err(TixError::Config(format!(
                    "`{path}.{kind}` must not be blank"
                )));
            }
            if reference.trim() != reference {
                return Err(TixError::Config(format!(
                    "`{path}.{kind}` (`{reference}`) has leading or trailing whitespace"
                )));
            }
            Ok((kind, reference.to_string()))
        }
        _ => {
            let listed = named
                .iter()
                .map(|(kind, _)| format!("`{kind}`"))
                .collect::<Vec<_>>()
                .join(" and ");
            Err(TixError::Config(format!(
                "`{path}.scope` names more than one scope ({listed}); an entry targets exactly one \
                 cycle, team, or assignee"
            )))
        }
    }
}

/// The identity a scope reference **resolves to**, for the one-ceiling-per-scope rule.
///
/// `canonical` is what two entries are compared on: a cycle's stable id or resolved name,
/// an assignee's canonical handle, a team label. `label` is the human spelling to print,
/// which differs from the literal a user wrote whenever two spellings resolve to one
/// identity (`@ada` and `ada`, a generated cycle's name and its id) — the case the
/// duplicate diagnostic has to explain.
struct ScopeIdentity {
    canonical: String,
    label: String,
}

/// The message every repeated-scope refusal uses.
fn duplicate_scope(
    path: &str,
    kind: CapacityScopeKind,
    reference: &str,
    identity: &ScopeIdentity,
    first: &str,
) -> TixError {
    let note = if identity.label == reference {
        String::new()
    } else {
        format!(" (`{reference}` resolves to `{}`)", identity.label)
    };
    TixError::Config(format!(
        "`{path}.{kind}` (`{reference}`) repeats the scope \
         `capacity.{first}.{kind}` already configures{note}; one ceiling per scope"
    ))
}

/// Resolve a scope reference to the identity the one-ceiling rule compares.
///
/// `index` is `Some` at the records' gate and `None` where only the configuration is
/// available. The cycle arm is the one that differs, and that difference is the whole
/// point of the split: with an index, a reference that resolves neither through the
/// records nor through `config.cycles` is refused by name; without one, a reference the
/// configuration does not name is accepted under a reference-shaped identity and left for
/// the records' gate to judge.
fn scope_identity(
    path: &str,
    config: &Config,
    index: Option<&ScheduleIndex>,
    kind: CapacityScopeKind,
    reference: &str,
) -> Result<ScopeIdentity> {
    match kind {
        CapacityScopeKind::Cycle => {
            if let Some(index) = index {
                return Ok(match resolve_cycle(index, reference) {
                    CycleReference::Generated { id, .. } => ScopeIdentity {
                        canonical: format!("cycle-id:{id}"),
                        label: id.to_string(),
                    },
                    CycleReference::Legacy { name } => ScopeIdentity {
                        canonical: format!("cycle-name:{name}"),
                        label: name,
                    },
                    // Not in the records: the configuration's own cycle registry is the
                    // second half of the validity rule, so a legacy table — or a stored
                    // cycle's name the loader copied in — is still a valid reference.
                    CycleReference::Unknown { .. } if config.cycles.contains_key(reference) => {
                        ScopeIdentity {
                            canonical: format!("cycle-name:{reference}"),
                            label: reference.to_string(),
                        }
                    }
                    CycleReference::Unknown { .. } => {
                        return Err(TixError::Config(format!(
                            "`{path}.cycle` (`{reference}`) does not name a cycle; add \
                             `[cycles.\"{reference}\"]`, or name a generated cycle's \
                             `<schedule-id>:<sequence>` id or its `cycles` value"
                        )));
                    }
                });
            }
            if config.cycles.contains_key(reference) {
                return Ok(ScopeIdentity {
                    canonical: format!("cycle-name:{reference}"),
                    label: reference.to_string(),
                });
            }
            // Only the records can say whether a generated cycle answers to this, and this
            // gate has no root: defer rather than refuse a reference the loader accepts.
            Ok(ScopeIdentity {
                canonical: format!("cycle-ref:{reference}"),
                label: reference.to_string(),
            })
        }
        CapacityScopeKind::Team => {
            if !config.teams.contains_key(reference) {
                return Err(TixError::Config(format!(
                    "`{path}.team` (`{reference}`) is not a configured team; add \
                     `[teams.{reference}]`"
                )));
            }
            Ok(ScopeIdentity {
                canonical: format!("team:{reference}"),
                label: reference.to_string(),
            })
        }
        CapacityScopeKind::Assignee => {
            // The model's own parser folds the spellings: `ada` and `@ada` are one
            // identity, so they are one scope here too.
            let Some(canonical) = crate::assignee::parse_assignee(reference) else {
                return Err(TixError::Config(format!(
                    "`{path}.assignee` (`{reference}`) is not an assignee identity; use a handle \
                     (`ada`, `@ada`) or `Ada Lovelace <ada@example.com>`"
                )));
            };
            Ok(ScopeIdentity {
                canonical: format!("assignee:{canonical}"),
                label: canonical,
            })
        }
    }
}

/// An enabled entry needs a non-negative ceiling in a declared unit; a disabled one may
/// keep the scope alone.
fn validate_ceiling(path: &str, entry: &CapacityEntry, config: &Config) -> Result<()> {
    match entry.capacity {
        Some(value) if value < 0 => {
            return Err(TixError::Config(format!(
                "`{path}.capacity` ({value}) must not be negative"
            )));
        }
        None if entry.enabled => {
            return Err(TixError::Config(format!(
                "`{path}.capacity` must be set for an enabled entry; set `enabled = false` to keep \
                 the scope without a ceiling"
            )));
        }
        _ => {}
    }
    match entry.unit.as_deref() {
        Some(unit) if unit.trim().is_empty() => {
            Err(TixError::Config(format!("`{path}.unit` must not be blank")))
        }
        Some(unit) if unit.trim() != unit => Err(TixError::Config(format!(
            "`{path}.unit` (`{unit}`) has leading or trailing whitespace"
        ))),
        Some(unit) if !declared_unit(config, unit) => Err(TixError::Config(format!(
            "`{path}.unit` (`{unit}`) is not a declared estimate unit on board `{board}`, which \
             is the board capacity calculations run under; declare `{unit}` under \
             `[kanban.{board}.wip.units]`",
            board = crate::workflow::active_board_name(config)
        ))),
        Some(_) => Ok(()),
        None if entry.enabled => Err(TixError::Config(format!(
            "`{path}.unit` must name the estimate unit `capacity` counts in; a capacity with no \
             unit cannot be calculated"
        ))),
        None => Ok(()),
    }
}

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

    fn closed_record() -> CycleRecord {
        CycleRecord {
            name: "Platform sprint".into(),
            start_date: Some("2026-01-05".into()),
            due_date: Some("2026-01-19".into()),
            schedule_id: Some("cs-1".into()),
            sequence: Some(1),
            state: Some("closed".into()),
            ..CycleRecord::default()
        }
    }

    #[test]
    fn a_closed_cycle_is_refused_a_configuration_edit_but_not_a_reopen() {
        let error = ensure_cycle_editable(&closed_record(), &CapacityEdit::Configure)
            .expect_err("a closed cycle is historical evidence");
        let message = error.to_string();
        assert!(message.contains("closed"), "{message}");
        assert!(message.contains("cs-1:000001"), "{message}");

        assert!(
            ensure_cycle_editable(&closed_record(), &CapacityEdit::Reopen { reason: "  " })
                .is_err(),
            "a reopen without a reason is not auditable"
        );
        ensure_cycle_editable(
            &closed_record(),
            &CapacityEdit::Reopen {
                reason: "recounting after an import",
            },
        )
        .expect("an explicit, reasoned reopen is the way through");
    }

    #[test]
    fn a_hand_written_cycle_has_no_state_to_refuse() {
        let record = CycleRecord {
            name: "Cycle 1".into(),
            ..CycleRecord::default()
        };
        ensure_cycle_editable(&record, &CapacityEdit::Configure)
            .expect("a hand-written cycle has no lifecycle state");
    }

    #[test]
    fn an_active_cycle_is_editable_and_a_skipped_one_is_not() {
        let active = CycleRecord {
            state: Some("active".into()),
            ..closed_record()
        };
        ensure_cycle_editable(&active, &CapacityEdit::Configure).expect("active is current work");

        let skipped = CycleRecord {
            state: Some("skipped".into()),
            ..closed_record()
        };
        let message = ensure_cycle_editable(&skipped, &CapacityEdit::Configure)
            .expect_err("a skipped sequence was never generated")
            .to_string();
        assert!(message.contains("skipped"), "{message}");
    }

    #[test]
    fn a_partial_generated_identity_is_a_finding_at_the_boundary() {
        let record = CycleRecord {
            state: None,
            ..closed_record()
        };
        assert!(
            ensure_cycle_editable(&record, &CapacityEdit::Configure).is_err(),
            "half an identity must not read as an open cycle"
        );
    }

    #[test]
    fn the_scope_accessors_report_none_when_the_entry_is_ambiguous() {
        let mut entry = CapacityEntry::default();
        assert_eq!(entry.scope_kind(), None);
        assert_eq!(entry.scope_id(), None);

        entry.cycle = Some("Cycle 1".into());
        assert_eq!(entry.scope_kind(), Some(CapacityScopeKind::Cycle));
        assert_eq!(entry.scope_id(), Some("Cycle 1"));

        entry.team = Some("Platform".into());
        assert_eq!(entry.scope_kind(), None, "two scopes are not a scope");
        assert_eq!(entry.scope_id(), None);
    }

    #[test]
    fn a_disabled_entry_without_numbers_is_not_effective() {
        let mut entry = CapacityEntry {
            team: Some("Platform".into()),
            ..CapacityEntry::default()
        };
        assert!(!entry.effective(), "no ceiling is configured yet");
        entry.capacity = Some(0);
        assert!(!entry.effective(), "no unit means it cannot be calculated");
        entry.unit = Some("d".into());
        assert!(entry.effective());
        entry.enabled = false;
        assert!(!entry.effective(), "a disabled entry enforces nothing");
    }
}