tix-tracker 0.11.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
//! The cycle/team/assignee scope indexes and the one issue snapshot every capacity
//! calculation reads (mission `cycle-capacity-planning-01M3C85C`, WP02).
//!
//! # One pass, one snapshot, one reading of every estimate
//!
//! [`IssueSnapshot::build`] walks the issues **once**. In that single walk it indexes
//! cycle membership, team membership, assignee membership, the shared #183 completion
//! answer, and each issue's estimate — parsed once and converted once per unit the
//! conversion table is resolved for. Every later question (`committed`, `completed`,
//! `remaining`, utilization, a per-scope detail view) is then a lookup, not a scan:
//! re-reading the store or re-parsing an estimate per scope is what NFR-001 exists to
//! forbid, and it is also how two surfaces start disagreeing about one repository.
//!
//! # Cycle membership resolves through the crate's one adapter
//!
//! An issue's `cycles` value is a **name**, and a name may be a hand-written
//! `[cycles.<name>]` cycle or one an issue-181 schedule generated. Both, and a
//! generated cycle's stable `<schedule-id>:<sequence>` id, resolve through
//! [`super::config::resolve_cycle`] — the crate's single cycle-reference resolver — so
//! a capacity scope naming any of the three selects exactly the same issues. The
//! snapshot keys membership on the **identity** that resolver answers with (a generated
//! cycle's id, a legacy cycle's name) and never on the spelling, so two spellings of
//! one cycle are one scope (data-model §2).
//!
//! # Team membership
//!
//! The only link the model offers between an issue and a team is the assignee: a team
//! is `[teams.<label>]` and its members are assignee identities. An issue therefore
//! belongs to a team when its `assignee`, canonicalised through
//! [`crate::assignee::parse_assignee`] (so `ada` and `@ada` are one identity, exactly
//! as [`super::config::validate`] folds them), is one of that team's canonical
//! members. An issue may belong to several teams; it contributes to each once.
//!
//! # References that resolve to nothing are diagnostics, not guesses
//!
//! An issue naming a cycle nothing resolves to is reported
//! ([`ScopeDiagnosticKind::UnknownScope`]) and contributes to **no** cycle scope: a
//! capacity entry can only be validated against a cycle that exists, so an unresolved
//! name could never be selected, and inventing a membership for it would be the silent
//! guess C-003 refuses. Two spellings of one identity inside one issue are reported too
//! ([`ScopeDiagnosticKind::AmbiguousScope`]) and deduplicated — the cycle counts once,
//! never twice.

use std::collections::btree_map::Entry;
use std::collections::{BTreeMap, BTreeSet};

use crate::assignee::parse_assignee;
use crate::config::Config;
use crate::cycle_schedule::identity::{CycleReference, ScheduleIndex};
use crate::error::render_diagnostics;
use crate::model::Issue;
use crate::wip::WipConfig;
use crate::workflow;

use super::config::{CapacityScopeKind, resolve_cycle};
use super::estimate::EstimateValue;

/// What a scope-index finding is about (data-model §5's vocabulary).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ScopeDiagnosticKind {
    /// An issue names a cycle that does not resolve to a record.
    UnknownScope,
    /// Two spellings in one issue resolve to one scope.
    AmbiguousScope,
}

impl ScopeDiagnosticKind {
    /// The stable spelling every surface prints.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::UnknownScope => "unknown_scope",
            Self::AmbiguousScope => "ambiguous_scope",
        }
    }
}

/// One scope-index finding: what it is, which scope, and which issue raised it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScopeDiagnostic {
    /// What is wrong.
    pub kind: ScopeDiagnosticKind,
    /// Which dimension the reference belongs to.
    pub scope_kind: CapacityScopeKind,
    /// The reference the issue wrote.
    pub reference: String,
    /// The issue that wrote it, when the finding came from an issue.
    pub issue: Option<u32>,
    /// One sentence saying what happened.
    pub message: String,
    /// A second sentence, when the first is not enough.
    pub because: Option<String>,
}

