tix-tracker 0.2.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
//! 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::fmt;
use std::str::FromStr;
use std::time::{SystemTime, UNIX_EPOCH};

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

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

/// 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).
    Other(String),
}

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

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)
        }
    }
}

/// Today's date as a local-free calendar date in `YYYY-MM-DD`.
///
/// Computed from the Unix epoch in UTC; `crate`-wide reproducible and
/// dependency-free. Later WPs reuse it for `created`/`updated` and the
/// date prefix of filenames.
pub fn today() -> String {
    let secs = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let days = (secs / 86_400) as i64;
    let (y, m, d) = civil_from_days(days);
    format!("{y:04}-{m:02}-{d:02}")
}

/// 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())
}

/// A single issue comment, parsed from the `## Comments` body section.
///
/// Mirrors `contracts/comments-format.md`: each comment is a level-3 heading
/// `### <author> (<YYYY-MM-DD>)` followed by free text up to the next `###`
/// head or end of file. Blank lines inside `text` are preserved verbatim
/// (NFR-005); the model never normalizes hand-authored content.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Comment {
    pub author: String,
    pub date: String,
    pub text: String,
}

/// An issue: one markdown file with YAML frontmatter.
///
/// Field order and names are frozen by `contracts/file-format.md` FR-012.
/// `number` is a stored frontmatter key assigned by the storage layer at
/// create time by scanning the live issue set (issue #52; previously from
/// `tix.toml` `[state].next_number`, which is no longer persisted); this
/// module models and validates it but never allocates. `filename` and
/// `body` are memory-only (`#[serde(skip)]`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Issue {
    /// Internal sequential id, never reused (C-007).
    pub number: u32,
    /// Human title; drives the slug in the filename.
    #[serde(default)]
    pub title: String,
    /// Column (board workflow stage) the issue sits in.
    #[serde(default)]
    pub status: Status,
    /// Free-form labels.
    #[serde(default)]
    pub labels: Labels,
    /// Priority; defaults to `medium`.
    #[serde(default)]
    pub priority: Priority,
    /// Assignee. In memory: bare handle (`alice`) or full `Name <email>`
    /// identity, verbatim. Files serialize per the rule documented on
    /// [`de_assignee`]/[`se_assignee`] (legacy `@alice` tolerated on read).
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "de_assignee",
        serialize_with = "se_assignee"
    )]
    pub assignee: Option<String>,
    /// Free-form estimate (e.g. `2`, `S`, `3d`); default `null`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub estimate: Option<String>,
    /// Git commit recorded when moved to `done` (FR-026).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub commit: Option<String>,
    /// Remote GitLab issue id after export/import.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub gitlab_id: Option<String>,
    /// Remote Linear issue id after export/import.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub linear_id: Option<String>,
    /// Spec Kitty mission slug (e.g. `v3-archive-review`) this issue belongs to, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mission: Option<String>,
    /// Spec Kitty work package id (e.g. `WP01`) this issue links to, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub task: Option<String>,
    /// Creation date, `YYYY-MM-DD`, equals the filename date prefix.
    #[serde(default = "today")]
    pub created: String,
    /// Last-mutation date, `YYYY-MM-DD`.
    #[serde(default = "today")]
    pub updated: String,
    /// Issue file name — path relative to the issues dir (e.g. `alice/2026-05-10-fix-login.md` for grouped layout, or `2026-05-10-fix-login.md` for legacy flat files per C-010).
    #[serde(skip)]
    pub filename: String,
    /// Raw markdown body; memory-only, preserved verbatim.
    #[serde(skip)]
    pub body: String,
}

