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
//! Issue data model and file-surface types.
//!
//! Mirrors `contracts/file-format.md` and `data-model.md` exactly. The
//! [`Issue`] struct is the Serde surface for the YAML frontmatter of an
//! issue file; the markdown body is carried in `body` and round-trips
//! verbatim. [`Status`], [`Priority`] and [`Labels`] are the value types
//! that appear in frontmatter.

use std::collections::{BTreeMap, HashSet};
use std::fmt;
use std::str::FromStr;
use std::time::{SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::error::{Result, TixError};
use crate::relationships::{IssueView, Relationship};
use crate::slug::slugify;

mod dates;
mod frontmatter;
mod history;
mod issue;
mod refs;
pub use dates::*;
pub use frontmatter::*;
pub use history::*;
pub use issue::*;
pub use refs::*;

/// A board column name. A newtype over the user-defined column strings from
/// `tix.toml`; unknown names survive deserialization because columns are
/// config-defined (a renamed column renders as a "Mismatched" pseudo-column,
/// never a crash).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct Status(pub String);

impl Status {
    /// Create a status from a column name.
    pub fn new(name: impl Into<String>) -> Self {
        Status(name.into())
    }

    /// Whether this status equals `name` (exact, case-sensitive).
    pub fn is(&self, name: &str) -> bool {
        self.0 == name
    }

    /// The column name this status refers to.
    pub fn display(&self) -> &str {
        &self.0
    }
}

impl Default for Status {
    fn default() -> Self {
        Status("todo".to_string())
    }
}

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

/// Issue priority.
///
/// The documented set is `low` / `medium` / `high` with `medium` as the
/// default (spec + data-model). Any other value is preserved as-is for
/// forward compatibility (data-model: "unknown values accepted as-is",
/// "preserved ... but not normalized"), so e.g. `urgent` round-trips
/// unchanged.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub enum Priority {
    Low,
    #[default]
    Medium,
    High,
    /// An unknown priority string, preserved verbatim (forward-compatible).
    ///
    /// The empty string is *not* treated as unknown: it is an explicitly unset
    /// priority, which `tix lint` accepts and which round-trips as `''`. It stays
    /// in this variant rather than getting a variant of its own because
    /// `Priority` is public API on a published crate, and adding a variant to a
    /// non-`#[non_exhaustive]` enum is a semver break for every downstream
    /// `match`. Use [`Priority::is_undefined`] rather than comparing the string.
    Other(String),
}

impl Priority {
    fn as_str(&self) -> &str {
        match self {
            Priority::Low => "low",
            Priority::Medium => "medium",
            Priority::High => "high",
            Priority::Other(s) => s,
        }
    }

    /// Whether the priority is explicitly **unset** — written `priority: ''`.
    ///
    /// Distinct from [`Priority::default`], which is `Medium`. An issue can
    /// therefore say "no priority" without being read as "medium", and without
    /// the value being silently rewritten on the next write.
    ///
    /// `tix lint` accepts this state; see [`crate::commands::lint`] for the
    /// check it is exempt from.
    pub fn is_undefined(&self) -> bool {
        matches!(self, Priority::Other(s) if s.is_empty())
    }
}

impl FromStr for Priority {
    type Err = std::convert::Infallible;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Ok(match s.to_ascii_lowercase().as_str() {
            "low" => Priority::Low,
            "medium" => Priority::Medium,
            "high" => Priority::High,
            _ => Priority::Other(s.to_string()),
        })
    }
}

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

impl Serialize for Priority {
    fn serialize<S: Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
        s.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for Priority {
    fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
        let raw = String::deserialize(d)?;
        match raw.parse() {
            Ok(parsed) => Ok(parsed),
            Err(_) => Ok(Priority::Other(raw)),
        }
    }
}

/// Issue labels. Free-form strings kept exactly as authored (case and
/// spaces preserved); default `[]`.
pub type Labels = Vec<String>;