impl ScopeDiagnostic {
    /// A finding with its message.
    #[must_use]
    pub fn new(
        kind: ScopeDiagnosticKind,
        scope_kind: CapacityScopeKind,
        reference: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            kind,
            scope_kind,
            reference: reference.into(),
            issue: None,
            message: message.into(),
            because: None,
        }
    }

    /// Attach the issue the finding came from.
    #[must_use]
    pub fn for_issue(mut self, number: u32) -> Self {
        self.issue = Some(number);
        self
    }

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

    /// Render through the crate's one diagnostic renderer.
    #[must_use]
    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));
        }
        render_diagnostics("E-tix-capacity", pairs)
    }
}

/// The one indexed issue snapshot capacity calculations read (T011).
///
/// Built by [`IssueSnapshot::build`] and immutable afterwards: every lookup is a map
/// read, so a calculation never touches a file, re-parses an estimate, or walks the
/// issue list again — there is no seam a lookup could parse through, and no interior
/// mutability to cache one in. The tally it exposes
/// ([`issue_visits`](Self::issue_visits),
/// [`estimates_parsed`](Self::estimates_parsed),
/// [`conversions_resolved`](Self::conversions_resolved)) is the pass's own record of the
/// parse and conversion work it performed, so a test can assert how much work the build
/// did instead of only that it was fast. What those counters do **not** observe is stated
/// on each of them.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct IssueSnapshot {
    /// Every issue number, in the order the pass saw them.
    numbers: Vec<u32>,
    /// A cycle identity -> its member issues, in issue order.
    by_cycle: BTreeMap<String, Vec<u32>>,
    /// A cycle identity -> the name it answers to, for a surface that lists scopes.
    cycle_names: BTreeMap<String, String>,
    /// A team label -> its member issues, in issue order.
    by_team: BTreeMap<String, Vec<u32>>,
    /// A canonical assignee identity -> its member issues, in issue order.
    by_assignee: BTreeMap<String, Vec<u32>>,
    /// An issue -> its estimate as stated, with the parse's diagnostics only.
    stated: BTreeMap<u32, EstimateValue>,
    /// An issue -> its estimate per target unit, conversion already applied.
    converted: BTreeMap<u32, BTreeMap<String, EstimateValue>>,
    /// The units every estimate was converted into, in a stable order.
    targets: Vec<String>,
    /// The issues #183's category service calls completed.
    completed: BTreeSet<u32>,
    /// The issues that belong to no cycle, team, or assignee scope.
    unscoped: Vec<u32>,
    /// The membership findings the pass produced, in the order it found them.
    diagnostics: Vec<ScopeDiagnostic>,
    /// How many issue records the pass's estimate seam walked.
    visits: usize,
    /// How many estimates that seam parsed.
    parses: usize,
    /// How many conversions that seam attempted: a readable estimate, per target unit.
    conversions: usize,
}