impl Issue {
    /// Parse a full issue file (`frontmatter` + `body`) from its text.
    ///
    /// The first line must be `---`; the closing `---` terminates the
    /// frontmatter. The body after it is preserved verbatim (the single
    /// structural separator blank line is consumed).
    pub fn parse(contents: &str) -> Result<Self> {
        let rest = contents
            .strip_prefix("---\n")
            .ok_or_else(|| TixError::Parse("file must start with a `---` delimiter".into()))?;
        let mut current = rest;
        let mut fm_len = 0usize;
        loop {
            let line_end = current.find('\n').map(|i| i + 1).unwrap_or(current.len());
            let content = current[..line_end]
                .strip_suffix('\n')
                .unwrap_or(&current[..line_end]);
            if content == "---" {
                break;
            }
            fm_len += line_end;
            current = &current[line_end..];
            if current.is_empty() {
                return Err(TixError::Parse(
                    "frontmatter is not terminated by a closing `---`".into(),
                ));
            }
        }
        let frontmatter = &rest[..fm_len];
        let body_raw = &rest[fm_len..];
        let mut body = body_raw.strip_prefix("---\n").unwrap_or(body_raw);
        if let Some(after) = body.strip_prefix('\n') {
            body = after;
        }
        let body = body.to_string();
        let mut issue: Issue =
            serde_yaml::from_str(frontmatter).map_err(|e| TixError::Parse(e.to_string()))?;
        issue.body = body;
        Ok(issue)
    }

    /// Serialize just the frontmatter YAML (no delimiters), with `None`
    /// fields omitted except `created`/`updated` which are always present.
    pub fn frontmatter(&self) -> String {
        let fm =
            serde_yaml::to_string(self).expect("Issue frontmatter serialization is infallible");
        fm.trim_end_matches('\n').to_string() + "\n"
    }

    /// Render the full issue file: `---`, frontmatter, closing `---`,
    /// blank separator and the raw body.
    pub fn to_file_contents(&self) -> String {
        format!("---\n{}---\n\n{}", self.frontmatter(), self.body)
    }

    /// The date-prefixed filename stem: `{created}-{slug}` (C-008).
    pub fn filename_stem(&self) -> String {
        format!("{}-{}", self.created, slugify(&self.title))
    }

    /// Record a mutation by stamping today's date into `updated`.
    pub fn bump_updated(&mut self) {
        self.updated = today();
    }

    /// The byte offset of the first top-level `## Comments` line in `body`,
    /// if any (C-001, `contracts/comments-format.md` rule 6).
    ///
    /// A line counts as the boundary only when it is *not* inside a fenced
    /// code block, so a literal `## Comments` in prose (or a code block) is
    /// never mistaken for the real section head.
    fn comments_boundary(body: &str) -> Option<usize> {
        let mut in_fence = false;
        let mut offset = 0usize;
        for raw in body.split_inclusive('\n') {
            let line = raw.strip_suffix('\n').unwrap_or(raw);
            if line.starts_with("```") || line.starts_with("~~~") {
                in_fence = !in_fence;
            } else if !in_fence && line == "## Comments" {
                return Some(offset);
            }
            offset += raw.len();
        }
        None
    }

    /// The description: everything above the first top-level `## Comments`
    /// heading, trimmed of trailing whitespace. With no section, the whole
    /// body is the description.
    pub fn description(&self) -> &str {
        match Self::comments_boundary(&self.body) {
            Some(idx) => self.body[..idx].trim_end(),
            None => self.body.trim_end(),
        }
    }

    /// The comments parsed from the `## Comments` section, in file order
    /// (NFR-005). With no section — or a section with no `###` heads —
    /// returns an empty vec.
    pub fn comments(&self) -> Vec<Comment> {
        let Some(boundary) = Self::comments_boundary(&self.body) else {
            return Vec::new();
        };
        let section = &self.body[boundary..];
        let mut comments = Vec::new();
        let mut offset = 0usize;
        for raw in section.split_inclusive('\n') {
            let line = raw.strip_suffix('\n').unwrap_or(raw);
            if let Some(after) = line.strip_prefix("### ") {
                let (author, date) = parse_comment_head(after);
                let start = offset + raw.len();
                let mut text = String::new();
                for next in section[start..].split_inclusive('\n') {
                    if next.strip_suffix('\n').unwrap_or(next).starts_with("### ") {
                        break;
                    }
                    text.push_str(next);
                }
                comments.push(Comment {
                    author,
                    date,
                    text: text.trim_end_matches('\n').to_string(),
                });
            }
            offset += raw.len();
        }
        comments
    }