/// Assignee file-encoding rule (FR-027 / FR-014, `contracts/file-format.md`
/// rule 5).
///
/// - **In memory**: a manual handle is always bare (`alice`, never
///   `@alice`); a git-derived identity is the full `Name <email>` string,
///   verbatim.
/// - **Read** ([`de_assignee`]): a single leading `@` is stripped, so both
///   the legacy `@alice` bytes and the bare `alice` bytes normalize to the
///   same in-memory handle. A full identity / identity-like value never
///   starts with `@` and passes through untouched.
/// - **Write** ([`se_assignee`]): a value carrying an identity form (both `<`
///   and `>` present, e.g. `Name <email>`) is persisted verbatim — no forced
///   `@` and no mangling of the angle brackets. Any other value is a manual
///   handle and is persisted with a single leading `@`, byte-identical to the
///   legacy `@alice` files (C-010) and to what `contracts/cli.md` conformance
///   pins for `--assignee @alice`.
/// - `None` persists as `null` (omitted by `skip_serializing_if`).
///
/// The in-memory value stays display-neutral: the `@` cosmetic a CLI/TUI
/// renders around handles is their concern, not the model's.
fn de_assignee<'de, D: Deserializer<'de>>(d: D) -> std::result::Result<Option<String>, D::Error> {
    let opt = Option::<String>::deserialize(d)?;
    Ok(opt.map(|v| v.strip_prefix('@').unwrap_or(&v).to_string()))
}

/// Serialize an assignee per the encoding rule documented on [`de_assignee`]:
/// identity-like values verbatim, manual handles `@`-prefixed (legacy bytes).
fn se_assignee<S: Serializer>(opt: &Option<String>, s: S) -> std::result::Result<S::Ok, S::Error> {
    match opt {
        None => s.serialize_none(),
        Some(value) => {
            let is_identity = value.contains('<') && value.contains('>');
            let full = if is_identity || value.starts_with('@') {
                value.clone()
            } else {
                format!("@{value}")
            };
            s.serialize_str(&full)
        }
    }
}

/// Serialization rule for the optional planning lists `cycles`/`milestones`
/// (`contracts/file-format-planning.md`): the key is omitted when absent or
/// empty (only non-empty lists serialize), and duplicate entries are
/// collapsed on write preserving first-seen order.
fn skip_planning_list(v: &Option<Vec<String>>) -> bool {
    v.as_deref().is_none_or(|items| items.is_empty())
}

fn se_planning_list<S: Serializer>(
    v: &Option<Vec<String>>,
    s: S,
) -> std::result::Result<S::Ok, S::Error> {
    let items: Vec<&String> = match v {
        Some(items) => {
            items
                .iter()
                .fold((Vec::new(), HashSet::new()), |(mut out, mut seen), item| {
                    if seen.insert(item.as_str()) {
                        out.push(item);
                    }
                    (out, seen)
                })
                .0
        }
        None => Vec::new(),
    };
    items.serialize(s)
}

/// The key of a top-level YAML mapping entry, or `None` for a continuation line.
///
/// Only column 0 counts. An indented `key:` is part of a nested mapping, and a
/// `- item` is a sequence entry; treating either as a top-level key would end the
/// previous block early and capture a fragment.
fn top_level_key(line: &str) -> Option<String> {
    if !line.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') {
        return None;
    }
    let colon = line.find(':')?;
    let key = &line[..colon];
    if key.is_empty()
        || !key
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
    {
        return None;
    }
    Some(key.to_string())
}

fn frontmatter_has_retired_links_key(frontmatter: &str) -> bool {
    if let Ok(mapping) = serde_yaml::from_str::<serde_yaml::Mapping>(frontmatter) {
        let key = serde_yaml::Value::String("links".into());
        return match mapping.get(&key) {
            Some(value) => !links_value_is_empty(value),
            None => false,
        };
    }
    frontmatter.lines().any(|line| {
        if line.starts_with(' ') || line.starts_with('\t') {
            return false;
        }
        line.split_once(':')
            .map(|(key, _)| key.trim() == "links")
            .unwrap_or(false)
    })
}