impl IssueSnapshot {
    /// Index `issues` in **one pass** against the repository's scopes and units.
    ///
    /// `index` is the caller's [`ScheduleIndex`], built from the cycle records
    /// (`crate::capacity::schedule_index`, or [`crate::cycle_schedule::registry::load_index`]
    /// — the same index either way). The units an estimate is converted into are the
    /// board's declared units plus every unit a configured capacity entry names, read
    /// from the config here: the conversion table is resolved **once**, at build time,
    /// so no calculation repeats it (R10).
    ///
    /// Conversions use the **default board**'s registry (`config.default_config()`,
    /// the board the CLI and other single-config surfaces run under, and the same board
    /// [`crate::workflow::resolution`] is built for here). A capacity scope names a
    /// cycle, a team, or an assignee and never a board, so there is no other board the
    /// arithmetic could run under; a unit *that* board does not declare is a
    /// `missing_conversion`/`unknown_unit` diagnostic per issue, never a guess.
    ///
    /// Completion is [`crate::workflow::is_completed`]'s answer (C-002): the snapshot
    /// records what the one status-category service decides and never re-derives it.
    #[must_use]
    #[allow(clippy::too_many_lines)]
    pub fn build(config: &Config, index: &ScheduleIndex, issues: &[Issue]) -> Self {
        let board = config.default_config();
        let resolution = workflow::resolution(config, board, "default");

        let mut targets: BTreeSet<String> = board.wip.units.keys().cloned().collect();
        for (_, entry) in config.capacity.iter() {
            if let Some(unit) = entry
                .unit
                .as_deref()
                .map(str::trim)
                .filter(|unit| !unit.is_empty())
            {
                targets.insert(unit.to_string());
            }
        }
        let targets: Vec<String> = targets.into_iter().collect();

        // Which teams a canonical assignee identity belongs to. Read from the config
        // once, so the issue pass stays a single pass.
        let mut teams_of: BTreeMap<String, Vec<String>> = BTreeMap::new();
        for (label, team) in &config.teams {
            for member in &team.members {
                let Some(handle) = parse_assignee(member) else {
                    continue;
                };
                let teams = teams_of.entry(handle).or_default();
                if !teams.contains(label) {
                    teams.push(label.clone());
                }
            }
        }

        let mut snapshot = Self {
            targets: targets.clone(),
            ..Self::default()
        };
        snapshot.numbers.reserve(issues.len());
        for issue in issues {
            snapshot.numbers.push(issue.number);

            let (stated, per_unit) = snapshot.read_issue(issue, &board.wip, &targets);
            snapshot.converted.insert(issue.number, per_unit);
            snapshot.stated.insert(issue.number, stated);

            if workflow::is_completed(issue, &resolution) {
                snapshot.completed.insert(issue.number);
            }

            // The cycle memberships, keyed on the identity `resolve_cycle` answers
            // with rather than on the spelling the issue used.
            let mut spellings: BTreeMap<String, String> = BTreeMap::new();
            let mut scoped = false;
            for reference in issue.cycles.iter().flatten() {
                let cycle = resolve_cycle(index, reference);
                let member = match &cycle {
                    CycleReference::Generated { name, id, .. } => {
                        Some((format!("cycle-id:{id}"), name.clone()))
                    }
                    CycleReference::Legacy { name } => {
                        Some((format!("cycle-name:{name}"), name.clone()))
                    }
                    CycleReference::Unknown { name } => {
                        snapshot.diagnostics.push(
                            ScopeDiagnostic::new(
                                ScopeDiagnosticKind::UnknownScope,
                                CapacityScopeKind::Cycle,
                                name.clone(),
                                format!(
                                    "issue #{} `cycles` names `{name}`, which does not resolve \
                                     to a cycle record",
                                    issue.number
                                ),
                            )
                            .for_issue(issue.number)
                            .because(
                                "the issue counts in no cycle until that cycle exists; an \
                                 unresolvable name is reported, never guessed (C-003)",
                            ),
                        );
                        None
                    }
                };
                let Some((key, name)) = member else {
                    continue;
                };
                snapshot.cycle_names.entry(key.clone()).or_insert(name);
                scoped = true;
                match spellings.entry(key.clone()) {
                    Entry::Vacant(slot) => {
                        slot.insert(reference.clone());
                        snapshot.by_cycle.entry(key).or_default().push(issue.number);
                    }
                    // A second spelling of one identity is one contribution, and the
                    // ambiguity is worth saying out loud.
                    Entry::Occupied(slot) => {
                        if slot.get() != reference {
                            snapshot.diagnostics.push(
                                ScopeDiagnostic::new(
                                    ScopeDiagnosticKind::AmbiguousScope,
                                    CapacityScopeKind::Cycle,
                                    reference.clone(),
                                    format!(
                                        "issue #{} `cycles` names `{reference}` and `{}`, \
                                         which resolve to one cycle",
                                        issue.number,
                                        slot.get()
                                    ),
                                )
                                .for_issue(issue.number)
                                .because("the cycle counts once, not twice"),
                            );
                        }
                    }
                }
            }

            if let Some(handle) = issue.assignee.as_deref().and_then(parse_assignee) {
                scoped = true;
                snapshot
                    .by_assignee
                    .entry(handle.clone())
                    .or_default()
                    .push(issue.number);
                for label in teams_of.get(&handle).into_iter().flatten() {
                    snapshot
                        .by_team
                        .entry(label.clone())
                        .or_default()
                        .push(issue.number);
                }
            }

            if !scoped {
                snapshot.unscoped.push(issue.number);
            }
        }

        for members in snapshot
            .by_cycle
            .values_mut()
            .chain(snapshot.by_team.values_mut())
            .chain(snapshot.by_assignee.values_mut())
        {
            members.sort_unstable();
            members.dedup();
        }
        snapshot.unscoped.sort_unstable();
        snapshot.unscoped.dedup();
        snapshot
    }

