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
//! One-pass WIP aggregates: what each column holds, where that stands against its
//! limit, and why a total is unknown when it is (mission
//! `configurable-wip-limits-01M3C6WX`, WP02).
//!
//! # One snapshot, derived once
//!
//! Every surface that wants to show or decide a limit asks *this* module, and the
//! module asks the issue slice once (T007). Counting per column by scanning the
//! issue set again would be `columns × issues` — and, worse, two surfaces counting
//! separately is how `tix status` and the board start disagreeing about how full a
//! column is. The snapshot is derived state: it is built from issues a caller
//! already holds, it reads no file, and it writes nothing.
//!
//! # Never a wrong number
//!
//! An issue whose `estimate` cannot be counted (not `<number><unit>`,
//! `malformed_estimate`; a unit the board does not declare, `missing_conversion`;
//! a conversion that does not divide exactly, `ambiguous_conversion`) makes the
//! column's estimate total **unknown**, not zero and not the sum of the others
//! (C-003). The diagnostic names the issue, so the reader can fix it; the state
//! stays [`LimitState::Unknown`], which is never read as "within the limit".

use crate::config::BoardConfiguration;
use crate::model::Issue;

use super::config::{ColumnLimit, Estimate, LimitPolicy, WipDiagnostic};

/// Where a column stands against its limit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LimitState {
    /// Within every configured ceiling.
    Within,
    /// Over at least one configured ceiling.
    Over,
    /// At least one aggregate could not be computed, so nothing is claimed. This
    /// is never "within": an uncountable estimate must not pass a limit silently.
    Unknown,
}

impl LimitState {
    /// The stable spelling every surface prints.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Within => "within",
            Self::Over => "over",
            Self::Unknown => "unknown",
        }
    }

    /// Whether anything is actually wrong: `Over`, or a total nobody can trust.
    pub const fn is_violation(self) -> bool {
        matches!(self, Self::Over)
    }

    /// The worse of two states, for a column that has two ceilings.
    pub const fn worse(self, other: Self) -> Self {
        match (self, other) {
            (Self::Over, _) | (_, Self::Over) => Self::Over,
            (Self::Unknown, _) | (_, Self::Unknown) => Self::Unknown,
            _ => Self::Within,
        }
    }
}

/// One column's usage, and the limit it is measured against.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ColumnUsage {
    /// The column's name, as the board declares it.
    pub column: String,
    /// How many issues the column holds.
    pub items: u32,
    /// The estimate total in the limit's unit.
    ///
    /// `None` when the board states no estimate ceiling for the column (there is no
    /// unit to count in) **or** when at least one issue's estimate could not be
    /// counted — the snapshot's diagnostics say which issue, and
    /// [`ColumnUsage::state`] is then [`LimitState::Unknown`].
    pub estimate: Option<u32>,
    /// The enabled limit in force for the column, if any.
    pub limit: Option<ColumnLimit>,
}

impl ColumnUsage {
    /// The item ceiling, when the column has one.
    pub fn max_items(&self) -> Option<u32> {
        self.limit.as_ref().and_then(|limit| limit.max_items)
    }

    /// The estimate ceiling, when the column has one.
    pub fn max_estimate(&self) -> Option<u32> {
        self.limit.as_ref().and_then(|limit| limit.max_estimate)
    }

    /// The unit the estimate ceiling counts in, when there is one.
    pub fn unit(&self) -> Option<&str> {
        self.limit.as_ref().and_then(|limit| limit.unit.as_deref())
    }

    /// The policy the column enforces, when it enforces one.
    pub fn policy(&self) -> Option<LimitPolicy> {
        self.limit.as_ref().and_then(ColumnLimit::resolved_policy)
    }

    /// Where the column stands on its own item ceiling.
    pub fn item_state(&self) -> LimitState {
        match self.max_items() {
            Some(max) => match self.items.cmp(&max) {
                std::cmp::Ordering::Greater => LimitState::Over,
                _ => LimitState::Within,
            },
            None => LimitState::Within,
        }
    }

    /// Where the column stands on its own estimate ceiling.
    pub fn estimate_state(&self) -> LimitState {
        match (self.max_estimate(), self.estimate) {
            // A ceiling nobody can measure is `Unknown`, never `Within`.
            (Some(_), None) => LimitState::Unknown,
            (Some(max), Some(total)) => match total.cmp(&max) {
                std::cmp::Ordering::Greater => LimitState::Over,
                _ => LimitState::Within,
            },
            (None, _) => LimitState::Within,
        }
    }

    /// Where the column stands overall: the worse of its two ceilings.
    pub fn state(&self) -> LimitState {
        self.item_state().worse(self.estimate_state())
    }