/// Whether a `links:` value carries no entries, in the shapes the old model
/// wrote and the shapes a hand-edit can produce: `[]`, `~`/`null`, an empty
/// scalar, and a block sequence with no items (`links:\n` followed by the next
/// key). Anything else is populated and therefore a finding.
fn links_value_is_empty(value: &serde_yaml::Value) -> bool {
    match value {
        serde_yaml::Value::Null => true,
        serde_yaml::Value::Sequence(items) => items.is_empty(),
        serde_yaml::Value::String(s) => s.trim().is_empty() || s.trim() == "[]",
        serde_yaml::Value::Mapping(m) => m.is_empty(),
        serde_yaml::Value::Tagged(t) => links_value_is_empty(&t.value),
        _ => false,
    }
}

/// Real day count for a Gregorian month (leap-aware).
fn days_in_month(year: u32, month: u32) -> u32 {
    match month {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        2 => {
            let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
            if leap { 29 } else { 28 }
        }
        _ => 0,
    }
}

/// Message-bearing [`validate_date`] for surfaces that want to explain what
/// was wrong. The error names the offending value; callers add field context.
fn validate_date_msg(s: &str) -> std::result::Result<(), String> {
    if validate_date(s) {
        Ok(())
    } else {
        Err(format!(
            "`{s}` is not a `YYYY-MM-DD` calendar date (year >= 1970)"
        ))
    }
}

/// Convert days since the Unix epoch to a `(year, month, day)` civil date
/// (Howard Hinnant's `civil_from_days`).
fn civil_from_days(z: i64) -> (i64, u32, u32) {
    let z = z + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = z - era * 146_097; // [0, 146096]
    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; // [0, 399]
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
    let mp = (5 * doy + 2) / 153; // [0, 11]
    let d = (doy - (153 * mp + 2) / 5 + 1) as u32; // [1, 31]
    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; // [1, 12]
    (if m <= 2 { y + 1 } else { y }, m, d)
}

/// Parse a `### <author> (<YYYY-MM-DD>)` comment head into its parts.
///
/// The date is the trailing `(<YYYY-MM-DD>)` group; the author is everything
/// before it. A head without a well-formed trailing date still yields the
/// author (the date defaults to `""`), so malformed heads survive the parse
/// without crashing (`contracts/comments-format.md` rule "preserve verbatim").
fn parse_comment_head(after: &str) -> (String, String) {
    let (author, date) = match after.len() {
        len if len >= 12 && after.as_bytes()[len - 1] == b')' => {
            let close = len - 1;
            let open = after[..close].rfind(" (");
            match open {
                Some(open) => {
                    let maybe_date = &after[open + 2..close];
                    if maybe_date.len() == 10
                        && maybe_date.as_bytes()[4] == b'-'
                        && maybe_date.as_bytes()[7] == b'-'
                    {
                        (&after[..open], maybe_date)
                    } else {
                        (after, "")
                    }
                }
                None => (after, ""),
            }
        }
        _ => (after, ""),
    };
    (author.trim_end().to_string(), date.to_string())
}

// ---------------------------------------------------------------------------
// Append-only History section (WP02 T007)
// ---------------------------------------------------------------------------

/// The separator between the four fields of a rendered History entry
/// (U+2014 em dash).
const HISTORY_SEP: char = '\u{2014}';