    /// One issue record's worth of the pass: the estimate as the issue stated it, and
    /// its reading in every target unit.
    ///
    /// This is the **one** place the snapshot parses an estimate or asks the registry
    /// for a conversion, and the one place the pass's tally
    /// ([`issue_visits`](Self::issue_visits),
    /// [`estimates_parsed`](Self::estimates_parsed),
    /// [`conversions_resolved`](Self::conversions_resolved)) grows. Keeping the work and
    /// its record in the same method is what lets those counters say something: work
    /// duplicated through this seam is counted twice and breaks the tests that anchor the
    /// tally to the slice. Work that bypasses the seam is not counted — see the
    /// accessors for exactly what the tally does and does not prove.
    fn read_issue(
        &mut self,
        issue: &Issue,
        registry: &WipConfig,
        targets: &[String],
    ) -> (EstimateValue, BTreeMap<String, EstimateValue>) {
        self.visits += 1;
        let stated = match issue.estimate.as_deref() {
            // A blank estimate states nothing, so it is unestimated rather than
            // invalid — the same rule the WIP aggregate follows.
            Some(raw) if !raw.trim().is_empty() => {
                self.parses += 1;
                EstimateValue::parse(issue.number, raw)
            }
            _ => EstimateValue::unestimated(),
        };
        let mut per_unit: BTreeMap<String, EstimateValue> = BTreeMap::new();
        for unit in targets {
            per_unit.insert(
                unit.clone(),
                stated.converted_to(issue.number, registry, unit),
            );
        }
        if stated.is_valid() {
            self.conversions += targets.len();
        }
        (stated, per_unit)
    }

    /// Every issue number, in the order the pass saw them.
    #[must_use]
    pub fn issues(&self) -> &[u32] {
        &self.numbers
    }

    /// How many issues the snapshot indexed.
    #[must_use]
    pub fn len(&self) -> usize {
        self.numbers.len()
    }