    /// The state the column **would** be in after `add_items` more cards and
    /// `add_estimate` more of its unit (T009).
    ///
    /// This is the before/after shape a move is judged with: the caller passes what
    /// the move would add, and reads the answer without touching a file. A move that
    /// adds nothing reproduces [`state`](ColumnUsage::state) exactly.
    pub fn prospective(&self, add_items: u32, add_estimate: u32) -> LimitState {
        let items = self.items.saturating_add(add_items);
        let item_state = match self.max_items() {
            Some(max) if items > max => LimitState::Over,
            _ => LimitState::Within,
        };
        let estimate_state = match (self.max_estimate(), self.estimate) {
            (Some(_), None) => LimitState::Unknown,
            (Some(max), Some(total)) => match total.saturating_add(add_estimate).cmp(&max) {
                std::cmp::Ordering::Greater => LimitState::Over,
                _ => LimitState::Within,
            },
            (None, _) => LimitState::Within,
        };
        item_state.worse(estimate_state)
    }

    /// The usage as one short cell: `4/5`, or `4` when the column has no item
    /// ceiling, with the estimate ceiling beside it in its unit (`12/20d`) when the
    /// board states one. A trailing `!` means something is over, or unknown.
    ///
    /// It is deliberately the *usage*, not a verdict: the verdict is the policy
    /// layer's, and a cell that said "block" would be a claim this module is not
    /// entitled to make.
    pub fn cell(&self) -> String {
        let mut cell = match self.max_items() {
            Some(max) => format!("{}/{max}", self.items),
            None => self.items.to_string(),
        };
        if let Some(max) = self.max_estimate() {
            let unit = self.unit().unwrap_or("");
            match self.estimate {
                Some(total) => cell.push_str(&format!(" {total}/{max}{unit}")),
                // No number to print: the diagnostics name the issue that made this
                // unmeasurable, and a `?` here is the honest cell.
                None => cell.push_str(&format!(" ?/{max}{unit}")),
            }
        }
        if !matches!(self.state(), LimitState::Within) {
            cell.push('!');
        }
        cell
    }
}

/// The board's WIP state: one derived snapshot of every configured column (T008).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WipSnapshot {
    columns: Vec<ColumnUsage>,
    diagnostics: Vec<WipDiagnostic>,
    configured: bool,
}

impl WipSnapshot {
    /// Derive the snapshot from `issues`, in the board's column order.
    ///
    /// **One pass over the issues** and no I/O: the columns are indexed once, and
    /// every issue is examined once and added to its own column's slot. An issue
    /// whose `status` is not a configured column is not counted anywhere — the board
    /// does not render it, so a limit on some other column is not its business
    /// (`tix status`'s own `mismatch` reporting is where such an issue is surfaced).
    pub fn build(board: &BoardConfiguration, issues: &[Issue]) -> Self {
        let mut columns: Vec<ColumnUsage> = board
            .columns
            .iter()
            .map(|column| ColumnUsage {
                column: column.clone(),
                items: 0,
                estimate: None,
                limit: board.wip.effective_limit(column).cloned(),
            })
            .collect();
        // A column that has an estimate ceiling starts its total at zero and grows
        // it; a column without one keeps `None`, because there is no unit to count
        // in and a raw sum would be a number with no meaning.
        let mut totals: Vec<Option<u32>> = columns
            .iter()
            .map(|usage| usage.max_estimate().map(|_| 0))
            .collect();
        let mut diagnostics: Vec<WipDiagnostic> = Vec::new();
        let index: std::collections::HashMap<&str, usize> = board
            .columns
            .iter()
            .enumerate()
            .map(|(slot, column)| (column.as_str(), slot))
            .collect();

        for issue in issues {
            let Some(&slot) = index.get(issue.status.display()) else {
                continue;
            };
            columns[slot].items = columns[slot].items.saturating_add(1);
            let Some(total) = totals[slot].as_mut() else {
                continue;
            };
            let Some(raw) = issue
                .estimate
                .as_deref()
                .map(str::trim)
                .filter(|raw| !raw.is_empty())
            else {
                // No estimate is zero estimate: the card is work, and it states no
                // size. That is not an error and produces no diagnostic.
                continue;
            };
            let unit = columns[slot].unit().unwrap_or_default().to_string();
            match Estimate::parse_terms(raw)
                .and_then(|terms| board.wip.convert_terms(&terms, &unit))
            {
                Ok(value) => *total = total.saturating_add(value),
                Err(error) => {
                    let diagnostic = error.first();
                    diagnostics.push(
                        WipDiagnostic::new(
                            diagnostic.kind,
                            format!(
                                "issue #{} in `{}` states `{raw}`, which this board cannot count \
                                 in `{unit}`: {}",
                                issue.number, columns[slot].column, diagnostic.message
                            ),
                        )
                        .because(
                            "the column's estimate total is unknown until this is fixed, and an \
                             unknown total never passes a limit (C-003)",
                        ),
                    );
                    // The total is now untrustworthy: `None` is the only honest value.
                    totals[slot] = None;
                    columns[slot].estimate = None;
                }
            }
        }

        for (slot, total) in totals.into_iter().enumerate() {
            columns[slot].estimate = total;
        }
        let configured = columns.iter().any(|usage| usage.limit.is_some());
        Self {
            columns,
            diagnostics,
            configured,
        }
    }

