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
#[allow(clippy::wildcard_imports)]
use super::*;

impl ProjectPartition {
    pub(super) fn build(config: &crate::config::Config, issues: &[Issue]) -> Self {
        // Both halves come from the **service**, so the board cannot disagree with
        // `tix list --group project` / `tix status --group project` about who is a
        // member or which bucket labels them (WP09 item D): the memberships are
        // [`crate::projects::ProjectIndex::resolved_memberships`], and the label is
        // [`crate::projects::project_bucket_label`].
        let index = crate::projects::ProjectIndex::build(config, issues);
        let order: HashMap<String, usize> = index
            .projects()
            .iter()
            .enumerate()
            .map(|(position, project)| (project.id.to_string(), position))
            .collect();
        Self {
            memberships: index.resolved_memberships(),
            order,
        }
    }

    /// The issue's resolved project ids, in declaration order.
    pub(super) fn memberships(&self, number: u32) -> Vec<String> {
        self.memberships.get(&number).cloned().unwrap_or_default()
    }

    /// The partition rank of one issue: a single membership sorts by its project's
    /// declaration index, several sort after every declared project (and before
    /// the no-project bucket), and none sorts last so `(no project)` is the final
    /// section.
    pub(super) fn rank(&self, number: u32) -> usize {
        match self.memberships.get(&number).map(Vec::as_slice) {
            None | Some([]) => usize::MAX,
            Some([only]) => self.order.get(only).copied().unwrap_or(usize::MAX),
            Some(_) => usize::MAX - 1,
        }
    }
}

/// The group-section label for one card's project membership (WP06 T028).
///
/// `(no project)` is the clearly labelled bucket T028 step 2 requires, and
/// `(multiple projects)` is the bucket an issue in several projects lands in (see
/// [`ProjectPartition`] for why it is one bucket rather than a duplicate per
/// project). A single membership is labelled with the project **id**, because the
/// id is what selects a project, so a reader can act on the header.
pub(crate) fn project_bucket_label(projects: &[String]) -> String {
    // The service owns the bucket rule (WP09 item D); this delegates rather than
    // spelling the three labels a second time.
    crate::projects::project_bucket_label(projects)
}

/// The epic partition of one board build (WP06 T030).
///
/// The exact analogue of [`ProjectPartition`] for the epic registry. Built once from
/// the **shared** membership index ([`crate::epics::EpicIndex::build`]), so the
/// board cannot disagree with `tix epic list` about who is a member: the resolved ids
/// are the registry's, and a reference the registry does not know is not an epic here
/// either — it is reported by `tix lint` instead, and its issue is bucketed
/// `(no epic)`.
///
/// That last point is the same **chosen asymmetry** the project partition records:
/// [`crate::search::StructuredFilter::epic_matches`] matches a stored reference
/// **verbatim**, so `epic:<stale-id>` still *finds* the issues carrying a deleted
/// epic's id (the repair affordance `tix epic remove` needs), while this partition —
/// which answers "which epic owns this issue?" — has no bucket for an id nothing
/// resolves to.
///
/// The bucket rules are the decision T029 step 4 records (one bucket per issue):
///
/// - an issue in **no** epic is its own clearly labelled `(no epic)` bucket;
/// - an issue in exactly **one** epic sits in that epic's bucket;
/// - an issue in **several** epics sits in a single `(multiple epics)` bucket rather
///   than being duplicated into each epic's section.
///
/// Duplication is the road not taken for the reason [`ProjectPartition`] gives: one
/// issue would become several cards, and the board's cursor, hit-testing and
/// per-column counts are all index-into-one-list arithmetic. The **filter** still
/// matches an issue in two epics under either id, so the union semantics are not lost
/// where they matter.
pub(crate) struct EpicPartition {
    /// Issue number -> its resolved epic ids, registry declaration order.
    pub(super) memberships: HashMap<u32, Vec<String>>,
    /// Epic id -> its declaration index, for the sort rank.
    pub(super) order: HashMap<String, usize>,
}