    /// Append a comment to the `## Comments` section.
    ///
    /// Whitespace-only text is discarded and the body is left untouched
    /// (FR-004 case 4). Otherwise the section is created if absent and the
    /// comment block is appended after the last existing comment. The
    /// description and any existing comments are never rewritten.
    pub fn add_comment(&mut self, author: &str, text: &str) {
        if text.trim().is_empty() {
            return;
        }
        if Self::comments_boundary(&self.body).is_none() {
            if !self.body.trim().is_empty() {
                if !self.body.ends_with('\n') {
                    self.body.push('\n');
                }
                self.body.push('\n');
            }
            self.body.push_str("## Comments\n");
        }
        if !self.body.is_empty() && !self.body.ends_with('\n') {
            self.body.push('\n');
        }
        if !self.body.ends_with("\n\n") {
            self.body.push('\n');
        }
        self.body
            .push_str(&format!("### {author} ({})\n\n{text}\n", today()));
        self.bump_updated();
    }
}

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

    #[test]
    fn status_helpers() {
        let s = Status::new("in progress");
        assert!(s.is("in progress"));
        assert!(!s.is("in_progress"));
        assert_eq!(s.display(), "in progress");
        assert_eq!(Status::default(), Status::new("todo"));
    }

    #[test]
    fn status_survives_unknown_column_name() {
        let parsed: Status = serde_yaml::from_str("\"renamed-column\"").unwrap();
        assert_eq!(parsed.display(), "renamed-column");
    }

    #[test]
    fn priority_roundtrips_lowercase_and_parses_case_insensitively() {
        assert_eq!("low".parse::<Priority>().unwrap(), Priority::Low);
        assert_eq!("HIGH".parse::<Priority>().unwrap(), Priority::High);
        assert_eq!(Priority::default(), Priority::Medium);
        assert_eq!(Priority::Low.to_string(), "low");
    }

    #[test]
    fn unknown_priority_is_preserved_not_normalized() {
        let urgent: Priority = serde_yaml::from_str("\"urgent\"").unwrap();
        assert_eq!(urgent.to_string(), "urgent");
        let yaml = serde_yaml::to_string(&urgent).unwrap();
        assert!(yaml.contains("urgent"));
    }

    #[test]
    fn issue_roundtrip_preserves_every_field_including_number_and_body() {
        let mut issue = Issue {
            number: 7,
            title: "Add documentation for the feature".into(),
            status: Status::new("todo"),
            labels: vec!["docs".into(), "onboarding".into()],
            priority: Priority::High,
            assignee: Some("alice".into()),
            estimate: Some("2".into()),
            commit: Some("abc123".into()),
            gitlab_id: Some("gl-9".into()),
            linear_id: Some("LIN-9".into()),
            mission: None,
            task: None,
            created: "2026-05-10".into(),
            updated: "2026-05-10".into(),
            filename: String::new(),
            body: "Describe the issue here.\n\n![diagram](./assets/diagram.png)".into(),
        };
        let contents = issue.to_file_contents();
        let parsed = Issue::parse(&contents).unwrap();
        assert_eq!(parsed, issue);
        issue.body.clear();
        assert_ne!(parsed, issue);
    }

    #[test]
    fn missing_dates_default_to_today() {
        let yaml = "number: 2\ntitle: Hi\nstatus: todo\n";
        let issue: Issue = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(issue.created, today());
        assert_eq!(issue.updated, today());
    }

    #[test]
    fn body_is_preserved_verbatim() {
        let issue = Issue {
            number: 1,
            title: "T".into(),
            status: Status::default(),
            labels: vec![],
            priority: Priority::default(),
            assignee: None,
            estimate: None,
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            created: "2026-01-02".into(),
            updated: "2026-01-02".into(),
            filename: String::new(),
            body: "line one\n\nline two\n```\ncode\n```".into(),
        };
        let contents = issue.to_file_contents();
        let parsed = Issue::parse(&contents).unwrap();
        assert_eq!(parsed.body, issue.body);
    }

    #[test]
    fn assignee_at_prefix_is_stripped_on_read_and_restored_on_write() {
        let yaml = "number: 3\ntitle: T\nstatus: todo\nassignee: \"@alice\"\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n";
        let issue: Issue = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(issue.assignee.as_deref(), Some("alice"));
        let rerendered = issue.frontmatter();
        assert!(
            rerendered.contains("assignee: \"@alice\"")
                || rerendered.contains("assignee: '@alice'")
        );
    }

    #[test]
    fn full_identity_assignee_round_trips_verbatim() {
        let issue = Issue {
            number: 5,
            title: "T".into(),
            status: Status::default(),
            labels: vec![],
            priority: Priority::default(),
            assignee: Some("Herbert Maschke <thyseus@pm.me>".into()),
            estimate: None,
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            created: "2026-01-01".into(),
            updated: "2026-01-01".into(),
            filename: String::new(),
            body: String::new(),
        };
        let fm = issue.frontmatter();
        assert!(
            fm.contains("Herbert Maschke <thyseus@pm.me>"),
            "identity must be stored verbatim, got:\n{fm}"
        );
        assert!(
            !fm.contains("@Herbert Maschke"),
            "identity must not be @-prefixed, got:\n{fm}"
        );
        let parsed = Issue::parse(&issue.to_file_contents()).unwrap();
        assert_eq!(parsed, issue);
    }

    #[test]
    fn bare_handle_assignee_writes_legacy_at_prefix_and_reads_back_bare() {
        let issue = Issue {
            number: 6,
            title: "T".into(),
            status: Status::default(),
            labels: vec![],
            priority: Priority::default(),
            assignee: Some("alice".into()),
            estimate: None,
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            created: "2026-01-01".into(),
            updated: "2026-01-01".into(),
            filename: String::new(),
            body: String::new(),
        };
        let fm = issue.frontmatter();
        assert!(
            fm.contains("assignee: \"@alice\"") || fm.contains("assignee: '@alice'"),
            "legacy @-prefixed bytes expected, got:\n{fm}"
        );
        let parsed = Issue::parse(&issue.to_file_contents()).unwrap();
        assert_eq!(parsed.assignee.as_deref(), Some("alice"));
    }

    #[test]
    fn assignee_read_accepts_both_bare_and_at_prefixed_handles() {
        let legacy = "number: 7\ntitle: T\nstatus: todo\nassignee: \"@alice\"\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n";
        let bare = "number: 7\ntitle: T\nstatus: todo\nassignee: \"alice\"\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n";
        let from_legacy: Issue = serde_yaml::from_str(legacy).unwrap();
        let from_bare: Issue = serde_yaml::from_str(bare).unwrap();
        assert_eq!(from_legacy.assignee.as_deref(), Some("alice"));
        assert_eq!(from_bare.assignee.as_deref(), Some("alice"));
    }

    #[test]
    fn angle_bracket_identity_without_name_written_verbatim() {
        let issue = Issue {
            number: 8,
            title: "T".into(),
            status: Status::default(),
            labels: vec![],
            priority: Priority::default(),
            assignee: Some("<thyseus@pm.me>".into()),
            estimate: None,
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            created: "2026-01-01".into(),
            updated: "2026-01-01".into(),
            filename: String::new(),
            body: String::new(),
        };
        let fm = issue.frontmatter();
        assert!(
            fm.contains("<thyseus@pm.me>"),
            "identity-like value must be verbatim, got:\n{fm}"
        );
        assert!(
            !fm.contains("@<thyseus"),
            "identity-like value must not be @-prefixed, got:\n{fm}"
        );
    }

    #[test]
    fn all_none_frontmatter_only_contains_required_keys() {
        let issue = Issue {
            number: 4,
            title: "T".into(),
            status: Status::default(),
            labels: vec![],
            priority: Priority::default(),
            assignee: None,
            estimate: None,
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            created: "2026-01-01".into(),
            updated: "2026-01-01".into(),
            filename: String::new(),
            body: String::new(),
        };
        let fm = issue.frontmatter();
        assert!(fm.contains("number:"));
        assert!(fm.contains("title:"));
        assert!(fm.contains("status:"));
        assert!(fm.contains("labels:"));
        assert!(fm.contains("priority:"));
        assert!(fm.contains("created:"));
        assert!(fm.contains("updated:"));
        for key in ["assignee", "estimate", "commit", "gitlab_id", "linear_id"] {
            assert!(!fm.contains(key), "frontmatter must omit {key}, got:\n{fm}");
        }
    }

    #[test]
    fn filename_stem_matches_contract_format() {
        let issue = Issue {
            number: 1,
            title: "Fix !Login crash?".into(),
            status: Status::default(),
            labels: vec![],
            priority: Priority::default(),
            assignee: None,
            estimate: None,
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            created: "2026-05-10".into(),
            updated: "2026-05-10".into(),
            filename: String::new(),
            body: String::new(),
        };
        assert_eq!(issue.filename_stem(), "2026-05-10-fix-login-crash");
    }

    #[test]
    fn bump_updated_stamps_today() {
        let mut issue = Issue {
            number: 1,
            title: "T".into(),
            status: Status::default(),
            labels: vec![],
            priority: Priority::default(),
            assignee: None,
            estimate: None,
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            created: "2020-01-01".into(),
            updated: "2020-01-01".into(),
            filename: String::new(),
            body: String::new(),
        };
        issue.bump_updated();
        assert_eq!(issue.updated, today());
        assert_ne!(issue.updated, "2020-01-01");
    }

    #[test]
    fn parse_rejects_malformed_frontmatter() {
        assert!(Issue::parse("no delimiter\n").is_err());
        assert!(Issue::parse("---\na: 1\n").is_err()); // unterminated
        assert!(Issue::parse("---\nbroken: [").is_err()); // bad yaml, unterminated
    }

    #[test]
    fn today_is_an_iso_calendar_date() {
        let t = today();
        assert_eq!(t.len(), 10);
        let parts: Vec<&str> = t.split('-').collect();
        assert_eq!(parts.len(), 3);
        assert_eq!(parts[0].len(), 4);
        assert_eq!(parts[1].len(), 2);
        assert_eq!(parts[2].len(), 2);
    }

    #[test]
    fn civil_from_days_epoch_is_1970_01_01() {
        assert_eq!(civil_from_days(0), (1970, 1, 1));
    }

    // ------------------------------------------------------------------
    // WP01 — Comment data model & body lifecycle
    // ------------------------------------------------------------------

    fn issue(body: &str) -> Issue {
        Issue {
            number: 1,
            title: "T".into(),
            status: Status::default(),
            labels: vec![],
            priority: Priority::default(),
            assignee: None,
            estimate: None,
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            created: "2026-01-01".into(),
            updated: "2026-01-01".into(),
            filename: String::new(),
            body: body.to_string(),
        }
    }

    // --- T001: parse body → description + comments ---

    #[test]
    fn comments_empty_when_no_section() {
        let i = issue("Some description text.\n");
        assert_eq!(i.description(), "Some description text.");
        assert!(i.comments().is_empty());
    }

    #[test]
    fn comments_parsed_from_section() {
        let i = issue(
            "Hello\n\n## Comments\n\n\
             ### @alice (2026-09-13)\n\n\
             First comment.\n\n\
             ### bob (2026-09-14)\n\n\
             Second comment.\n",
        );
        assert_eq!(i.description(), "Hello");
        let cs = i.comments();
        assert_eq!(cs.len(), 2);
        assert_eq!(cs[0].author, "@alice");
        assert_eq!(cs[0].date, "2026-09-13");
        assert_eq!(cs[1].author, "bob");
        assert_eq!(cs[1].date, "2026-09-14");
    }

    #[test]
    fn code_fence_boundary_not_treated_as_boundary() {
        let body = "Description\n\n\
             ```\n\
             ## Comments\n\
             ```\n\n\
             ## Comments\n\n\
             ### eve (2026-10-01)\n\n\
             real comment\n";
        let i = issue(body);
        let cs = i.comments();
        assert_eq!(cs.len(), 1);
        assert_eq!(cs[0].author, "eve");
        assert_eq!(cs[0].date, "2026-10-01");
        assert_eq!(cs[0].text, "\nreal comment");
        assert!(
            i.description().contains("## Comments"),
            "code-blocked heading must be in description"
        );
    }

    #[test]
    fn blank_lines_preserved_in_comment_text() {
        let i = issue(
            "## Comments\n\n\
             ### @alice (2026-09-13)\n\n\
             line one\n\nline two\n\n\n\
             line three\n",
        );
        let cs = i.comments();
        assert_eq!(cs.len(), 1);
        let text = &cs[0].text;
        assert!(
            text.contains("\nline two"),
            "internal blank lines must be preserved: got {text:?}"
        );
        assert!(
            text.contains("line three"),
            "must contain all lines: got {text:?}"
        );
    }

    #[test]
    fn comments_empty_when_section_has_no_heads() {
        let i = issue("## Comments\n\n\n");
        assert!(i.comments().is_empty());
    }

    // --- T002: add_comment ---

    #[test]
    fn add_first_comment_to_empty_body() {
        let mut i = issue("");
        i.add_comment("@alice", "Hello world");
        assert_eq!(i.description(), "");
        let cs = i.comments();
        assert_eq!(cs.len(), 1);
        assert_eq!(cs[0].author, "@alice");
        assert_eq!(cs[0].text, "\nHello world");
        assert!(i.body.contains("## Comments"));
    }

    #[test]
    fn second_comment_appended_after_first() {
        let mut i = issue("");
        i.add_comment("@alice", "first");
        i.add_comment("bob", "second");
        let cs = i.comments();
        assert_eq!(cs.len(), 2);
        let pos_a = i.body.find("### @alice");
        let pos_b = i.body.find("### bob");
        assert!(pos_a < pos_b, "first comment must precede second");
    }

    #[test]
    fn whitespace_only_comment_discarded() {
        let mut i = issue("Hello\n");
        let before = i.body.clone();
        i.add_comment("@alice", "   \n  ");
        assert_eq!(i.body, before, "whitespace-only text must not change body");
    }

    #[test]
    fn description_unchanged_after_add_comment() {
        let mut i = issue("Description text.\n");
        i.add_comment("@alice", "a comment");
        assert_eq!(i.description(), "Description text.");
    }

    #[test]
    fn literal_comments_heading_in_code_block_not_touched() {
        let mut i = issue("```\n## Comments\n```\n");
        i.add_comment("@alice", "new");
        assert!(
            i.body.contains("```\n## Comments\n```"),
            "code-block heading must be preserved: {0:?}",
            i.body
        );
        assert!(i.body.contains("### @alice"), "must contain new comment");
    }

    // --- T003: roundtrip / NFR-005 ---

    #[test]
    fn roundtrip_preserves_comment_data() {
        let mut i = issue(
            "## Comments\n\n\
             ### @alice (2026-09-13)\n\n\
             Original comment.\n",
        );
        i.add_comment("bob", "Second comment");
        let file = i.to_file_contents();
        let parsed = Issue::parse(&file).unwrap();
        assert_eq!(parsed.description(), i.description());
        let cs = parsed.comments();
        assert_eq!(cs.len(), 2);
        assert_eq!(cs[0].author, "@alice");
        assert_eq!(cs[1].author, "bob");
        assert_eq!(cs[1].text, "\nSecond comment");
    }

    #[test]
    fn three_comments_in_file_order() {
        let mut i = issue("");
        i.add_comment("a", "one");
        i.add_comment("b", "two");
        i.add_comment("c", "three");
        let cs = i.comments();
        assert_eq!(
            cs.iter().map(|c| c.author.as_str()).collect::<Vec<_>>(),
            ["a", "b", "c"]
        );
        assert_eq!(
            i.body,
            format!(
                "## Comments\n\n### a ({0})\n\none\n\n### b ({0})\n\ntwo\n\n### c ({0})\n\nthree\n",
                today()
            )
        );
    }

    #[test]
    fn preserves_hand_authored_comment_markdown() {
        let body = "## Comments\n\n\
             ### @alice (2026-09-13)\n\n\
             **bold** and _italic_\n\n\
             - item 1\n- item 2\n\n";
        let i = issue(body);
        let cs = i.comments();
        assert_eq!(cs.len(), 1);
        assert!(cs[0].text.contains("**bold**"));
        assert!(cs[0].text.contains("- item 1"));
    }

    #[test]
    fn description_code_block_heading_not_boundary() {
        let mut i = issue("Intro text here\n\n```\n## Comments\n```\n");
        let before = i.body.clone();
        i.add_comment("eve", "real");
        assert_eq!(i.description(), "Intro text here\n\n```\n## Comments\n```");
        let cs = i.comments();
        assert_eq!(cs.len(), 1);
        assert_eq!(cs[0].author, "eve");
        assert!(
            i.body.starts_with(&before),
            "code-block heading must be preserved"
        );
    }
}