    /// Every configured column, in board order.
    pub fn columns(&self) -> &[ColumnUsage] {
        &self.columns
    }

    /// One column's usage, by name.
    pub fn column(&self, column: &str) -> Option<&ColumnUsage> {
        self.columns.iter().find(|usage| usage.column == column)
    }

    /// The findings that made a total unknown.
    pub fn diagnostics(&self) -> &[WipDiagnostic] {
        &self.diagnostics
    }

    /// Whether any column enforces a limit at all.
    ///
    /// A surface that shows limits should ask this first: a board with no limits must
    /// render exactly what it rendered before this mission, byte for byte.
    pub fn is_configured(&self) -> bool {
        self.configured
    }

    /// Where `column` stands, or [`LimitState::Within`] for a column with no limit.
    pub fn state(&self, column: &str) -> LimitState {
        self.column(column)
            .map_or(LimitState::Within, ColumnUsage::state)
    }

    /// Every column that is over a ceiling, in board order.
    pub fn violations(&self) -> impl Iterator<Item = &ColumnUsage> {
        self.columns
            .iter()
            .filter(|usage| usage.state().is_violation())
    }
}

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

    use crate::config::BoardConfiguration;
    use crate::wip::WipConfig;
    use crate::wip::config::WipDiagnosticKind;

    fn board(limits: &[(&str, ColumnLimit)]) -> BoardConfiguration {
        BoardConfiguration {
            columns: ["todo", "in progress", "in review", "done"]
                .into_iter()
                .map(String::from)
                .collect(),
            wip: WipConfig {
                units: [("d", 1), ("w", 5)]
                    .into_iter()
                    .map(|(name, factor)| (name.to_string(), factor))
                    .collect::<IndexMap<_, _>>(),
                limits: limits
                    .iter()
                    .map(|(column, limit)| ((*column).to_string(), limit.clone()))
                    .collect(),
            },
            ..BoardConfiguration::default()
        }
    }

    /// An issue through the **real** parser: the `estimate:` key is frontmatter, so
    /// the fixture is the file format rather than a hand-built struct.
    fn issue(number: u32, status: &str, estimate: Option<&str>) -> Issue {
        let estimate = estimate
            .map(|value| format!("estimate: \"{value}\"\n"))
            .unwrap_or_default();
        let contents = format!(
            "---\nnumber: {number}\ntitle: \"Issue {number}\"\nstatus: \"{status}\"\n\
             created: \"2026-01-01\"\nupdated: \"2026-01-01\"\n{estimate}---\n\nBody.\n"
        );
        let mut issue = Issue::parse(&contents).expect("the fixture parses");
        issue.filename = format!("issue-{number}.md");
        issue
    }

    #[test]
    fn wip_aggregate_counts_every_column_in_one_pass() {
        let board = board(&[("in progress", ColumnLimit::items(2, LimitPolicy::Warn))]);
        let issues = vec![
            issue(1, "todo", None),
            issue(2, "in progress", None),
            issue(3, "in progress", None),
            issue(4, "done", None),
            issue(5, "shipped", None), // not a configured column
        ];
        let snapshot = WipSnapshot::build(&board, &issues);
        assert_eq!(
            snapshot
                .columns()
                .iter()
                .map(|usage| (usage.column.as_str(), usage.items))
                .collect::<Vec<_>>(),
            vec![
                ("todo", 1),
                ("in progress", 2),
                ("in review", 0),
                ("done", 1)
            ],
            "every configured column appears, in board order"
        );
        assert_eq!(
            snapshot.column("in progress").expect("usage").state(),
            LimitState::Within
        );
        assert_eq!(
            snapshot.state("todo"),
            LimitState::Within,
            "no limit is within"
        );
        assert!(snapshot.is_configured());
    }

    #[test]
    fn wip_aggregate_state_is_over_only_past_the_ceiling() {
        let board = board(&[("in progress", ColumnLimit::items(2, LimitPolicy::Block))]);
        let at_limit = WipSnapshot::build(
            &board,
            &[issue(1, "in progress", None), issue(2, "in progress", None)],
        );
        let usage = at_limit.column("in progress").expect("usage");
        assert_eq!(
            usage.state(),
            LimitState::Within,
            "exactly at the limit is within"
        );
        assert_eq!(usage.prospective(1, 0), LimitState::Over);
        assert_eq!(
            usage.prospective(0, 0),
            LimitState::Within,
            "a no-op move is within"
        );

        let over = WipSnapshot::build(
            &board,
            &[
                issue(1, "in progress", None),
                issue(2, "in progress", None),
                issue(3, "in progress", None),
            ],
        );
        assert_eq!(
            over.column("in progress").expect("usage").state(),
            LimitState::Over
        );
        assert_eq!(over.violations().count(), 1);
        assert_eq!(over.column("in progress").expect("usage").cell(), "3/2!");
    }

    #[test]
    fn wip_aggregate_totals_estimates_in_the_limit_unit() {
        let board = board(&[(
            "in progress",
            ColumnLimit::estimate(10, "d", LimitPolicy::Warn),
        )]);
        let issues = vec![
            issue(1, "in progress", Some("3")),
            issue(2, "in progress", Some("1w")),
            issue(3, "in progress", None),
            issue(4, "in progress", Some("  ")),
            issue(5, "todo", Some("9w")),
        ];
        let snapshot = WipSnapshot::build(&board, &issues);
        let usage = snapshot.column("in progress").expect("usage");
        assert_eq!(usage.items, 4, "an unestimated card is still work");
        assert_eq!(
            usage.estimate,
            Some(8),
            "3 + 5d; the empty ones add nothing"
        );
        assert_eq!(usage.state(), LimitState::Within);
        assert_eq!(usage.cell(), "4 8/10d");
        assert_eq!(
            snapshot.column("todo").expect("usage").estimate,
            None,
            "no estimate ceiling means no unit, so no total"
        );
        assert_eq!(snapshot.diagnostics(), []);
    }

    #[test]
    fn wip_aggregate_unknown_total_is_never_within() {
        let board = board(&[(
            "in progress",
            ColumnLimit::estimate(10, "d", LimitPolicy::Block),
        )]);
        for (raw, kind) in [
            ("three", WipDiagnosticKind::MalformedEstimate),
            ("3q", WipDiagnosticKind::MissingConversion),
        ] {
            let snapshot = WipSnapshot::build(
                &board,
                &[
                    issue(1, "in progress", Some("2")),
                    issue(2, "in progress", Some(raw)),
                ],
            );
            let usage = snapshot.column("in progress").expect("usage");
            assert_eq!(usage.estimate, None, "`{raw}`: no total is claimed");
            assert_eq!(usage.estimate_state(), LimitState::Unknown, "`{raw}`");
            assert_eq!(usage.prospective(0, 0), LimitState::Unknown, "`{raw}`");
            assert_eq!(
                usage.cell(),
                "2 ?/10d!",
                "the cell says unknown with a `!`, never a number"
            );
            let diagnostic = &snapshot.diagnostics()[0];
            assert_eq!(diagnostic.kind, kind, "`{raw}`");
            assert!(
                diagnostic.message.contains("issue #2") && diagnostic.message.contains(raw),
                "{}",
                diagnostic.message
            );
        }
    }

    #[test]
    fn wip_aggregate_fractional_conversion_makes_the_total_unknown() {
        let mut board = board(&[(
            "in progress",
            ColumnLimit::estimate(10, "w", LimitPolicy::Warn),
        )]);
        board.wip.units.insert("h".to_string(), 1);
        board.wip.units.insert("d".to_string(), 8);
        let snapshot = WipSnapshot::build(&board, &[issue(1, "in progress", Some("3d"))]);
        let usage = snapshot.column("in progress").expect("usage");
        assert_eq!(usage.estimate_state(), LimitState::Unknown);
        assert_eq!(
            snapshot.diagnostics()[0].kind,
            WipDiagnosticKind::AmbiguousConversion
        );
    }

    #[test]
    fn wip_aggregate_without_limits_is_inert() {
        let board = BoardConfiguration::default();
        let issues = vec![issue(1, "todo", Some("3d")), issue(2, "todo", Some("nope"))];
        let snapshot = WipSnapshot::build(&board, &issues);
        assert!(!snapshot.is_configured(), "nothing is configured");
        assert!(snapshot.violations().next().is_none());
        assert_eq!(snapshot.column("todo").expect("usage").items, 2);
        assert!(
            snapshot.diagnostics().is_empty(),
            "with no limit there is nothing to measure, so nothing is broken"
        );
    }
}