    /// Whether the snapshot indexed no issues.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.numbers.is_empty()
    }

    /// The units every estimate was converted into, in a stable order (T007).
    #[must_use]
    pub fn targets(&self) -> &[String] {
        &self.targets
    }

    /// An issue's estimate as stated: the raw text, the parsed unit and value, and the
    /// parse diagnostics. No conversion has been applied.
    #[must_use]
    pub fn estimate(&self, number: u32) -> Option<&EstimateValue> {
        self.stated.get(&number)
    }

    /// An issue's estimate converted into `unit`, conversion included.
    ///
    /// `None` only when the issue is not in the snapshot or `unit` was not in the
    /// conversion table — the units [`targets`](Self::targets) lists. Every issue in the
    /// snapshot otherwise answers, including an unestimated one (which stays
    /// unestimated) and an invalid one (whose diagnostics say why).
    #[must_use]
    pub fn estimate_in(&self, number: u32, unit: &str) -> Option<&EstimateValue> {
        self.converted.get(&number)?.get(unit)
    }

    /// Whether #183's category service calls this issue completed.
    #[must_use]
    pub fn is_completed(&self, number: u32) -> bool {
        self.completed.contains(&number)
    }

    /// The issues #183's category service calls completed, in issue order.
    #[must_use]
    pub fn completed(&self) -> &BTreeSet<u32> {
        &self.completed
    }

    /// The issues whose `cycles` resolve to `reference`'s identity.
    ///
    /// `reference` may be a hand-written cycle's name, a generated cycle's name, or a
    /// generated cycle's stable id: all three go through [`resolve_cycle`], so all
    /// three select the same set (T010). An unknown reference selects nobody.
    #[must_use]
    pub fn cycle_members(&self, index: &ScheduleIndex, reference: &str) -> &[u32] {
        let key = match resolve_cycle(index, reference) {
            CycleReference::Generated { id, .. } => format!("cycle-id:{id}"),
            CycleReference::Legacy { name } => format!("cycle-name:{name}"),
            CycleReference::Unknown { .. } => return &[],
        };
        self.by_cycle.get(&key).map_or(&[], Vec::as_slice)
    }

    /// The issues whose assignee is a member of team `label`.
    #[must_use]
    pub fn team_members(&self, label: &str) -> &[u32] {
        self.by_team.get(label).map_or(&[], Vec::as_slice)
    }

    /// The issues assigned to `reference`, by the model's assignee identity.
    ///
    /// The reference folds the way [`crate::assignee::parse_assignee`] folds it, so
    /// `ada` and `@ada` select the same issues and `Ada Lovelace <ada@example.com>` is
    /// its own identity — the same folding [`super::config::validate`] applies.
    #[must_use]
    pub fn assignee_members(&self, reference: &str) -> &[u32] {
        match parse_assignee(reference) {
            Some(handle) => self.by_assignee.get(&handle).map_or(&[], Vec::as_slice),
            None => &[],
        }
    }

    /// The issues in one scope, whichever dimension it is.
    ///
    /// The one call a calculation needs: it dispatches on the entry's scope kind, so
    /// no surface re-implements the per-kind lookup.
    #[must_use]
    pub fn members(
        &self,
        kind: CapacityScopeKind,
        reference: &str,
        index: &ScheduleIndex,
    ) -> &[u32] {
        match kind {
            CapacityScopeKind::Cycle => self.cycle_members(index, reference),
            CapacityScopeKind::Team => self.team_members(reference),
            CapacityScopeKind::Assignee => self.assignee_members(reference),
        }
    }

    /// The cycles with at least one member, by the name they answer to.
    #[must_use]
    pub fn cycle_scopes(&self) -> Vec<&str> {
        self.by_cycle
            .keys()
            .map(|key| {
                self.cycle_names
                    .get(key)
                    .map_or(key.as_str(), String::as_str)
            })
            .collect()
    }

    /// The teams with at least one member.
    #[must_use]
    pub fn team_scopes(&self) -> Vec<&str> {
        self.by_team.keys().map(String::as_str).collect()
    }

    /// The assignee identities with at least one member.
    #[must_use]
    pub fn assignee_scopes(&self) -> Vec<&str> {
        self.by_assignee.keys().map(String::as_str).collect()
    }

    /// The issues that belong to no cycle, team, or assignee scope, in issue order.
    ///
    /// An issue naming only a cycle that does not resolve is here too: it is in no
    /// scope a capacity entry could select.
    #[must_use]
    pub fn unscoped(&self) -> &[u32] {
        &self.unscoped
    }

    /// The membership findings the pass produced, in the order it found them.
    #[must_use]
    pub fn diagnostics(&self) -> &[ScopeDiagnostic] {
        &self.diagnostics
    }

    /// How many issue records the pass's estimate seam walked — the cursor's record.
    ///
    /// One per issue by construction: the pass walks the slice once and this counts the
    /// walk. It is a **discipline about this pass**, not evidence about code outside it —
    /// a second scan elsewhere in the crate would not appear here, and neither would a
    /// re-parse that bypassed the seam. The counters that can catch duplicated work are
    /// [`estimates_parsed`](Self::estimates_parsed) and
    /// [`conversions_resolved`](Self::conversions_resolved), which are incremented by the
    /// work itself.
    #[must_use]
    pub fn issue_visits(&self) -> usize {
        self.visits
    }

    /// How many estimates the pass parsed: one per issue that stated one.
    ///
    /// Counted where the parse happens, so a second read of the estimates through the
    /// same seam counts twice and is visible; the counters measure the work performed,
    /// not the absence of other code. A lookup adds nothing, because a lookup does not
    /// parse (NFR-001).
    #[must_use]
    pub fn estimates_parsed(&self) -> usize {
        self.parses
    }

    /// How many explicit conversions the pass attempted: one per issue with a readable
    /// estimate, per unit in [`targets`](Self::targets).
    ///
    /// This counts the **attempts** — the conversion seam was consulted exactly that
    /// many times, in this pass and nowhere else. Whether a particular attempt produced
    /// a number is read from the value itself
    /// ([`is_converted`](EstimateValue::is_converted)), because a refusal is a
    /// diagnostic on the value, not the loss of one.
    #[must_use]
    pub fn conversions_resolved(&self) -> usize {
        self.conversions
    }
}