/// The marker separating the transition record from its override reason.
///
/// **Includes the closing paren**, and that is load-bearing rather than
/// cosmetic. The obvious marker is `"; override: "`, split with `rsplit_once` so a
/// reason containing the marker survives — and it does not: the *last* occurrence
/// of a bare `"; override: "` inside a reason like `typo; override: actually…` is
/// the one that splits, which leaves the head ending in `; override: typo` and no
/// closing paren, so the parse fails outright. WP03's first version did exactly
/// that and its own test caught it.
///
/// Anchoring the marker to the `)` that closes the head makes the split
/// **unambiguous in both directions**: the head is the only `)` followed by the
/// marker, so `split_once` at the *first* occurrence always takes the right one.
/// A reason may therefore contain the bare marker, a bare `")"`, and even the full
/// anchored marker, and still round-trip.
///
/// That last case is worth spelling out because WP03's first two attempts both got
/// it wrong in opposite directions. `rsplit_once` on the *bare* marker took the
/// last occurrence, so a reason containing `"; override: "` truncated and the parse
/// failed outright. `rsplit_once` on the *anchored* marker would be no better: for
/// a reason containing `"); override: "` the last occurrence is the one inside the
/// reason. `split_once` on the anchored marker is the only combination of the two
/// that is correct, and `t012_a_reason_containing_the_anchored_marker_survives`
/// exists to keep it that way.
const OVERRIDE_MARKER: &str = "); override: ";
/// The marker opening the bracketed category pair.
const CATEGORY_OPEN: &str = " (";
/// The arrow between two names in the `detail` grammar.
const DETAIL_ARROW: &str = " -> ";

/// Whether a line is a **recognised** History entry attempt.
/// Whether a line is **shaped like a markdown list item**, regardless of whether
/// it is a valid entry.
///
/// Used to decide where an unrecognised line belongs: a list item inside a
/// History section is far more likely a hand-edited entry than prose, and the two
/// are not told apart by anything else, because the section has no terminator.
///
/// All four common markers count, not just `- `. This is not a widening of the
/// entry grammar — recognition still requires U+2014, so nothing here can be read
/// as a relationship. With `- ` alone, an entry written
/// `* 2026-01-01T00:00:00Z — a — kind — d` was treated as prose, so the section
/// ended, the heading was deleted, and the next append was rendered above it.
fn is_list_item(item: &str) -> bool {
    for marker in ["- ", "* ", "+ "] {
        if item.starts_with(marker) {
            return true;
        }
    }
    // An ordered marker: digits then `.` or `)` then a space. Bounded to two
    // digits, or `2026. Q1 goals` reads as an ordered-list item and a paragraph
    // of ordinary body prose gets retained in the audit log.
    let Some(dot) = item.find(['.', ')']) else {
        return false;
    };
    dot > 0
        && dot <= 2
        && item[..dot].bytes().all(|b| b.is_ascii_digit())
        && item[dot + 1..].starts_with(' ')
}

/// Tail fields required to call a line a mistyped entry when **reporting** it.
///
/// Four fields in total, because that is the form carrying a detail; the shorter
/// three-field form is indistinguishable from a dated changelog line
/// (`- 2026-01-01 - Bob - Done`), and `tix lint` exits non-zero on a finding.
const STRICT_TAIL_FIELDS: usize = 3;

/// Tail fields required to call a line an entry **attempt** when deciding whether
/// to retain it.
///
/// Two, i.e. three fields in total, which is the shortest form `HistoryEvent::parse`
/// accepts — `detail` is optional there. A retention test stricter than the
/// recognition path is backwards: a valid three-field entry would be demoted to
/// body text and then destroyed by the next `tix edit --body`, while the
/// malformed four-field one survived. Cycle 6 found that inversion.
const RETENTION_TAIL_FIELDS: usize = 2;

fn is_entry_attempt(item: &str) -> bool {
    let Some(rest) = strip_list_marker(item) else {
        return false;
    };
    if rest.contains(HISTORY_SEP) {
        // Correct separators. A `*`- or `1.`-marked entry is not *recognised* —
        // both `looks_like_history_entry` and `HistoryEvent::parse` require the
        // `- ` prefix — but it is unmistakably an entry attempt, and treating it
        // as prose cost a well-formed audit line. Cycle 6 found this.
        return true;
    }
    entry_shaped_by_ascii_hyphens(rest, RETENTION_TAIL_FIELDS)
}