impl EpicPartition {
    pub(super) fn build(config: &crate::config::Config, issues: &[Issue]) -> Self {
        // Both halves come from the **service**: the index owns the membership rule
        // (which references resolve), and `memberships_by_issue` is the service's own
        // inverse of its buckets, in declaration order — so a filter, the CLI's
        // `--group epic` and this partition cannot disagree about who is a member
        // (WP09 item C).
        let index = crate::epics::EpicIndex::build(config, issues);
        let order: HashMap<String, usize> = index
            .epics()
            .iter()
            .enumerate()
            .map(|(position, epic)| (epic.id.to_string(), position))
            .collect();
        let memberships = index.memberships_by_issue();
        Self { memberships, order }
    }

    /// The issue's resolved epic ids, in declaration order.
    pub(super) fn memberships(&self, number: u32) -> Vec<String> {
        self.memberships.get(&number).cloned().unwrap_or_default()
    }

    /// The partition rank of one issue: a single membership sorts by its epic's
    /// declaration index, several sort after every declared epic (and before the
    /// no-epic bucket), and none sorts last so `(no epic)` is the final section.
    pub(super) fn rank(&self, number: u32) -> usize {
        match self.memberships.get(&number).map(Vec::as_slice) {
            None | Some([]) => usize::MAX,
            Some([only]) => self.order.get(only).copied().unwrap_or(usize::MAX),
            Some(_) => usize::MAX - 1,
        }
    }
}

/// The group-section label for one card's epic membership (WP06 T030).
///
/// Delegates to [`crate::search::epic_bucket_label`] rather than spelling the three
/// labels a second time, so the board's header and the filter's vocabulary name the
/// same bucket.
pub(crate) fn epic_bucket_label(ids: &[String]) -> String {
    crate::search::epic_bucket_label(ids)
}

impl crate::config::OrderBy {
    /// Sort cards in place per the board's `order_by` setting. `none` is a
    /// no-op. `sort_by` is stable, so equal creation dates keep the
    /// underlying store order (relative filename ascending) — deterministic
    /// ties with no extra key. Dates are zero-padded `YYYY-MM-DD`, so
    /// lexicographic comparison is chronological.
    pub fn sort(&self, cards: &mut [Card]) {
        match self {
            crate::config::OrderBy::CreatedAtDesc => {
                cards.sort_by(|a, b| b.created.cmp(&a.created))
            }
            crate::config::OrderBy::CreatedAtAsc => cards.sort_by(|a, b| a.created.cmp(&b.created)),
            crate::config::OrderBy::None => {}
        }
    }
}

pub(crate) fn sort_by_default_order(board_config: &BoardConfiguration, cards: &mut [Card]) {
    match board_config.order_by {
        crate::config::OrderBy::CreatedAtDesc => {
            cards.sort_by(|a, b| {
                b.created
                    .cmp(&a.created)
                    .then_with(|| a.filename.cmp(&b.filename))
            });
        }
        crate::config::OrderBy::CreatedAtAsc => {
            cards.sort_by(|a, b| {
                a.created
                    .cmp(&b.created)
                    .then_with(|| a.filename.cmp(&b.filename))
            });
        }
        crate::config::OrderBy::None => {
            cards.sort_by(|a, b| a.filename.cmp(&b.filename));
        }
    }
}

pub(crate) fn sort_cards(board_config: &BoardConfiguration, cards: &mut [Card]) {
    if board_config.card_order.is_empty() {
        sort_by_default_order(board_config, cards);
        return;
    }

    let mut baseline = cards.to_vec();
    sort_by_default_order(board_config, &mut baseline);

    let manual_cards: Vec<Card> = board_config
        .card_order
        .iter()
        .filter_map(|filename| {
            baseline
                .iter()
                .find(|card| card.filename == *filename)
                .cloned()
        })
        .collect();
    let touched: HashSet<String> = manual_cards
        .iter()
        .map(|card| card.filename.clone())
        .collect();
    let mut manual_iter = manual_cards.into_iter();
    let mut ordered = Vec::with_capacity(baseline.len());

    for card in baseline {
        if touched.contains(card.filename.as_str()) {
            if let Some(manual_card) = manual_iter.next() {
                ordered.push(manual_card);
            } else {
                ordered.push(card);
            }
        } else {
            ordered.push(card);
        }
    }

    cards.clone_from_slice(&ordered);
}

/// Reorder one column so each card's sub-issues sit **immediately after it**,
/// marking them `depth = 1` (tix #1399).
///
/// Only **one** level is ever nested. A card is placed under its parent only when
/// that parent is itself a *top-level* card of this column — meaning the parent has
/// no parent of its own present here. A grandchild (a card whose parent is itself a
/// sub-issue) therefore stays `depth = 0` in its normal position rather than
/// stacking under the child, so the tree cannot grow past one indent.
///
/// The ordering is settled **here, at build time**, not in the renderer: the
/// selection index and the pointer hit-test both address cards by their index in
/// the column, so a reorder only the renderer knew about would make a click or a
/// `j` land on the wrong card.
///
/// Every card is emitted exactly once: a nested card is dropped from the top-level
/// sequence and re-emitted under its parent, and nothing else moves.
pub(crate) fn nest_children(cards: &mut Vec<Card>) {
    let count = cards.len();
    if count == 0 {
        return;
    }
    let position: std::collections::HashMap<crate::id::IssueRef, usize> = cards
        .iter()
        .enumerate()
        .map(|(i, card)| (card.reference, i))
        .collect();
    let mut adopted: Vec<Vec<usize>> = vec![Vec::new(); count];
    let mut top_level: Vec<usize> = Vec::with_capacity(count);
    for (index, card) in cards.iter().enumerate() {
        match card
            .parent
            .and_then(|parent| position.get(&parent).copied())
        {
            Some(parent)
                if cards[parent]
                    .parent
                    .is_none_or(|grandparent| !position.contains_key(&grandparent)) =>
            {
                adopted[parent].push(index);
            }
            _ => top_level.push(index),
        }
    }

    let mut ordered: Vec<Card> = Vec::with_capacity(count);
    for index in top_level {
        let mut card = cards[index].clone();
        card.depth = 0;
        ordered.push(card);
        for &child in &adopted[index] {
            let mut child_card = cards[child].clone();
            child_card.depth = 1;
            ordered.push(child_card);
        }
    }
    *cards = ordered;
}

impl BoardState {
    /// Build a board from the search corpus, keeping only cards whose full
    /// serialized text matches **both** the fuzzy `query` layer and the
    /// structured `filter` layer (FR-012/FR-013). Both predicates run in a
    /// single pass over the corpus via [`crate::search::matches`] (NFR-001).
    ///
    /// When a filter is active (non-empty query or structured criteria set),
    /// hidden columns' matching cards are **revealed** in the rendered surface
    /// (DM-01M2MHJB884WCTVCDHPD2T3GE7: hidden-column cards reachable via
    /// filters/search). When no filter is active, matching cards from hidden
    /// columns are stashed in [`BoardState::hidden`] (no visual presence).
    pub fn build_filtered(
        board_config: &BoardConfiguration,
        config: &crate::config::Config,
        corpus: &Corpus,
        query: &str,
        filter: &StructuredFilter,
        resolution: &crate::workflow::CategoryResolution,
    ) -> Self {
        Self::build_filtered_with(
            board_config,
            config,
            corpus,
            query,
            filter,
            resolution,
            false,
        )
    }

    /// [`BoardState::build_filtered`], optionally rendering sub-issues under their
    /// parents (tix #1399).
    ///
    /// The `u` toggle is global, so it must keep working while a search or
    /// structured filter is active: `build_filtered` delegates here with
    /// `show_children == false` and the TUI passes its flag through.
    pub fn build_filtered_with(
        board_config: &BoardConfiguration,
        config: &crate::config::Config,
        corpus: &Corpus,
        query: &str,
        filter: &StructuredFilter,
        resolution: &crate::workflow::CategoryResolution,
        show_children: bool,
    ) -> Self {
        let show_mismatch = board_config.show_mismatch;
        // WP09, as in `build`: the service's completion column, so the filtered and
        // unfiltered boards agree on which column is blocked and which is complete.
        let done_column = crate::workflow::completion_column_or_default(board_config, config);
        let done_column = done_column.as_str();
        // Built from the corpus, not from the filtered slice below: a blocker the
        // query happens to exclude must still count as a blocker.
        let blocked = blocked_reasons(&corpus.issues, done_column);
        // Same reason, same discipline: a child the query excludes is still a
        // child, so a parent's marker must not shrink because the board is
        // filtered.
        let children = child_markers(&corpus.issues, done_column);
        let filtering = !query.is_empty() || filter.has_active_criteria();
        // A `group:<key>` with no explicit `sort:<key>` sorts by that key
        // (WP06 T028). A partition is only contiguous — and only in the key's own
        // order — when the cards are ordered by the same key, and the contract for
        // the project partition names the order explicitly ("declaration order,
        // no-project bucket last"). Without this, `group:project` alone would emit
        // one section per created-date run and the order would depend on the user
        // remembering to type `sort:project` as well.
        //
        // An explicit `sort:` still wins, so `group:cycle sort:due` keeps meaning
        // what it meant.
        let sort_key = crate::search::control_token(query, "sort")
            .or_else(|| crate::search::control_token(query, "group"));
        // The project partition, resolved once from the shared membership index
        // (NFR-001): the sorter and the renderer both read this, so there is no
        // second membership read and no scan per criterion.
        let projects = ProjectPartition::build(config, &corpus.issues);
        // The epic partition, read once from the same shared index as `projects`
        // (WP06 T030): the sorter and the renderer both read this, so there is no
        // second membership read.
        let epics = EpicPartition::build(config, &corpus.issues);
        // A bare-number query (all-ASCII-digit after trim) is an exact issue
        // number match, not a fuzzy digit search: only the issue whose
        // `number` equals it survives, still ANDed with the structured
        // filter (board-filtering FR-02 / FR-03). Any other query keeps the
        // fuzzy-text path.
        let number = crate::search::number_query(query);
        let hidden_names: Vec<&str> = board_config
            .hidden_columns
            .iter()
            .map(String::as_str)
            .collect();
        let mut column_map: Vec<Vec<Card>> =
            board_config.columns.iter().map(|_| Vec::new()).collect();
        let mut mismatch_cards = Vec::new();
        let mut matched_issues: Vec<&crate::model::Issue> = Vec::new();

        for (issue, text) in corpus.issues.iter().zip(corpus.texts().iter()) {
            // Bare-number query: exact issue-number match replaces the fuzzy
            // text layer (board-filtering FR-02); the structured filter still
            // runs (FR-03). Otherwise the composite fuzzy+structured
            // predicate applies unchanged.
            // `matches_issue`, not `matches` (WP08 T035): the TUI filter modal can
            // set a `category` criterion, and `matches` cannot judge it — it would
            // silently drop the criterion and show the **unfiltered** board while
            // the modal showed `category: completed` as active. The board already
            // holds the `resolution` (it is a parameter, because WP05 needed it for
            // the card labels), so the criterion costs one hash lookup per issue.
            let keep = if let Some(n) = number {
                issue.number == n && filter.evaluate_issue(issue, text, resolution)
            } else {
                crate::search::matches_issue(query, filter, issue, text, resolution)
            };
            if !keep {
                continue;
            }
            matched_issues.push(issue);
        }

        Self::sort_filtered_issues(&mut matched_issues, sort_key.as_deref(), &projects, &epics);

        let health_badges = health_badges(&corpus.issues);
        for issue in matched_issues {
            let card = Card {
                reference: crate::id::canonical_ref(issue),
                number: issue.number,
                title: issue.title.clone(),
                priority: issue.priority.clone(),
                labels: issue.labels.clone(),
                assignee: issue.assignee.clone(),
                filename: issue.filename.clone(),
                commit: issue.commit.clone(),
                created: issue.created.clone(),
                due_date: issue.due_date.clone(),
                status: issue.status.display().to_string(),
                category: crate::workflow::category_of(issue, resolution)
                    .map(|c| c.label().to_string()),
                category_color: crate::workflow::category_of(issue, resolution)
                    .and_then(|c| c.color_hint()),
                done: crate::workflow::is_completed(issue, resolution),
                cycle: issue.cycles.as_ref().and_then(|v| v.first().cloned()),
                milestone: issue.milestones.as_ref().and_then(|v| v.first().cloned()),
                blocked: blocked.get(&issue.number).cloned(),
                children: children.get(&issue.number).cloned(),
                parent: issue.parent,
                depth: 0,
                archived: issue.archived,
                related: issue.related_issues.len(),
                health: health_badges.get(&issue.number).cloned(),
                projects: projects.memberships(issue.number),
                epics: epics.memberships(issue.number),
            };
            if let Some(idx) = board_config
                .columns
                .iter()
                .position(|c| c == issue.status.display())
            {
                column_map[idx].push(card);
            } else {
                mismatch_cards.push(card);
            }
        }

        if sort_key.is_none() {
            for cards in column_map.iter_mut() {
                sort_cards(board_config, cards);
            }
            sort_cards(board_config, &mut mismatch_cards);
        }

        let mut columns: Vec<BoardColumn> = Vec::new();
        let mut hidden: Vec<BoardColumn> = Vec::new();
        for (cards, name) in column_map.into_iter().zip(board_config.columns.iter()) {
            let col = BoardColumn {
                name: name.clone(),
                cards,
            };
            if hidden_names.contains(&name.as_str()) {
                if filtering {
                    // Reveal hidden column when a filter is active so
                    // matching cards appear in the rendered surface
                    // (DM-01M2MHJB884WCTVCDHPD2T3GE7).
                    columns.push(col);
                } else {
                    hidden.push(col);
                }
            } else {
                columns.push(col);
            }
        }

        let mut state = BoardState {
            columns,
            hidden,
            mismatch: BoardColumn {
                name: "Mismatched".to_string(),
                cards: mismatch_cards,
            },
            show_mismatch,
            active_col: 0,
            selected: 0,
            filter: Some(query.to_string()),
            hover: None,
            hover_col: None,
        };
        state.apply_child_order(show_children);
        state
    }

    pub(super) fn sort_filtered_issues(
        issues: &mut [&crate::model::Issue],
        sort: Option<&str>,
        projects: &ProjectPartition,
        epics: &EpicPartition,
    ) {
        match sort.unwrap_or("created") {
            // The project partition order (WP06 T028): registry declaration order
            // for a single membership, after every declared project for an issue in
            // several, and last of all for an issue in none — which is exactly the
            // order the buckets are rendered in, so the sections come out
            // contiguous and the `(no project)` bucket is last.
            "project" => issues.sort_by(|a, b| {
                projects
                    .rank(a.number)
                    .cmp(&projects.rank(b.number))
                    .then(a.number.cmp(&b.number))
            }),
            // The epic partition order (WP06 T030): the exact analogue of `project`
            // above, so `group:epic` alone emits one contiguous section per epic in
            // declaration order, then `(multiple epics)`, then `(no epic)` last.
            "epic" => issues.sort_by(|a, b| {
                epics
                    .rank(a.number)
                    .cmp(&epics.rank(b.number))
                    .then(a.number.cmp(&b.number))
            }),
            "due" => {
                issues.sort_by(|a, b| a.due_date.cmp(&b.due_date).then(a.number.cmp(&b.number)))
            }
            "start" => issues.sort_by(|a, b| {
                a.start_date
                    .cmp(&b.start_date)
                    .then(a.number.cmp(&b.number))
            }),
            "reviewer" => {
                issues.sort_by(|a, b| a.reviewer.cmp(&b.reviewer).then(a.number.cmp(&b.number)))
            }
            "cycle" => issues.sort_by(|a, b| {
                a.cycles
                    .as_ref()
                    .and_then(|v| v.first())
                    .cmp(&b.cycles.as_ref().and_then(|v| v.first()))
                    .then(a.number.cmp(&b.number))
            }),
            "milestone" => issues.sort_by(|a, b| {
                a.milestones
                    .as_ref()
                    .and_then(|v| v.first())
                    .cmp(&b.milestones.as_ref().and_then(|v| v.first()))
                    .then(a.number.cmp(&b.number))
            }),
            "status" => issues.sort_by(|a, b| {
                a.status
                    .display()
                    .cmp(b.status.display())
                    .then(a.number.cmp(&b.number))
            }),
            "priority" => issues.sort_by(|a, b| {
                a.priority
                    .to_string()
                    .cmp(&b.priority.to_string())
                    .then(a.number.cmp(&b.number))
            }),
            _ => issues.sort_by(|a, b| a.created.cmp(&b.created).then(a.number.cmp(&b.number))),
        }
    }
}