/// Whether `rest` is a plausible entry body whose separators were typed as ASCII
/// hyphens: a date, then at least `min_tail` further hyphen-separated fields.
///
/// The tail splits on hyphens with optional surrounding spaces rather than on the
/// literal `" - "`, because an entry typed with ASCII hyphens is often typed
/// without the spaces too: `- 2026-01-01T00:00:00Z-alice-kind-d`. An earlier
/// version required `" - "` and so missed the case this tool exists to catch,
/// while the recognition path trims after the marker and accepted the same
/// whitespace — the identical line was "not an entry" and never mentioned.
fn entry_shaped_by_ascii_hyphens(rest: &str, min_tail: usize) -> bool {
    let Some(tail) = strip_leading_timestamp(rest) else {
        return false;
    };
    let parts: Vec<&str> = tail
        .split('-')
        .map(str::trim)
        .filter(|p| !p.is_empty())
        .collect();
    if parts.len() < min_tail {
        return false;
    }
    // The field right after the timestamp is an actor or a kind, and neither is a
    // date. Rejecting a numeric one is what keeps a date *range* out:
    // `- 2026-01-01..2026-01-05 was the freeze` otherwise splits into three
    // parts and reads as a mistyped entry.
    !starts_like_a_date(parts[0])
}

/// Whether a token opens with a run of four or more digits — a year, a serial
/// number, a date. Used only to reject prose that would otherwise split into
/// enough hyphen-separated fields to look like an entry.
fn starts_like_a_date(token: &str) -> bool {
    let digits = token.bytes().take_while(u8::is_ascii_digit).count();
    digits >= 4
}

/// The text after any accepted list marker, with whatever whitespace a hand put
/// after it removed.
///
/// `HistoryEvent::parse` trims after the prefix too, so this must as well:
/// otherwise `-  2026-…—…` and `-\t2026-…—…` are recognised as real entries while
/// their ASCII-hyphen equivalents are silently unreported.
fn strip_list_marker(line: &str) -> Option<&str> {
    let item = line.trim();
    if is_list_item(item) {
        let space = item.find(char::is_whitespace).unwrap_or(item.len());
        return Some(item[space..].trim_start());
    }
    None
}

/// The remainder of a line whose first field begins with a plausible ISO date, or
/// `None` if it does not.
///
/// A date is the only field shape that separates a mistyped entry from an
/// ordinary dated bullet, and requiring it is what keeps `tix lint` quiet on
/// prose. Plausibility is deliberately not checked: rejecting a hand-typed
/// offset like `+02:00` would create a false negative in the one tool whose job
/// is to catch exactly this mistake, so implausible shapes are reported rather
/// than filtered.
fn strip_leading_timestamp(rest: &str) -> Option<&str> {
    let b = rest.as_bytes();
    if b.len() < 10
        || !b[0..4].iter().all(u8::is_ascii_digit)
        || b[4] != b'-'
        || !b[5..7].iter().all(u8::is_ascii_digit)
        || b[7] != b'-'
        || !b[8..10].iter().all(u8::is_ascii_digit)
    {
        return None;
    }
    let mut i = 10;
    if b.get(i) == Some(&b'T') {
        i += 1;
        while i < b.len() && (b[i].is_ascii_digit() || b[i] == b':' || b[i] == b'.') {
            i += 1;
        }
        match b.get(i) {
            Some(b'Z') => i += 1,
            // A `-` is a zone separator only when digits follow it; otherwise it
            // is the first field separator and the timestamp ended at the time.
            Some(&b'-') => {
                let mut j = i + 1;
                while j < b.len() && b[j].is_ascii_digit() {
                    j += 1;
                }
                if j > i + 1 {
                    i = j;
                }
            }
            Some(&b'+') => {
                i += 1;
                while i < b.len() && (b[i].is_ascii_digit() || b[i] == b':') {
                    i += 1;
                }
            }
            _ => {}
        }
    }
    // \`.\` too: a date *range* continues with \`..\`, and leaving it glued to
    // the next token makes \`- 2026-01-01..2026-01-05 was the freeze\` split into
    // three fields.
    Some(rest[i.min(rest.len())..].trim_start_matches(['-', ' ', '\t', '.']))
}

// ---------------------------------------------------------------------------
// The hierarchy service's view of an `Issue`
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// The project service's view of an `Issue`
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// The epic service's view of an `Issue`
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests;