tix-tracker 0.3.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
//! `tix.toml` config schema, defaults, loading, saving and validation.
//!
//! Mirrors `contracts/tix-toml.md` and `data-model.md` §Config. The
//! [`Config`] type is the Serde surface for `tix.toml`; [`StateConfig`]
//! carries the legacy `[state].next_number` counter, which is tolerated on
//! load and never written back out (issue #52 — the issue number is
//! resolved at creation time by scanning the live issue set). Loading emits
//! a warning whenever a cleartext token is read from the file, and
//! [`Config::save`] never serializes tokens back to disk.

use std::collections::HashSet;
use std::path::{Path, PathBuf};

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

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

/// Remote tracker credentials/targets embedded in `tix.toml`.
///
/// `token` values are read-only: they are never serialized back out and are
/// never echoed in logs or errors. `base_url` may override the default
/// endpoint for self-hosted GitLab instances.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct RemoteConfig {
    /// Optional cleartext token; prefer the `GITLAB_TOKEN`/`LINEAR_TOKEN`
    /// env vars. Never serialized back to disk.
    pub token: Option<String>,
    /// Optional base URL (e.g. self-hosted GitLab).
    pub base_url: Option<String>,
    /// GitLab project path (e.g. `acme/tix`) passed to `glab`.
    pub project: Option<String>,
    /// Linear team name passed to `linear-cli`.
    pub team: Option<String>,
}

/// The `[export]` section: per-target remote configuration.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ExportConfig {
    /// GitLab remote target.
    pub gitlab: Option<RemoteConfig>,
    /// Linear remote target.
    pub linear: Option<RemoteConfig>,
}

/// The `[state]` section — deprecated runtime bookkeeping that is still
/// tolerated on load for legacy `tix.toml` files but is never serialized.
///
/// The monotonic `next_number` counter this held was removed in issue #52:
/// issue numbers are now resolved at creation time by scanning the live
/// issue set, so [`Config::save`] writes no `[state]` section at all.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct StateConfig {
    /// Legacy monotonic issue-number counter (C-007). Read-only — kept so
    /// old `tix.toml` files with `[state].next_number` still load, and
    /// never persisted once saved again.
    #[serde(skip_serializing)]
    pub next_number: u32,
}

/// Card ordering for the rendered board (`[kanban.<name>].order_by`).
///
/// Applied per column in the board builders; the store's underlying order is
/// untouched so the CLI keeps its own sequencing (board-display FR-02).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum OrderBy {
    /// Most recently created issues first (the default).
    #[default]
    #[serde(rename = "created_at_desc")]
    CreatedAtDesc,
    /// Oldest issues first.
    #[serde(rename = "created_at_asc")]
    CreatedAtAsc,
    /// Preserve the underlying store (filename/created-date ascending) order.
    #[serde(rename = "none")]
    None,
}

impl OrderBy {
    /// The TOML spelling of this variant.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::CreatedAtDesc => "created_at_desc",
            Self::CreatedAtAsc => "created_at_asc",
            Self::None => "none",
        }
    }

    /// The next variant when cycling the setting in the TUI settings modal.
    pub fn next(self) -> Self {
        match self {
            Self::CreatedAtDesc => Self::CreatedAtAsc,
            Self::CreatedAtAsc => Self::None,
            Self::None => Self::CreatedAtDesc,
        }
    }
}

/// A named board configuration (`[kanban.<name>]` in `tix.toml`).
///
/// Carries the ordered column list plus per-configuration metadata: the done
/// column, columns hidden from the rendered board, and whether the computed
/// "Mismatched" pseudo-column is shown (C-002 / DM-01M2MH4D84NHG0JVWEPR6ZH4VR).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct BoardConfiguration {
    /// Ordered, case-sensitive, non-empty, unique column names.
    pub columns: Vec<String>,
    /// The column treated as "done" (commit prompting). Defaults to `"done"`
    /// when that name is present in `columns`, else the last configured
    /// column (contracts/tix-toml.md field rules).
    pub done_column: Option<String>,
    /// Columns hidden from the rendered board. Must be a subset of `columns`;
    /// their cards stay in board state and remain reachable via filters/search.
    pub hidden_columns: Vec<String>,
    /// Whether the computed "Mismatched" pseudo-column is rendered. Default
    /// `false`. Never a configured column.
    pub show_mismatch: bool,
    /// Whether long card titles wrap onto multiple lines. Default `true`.
    pub wrap_titles: bool,
    /// The maximum number of lines a wrapped card may occupy. Default `3`;
    /// validated `>= 1` in [`validate_board`]. Ignored when `wrap_titles`
    /// is `false`.
    pub title_lines: usize,
    /// Ordering of cards within each rendered column. Default
    /// `created_at_desc` (most recently created first).
    pub order_by: OrderBy,
}

impl Default for BoardConfiguration {
    fn default() -> Self {
        Self {
            columns: ["todo", "in progress", "in review", "done"]
                .into_iter()
                .map(String::from)
                .collect(),
            done_column: Some("done".to_string()),
            hidden_columns: Vec::new(),
            show_mismatch: false,
            wrap_titles: true,
            title_lines: 3,
            order_by: OrderBy::default(),
        }
    }
}

impl BoardConfiguration {
    /// The resolved done column: the explicit `done_column`, else `"done"`
    /// when present in `columns`, else the last configured column.
    pub fn effective_done_column(&self) -> Option<&str> {
        if let Some(done) = self.done_column.as_deref() {
            return Some(done);
        }
        if self.columns.iter().any(|c| c == "done") {
            Some("done")
        } else {
            self.columns.last().map(String::as_str)
        }
    }
}

/// The `[kanban]` section: named configurations in declaration order.
///
/// `#[serde(transparent)]` maps the TOML table `[kanban.<name>]` straight
/// onto the [`IndexMap`]. The `toml` parser sorts table keys, so
/// [`Config::load_with_warning`] re-orders the map from the source
/// document's `[kanban.<name>]` header order via
/// [`restore_declaration_order`] (D-02: declaration order = tab order,
/// validated by the round-trip test). The map is never empty after load —
/// [`Config::load_with_warning`] synthesizes the shipped `default`
/// configuration when `tix.toml` omits the section.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default, transparent)]
pub struct KanbanSection {
    /// Named configurations, keyed by name, in declaration order.
    pub configurations: IndexMap<String, BoardConfiguration>,
}

/// The project configuration file (`tix.toml`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
    /// Named board configurations (`[kanban]`). Always ≥1 after load.
    pub kanban: KanbanSection,
    /// Directory holding issue files, relative to the repo root.
    pub issues_dir: PathBuf,
    /// Optional `$EDITOR` override for full-file editing.
    pub editor: Option<String>,
    /// Configured AI agent command (opencode, claude, etc.) launched with
    /// the issue body as its specification. Mirrors the `editor` resolution
    /// chain (explicit → `$TIX_AGENT` → `$AGENT` env → PATH fallback).
    pub agent: Option<String>,
    /// Persisted runtime state (`[state]`). Tolerated on load for legacy
    /// files, never written back to disk (issue #52).
    #[serde(skip_serializing)]
    pub state: StateConfig,
    /// External tracker targets (`[export]`).
    pub export: ExportConfig,
}

impl Default for Config {
    fn default() -> Self {
        Config {
            kanban: KanbanSection {
                configurations: IndexMap::from([(
                    "default".to_string(),
                    BoardConfiguration::default(),
                )]),
            },
            issues_dir: PathBuf::from("docs/issues"),
            editor: None,
            state: StateConfig::default(),
            export: ExportConfig::default(),
            agent: None,
        }
    }
}

impl Config {
    /// Validate the invariant rules from `contracts/tix-toml.md`, returning
    /// the `Config` error variant with a human message. Errors name the
    /// offending configuration as `kanban.<name>.<field>` (NFR-003).
    fn validate(&self) -> Result<()> {
        if self.issues_dir.as_os_str().is_empty() {
            return Err(TixError::Config("`issues_dir` must not be blank".into()));
        }
        if self.kanban.configurations.is_empty() {
            return Err(TixError::Config(
                "`[kanban]` must define at least one configuration".into(),
            ));
        }
        for (name, board) in &self.kanban.configurations {
            validate_board(name, board)?;
        }
        Ok(())
    }

    /// Restore the canonical declaration order of named configurations,
    /// which the TOML parser loses (it sorts table keys). The order comes
    /// from `[kanban.<name>]` section headers in the source document.
    fn restore_declaration_order(&mut self, contents: &str) {
        crate::config::restore_declaration_order(&mut self.kanban, contents);
    }

    /// The configuration used by the CLI and other single-config surfaces:
    /// the one named `default` if present, else the first declared.
    pub fn default_config(&self) -> &BoardConfiguration {
        self.kanban
            .configurations
            .get("default")
            .or_else(|| self.kanban.configurations.first().map(|(_, board)| board))
            .expect("validate() guarantees at least one configuration")
    }

    /// Named configurations in declaration order (tab order = declaration
    /// order, D-02).
    pub fn configs(&self) -> impl Iterator<Item = (&str, &BoardConfiguration)> {
        self.kanban
            .configurations
            .iter()
            .map(|(name, board)| (name.as_str(), board))
    }

    /// Load a `tix.toml` at `path`, emitting a warning through `sink` for
    /// every cleartext token read from the file.
    ///
    /// Parse and validation failures surface as [`TixError::Config`] with
    /// the file's path and (where the TOML parser reports it) line.
    pub fn load_with_warning(path: &Path, mut sink: impl FnMut(&str)) -> Result<Config> {
        let contents = std::fs::read_to_string(path)
            .map_err(|e| TixError::Config(format!("{}: {e}", path.display())))?;
        let mut config: Config = toml::from_str(&contents)
            .map_err(|e| TixError::Config(format!("{}: {e}", path.display())))?;
        config.restore_declaration_order(&contents);
        if config.kanban.configurations.is_empty() {
            config.kanban = KanbanSection {
                configurations: IndexMap::from([(
                    "default".to_string(),
                    BoardConfiguration::default(),
                )]),
            };
        }
        config.validate().map_err(|e| match e {
            TixError::Config(msg) => TixError::Config(format!("{}: {msg}", path.display())),
            other => other,
        })?;
        for remote in [config.export.gitlab.as_ref(), config.export.linear.as_ref()]
            .into_iter()
            .flatten()
        {
            if remote.token.is_some() {
                sink(
                    "Warning: token found in tix.toml — prefer GITLAB_TOKEN / LINEAR_TOKEN env vars",
                );
            }
        }
        Ok(config)
    }

    /// Load the config for a project root: `tix.toml` at the root if
    /// present, otherwise the defaults. An absent file is *not* an error —
    /// the CLI layer decides whether to nag about `tix init`.
    pub fn load(project_root: &Path) -> Result<Config> {
        let path = project_root.join("tix.toml");
        if !path.is_file() {
            return Ok(Config::default());
        }
        Self::load_with_warning(&path, |w| eprintln!("{w}"))
    }

    /// Find the project root for `cwd` by walking upward for a `tix.toml`.
    /// Returns `None` when no ancestor (including `cwd` itself) holds one.
    pub fn project_root(cwd: &Path) -> Option<PathBuf> {
        let mut dir = Some(cwd.to_path_buf());
        while let Some(current) = dir {
            if current.join("tix.toml").is_file() {
                return Some(current);
            }
            dir = current.parent().map(Path::to_path_buf);
        }
        None
    }

    /// A copy of this config with every token stripped, for writing.
    fn sanitized_for_disk(&self) -> Config {
        let mut copy = self.clone();
        if let Some(gitlab) = copy.export.gitlab.as_mut() {
            gitlab.token = None;
        }
        if let Some(linear) = copy.export.linear.as_mut() {
            linear.token = None;
        }
        copy
    }

    /// Write `tix.toml` atomically (temp file + rename in the same
    /// directory, with an `fsync` before the rename — NFR-006).
    ///
    /// Tokens are never written to disk, so a round-trip `load` → `save`
    /// drops any cleartext token (expected: prefer env vars).
    pub fn save(&self, path: &Path) -> Result<()> {
        let dir = match path.parent() {
            Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
            _ => PathBuf::from("."),
        };
        std::fs::create_dir_all(&dir)?;

        let disk = self.sanitized_for_disk();
        let contents = toml::to_string_pretty(&disk)
            .map_err(|e| TixError::Config(format!("cannot serialize tix.toml: {e}")))?;

        let file_name = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("tix.toml");
        let tmp = dir.join(format!("{file_name}.tmp-{}", std::process::id()));

        let write_result = (|| -> std::io::Result<()> {
            let mut f = std::fs::File::create(&tmp)?;
            use std::io::Write;
            f.write_all(contents.as_bytes())?;
            f.sync_all()?;
            Ok(())
        })();
        if let Err(e) = write_result {
            let _ = std::fs::remove_file(&tmp);
            return Err(TixError::Io(e));
        }

        if let Err(e) = std::fs::rename(&tmp, path) {
            let _ = std::fs::remove_file(&tmp);
            return Err(TixError::Io(e));
        }
        Ok(())
    }
}

/// Reorder `configurations` to the declaration order of `[kanban.<name>]`
/// section headers in the source document (D-02: declaration order = tab
/// order). The `toml` crate sorts table keys on deserialize, so the parser's
/// order is not trustworthy; this returns to the document's byte order.
fn restore_declaration_order(section: &mut KanbanSection, contents: &str) {
    let mut order: Vec<String> = Vec::new();
    for line in contents.lines() {
        let line = line.trim();
        if let Some(rest) = line.strip_prefix("[").and_then(|s| s.strip_suffix("]")) {
            let mut parts = rest.split('.').map(str::trim);
            if parts.next() == Some("kanban")
                && let Some(name) = parts.next()
                && parts.next().is_none()
                && !order.iter().any(|n| n == name)
            {
                order.push(name.to_string());
            }
        }
    }
    if order.is_empty() {
        return;
    }
    let mut ordered = IndexMap::new();
    for name in &order {
        if let Some(board) = section.configurations.shift_remove(name) {
            ordered.insert(name.clone(), board);
        }
    }
    ordered.extend(
        section
            .configurations
            .iter()
            .map(|(n, b)| (n.clone(), b.clone())),
    );
    section.configurations = ordered;
}

/// Per-configuration validation (NFR-003): non-empty unique non-blank
/// columns, `done_column` ⊆ columns, `hidden_columns` ⊆ columns.
fn validate_board(name: &str, board: &BoardConfiguration) -> Result<()> {
    if board.columns.is_empty() {
        return Err(TixError::Config(format!(
            "`kanban.{name}.columns` must not be empty"
        )));
    }
    if board.columns.iter().any(|c| c.trim().is_empty()) {
        return Err(TixError::Config(format!(
            "`kanban.{name}.columns` must not contain blank names"
        )));
    }
    let mut seen: HashSet<&str> = HashSet::new();
    for column in &board.columns {
        if !seen.insert(column.as_str()) {
            return Err(TixError::Config(format!(
                "`kanban.{name}.columns` must be unique; found duplicate `{column}`"
            )));
        }
    }
    if let Some(done) = &board.done_column
        && !board.columns.contains(done)
    {
        return Err(TixError::Config(format!(
            "`kanban.{name}.done_column` (`{done}`) must be one of the configured columns"
        )));
    }
    for hidden in &board.hidden_columns {
        if !board.columns.contains(hidden) {
            return Err(TixError::Config(format!(
                "`kanban.{name}.hidden_columns` (`{hidden}`) must be a subset of `columns`"
            )));
        }
    }
    if board.title_lines == 0 {
        return Err(TixError::Config(format!(
            "`kanban.{name}.title_lines` must be at least 1"
        )));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;
    use tempfile::TempDir;

    fn write_toml(dir: &Path, contents: &str) -> PathBuf {
        let path = dir.join("tix.toml");
        std::fs::write(&path, contents).unwrap();
        path
    }

    #[test]
    fn defaults_match_contract() {
        let c = Config::default();
        let board = c.default_config();
        assert_eq!(board.columns, ["todo", "in progress", "in review", "done"]);
        assert_eq!(board.done_column.as_deref(), Some("done"));
        assert_eq!(board.hidden_columns, Vec::<String>::new());
        assert!(!board.show_mismatch);
        assert!(board.wrap_titles);
        assert_eq!(board.title_lines, 3);
        assert_eq!(board.order_by, OrderBy::CreatedAtDesc);
        assert_eq!(c.issues_dir, PathBuf::from("docs/issues"));
        assert_eq!(c.editor, None);
        assert_eq!(c.state.next_number, 0);
        assert_eq!(c.export.gitlab, None);
        assert_eq!(c.export.linear, None);
    }

    #[test]
    fn load_returns_defaults_when_file_absent() {
        let tmp = TempDir::new().unwrap();
        let cfg = Config::load(tmp.path()).unwrap();
        assert_eq!(cfg.state.next_number, 0);
        assert_eq!(cfg.default_config().columns.len(), 4);
    }

    #[test]
    fn load_synthesizes_default_config_when_kanban_section_missing() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), "issues_dir = \"docs/issues\"\n");
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(cfg.kanban.configurations.len(), 1);
        assert!(cfg.kanban.configurations.contains_key("default"));
        assert_eq!(cfg.default_config().columns.len(), 4);
    }

    #[test]
    fn load_parses_state_and_keeps_editor_and_remote_targets() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            r#"issues_dir = "tickets"
editor = "nvim"

[kanban.default]
columns = ["todo", "done"]
done_column = "done"

[state]
next_number = 17

[export.gitlab]
project = "acme/tix"
"#,
        );
        let cfg = Config::load_with_warning(&path, |_| panic!("no token, no warning")).unwrap();
        assert_eq!(
            cfg.kanban.configurations.get("default").unwrap().columns,
            ["todo", "done"]
        );
        assert_eq!(cfg.issues_dir, PathBuf::from("tickets"));
        assert_eq!(cfg.editor.as_deref(), Some("nvim"));
        assert_eq!(cfg.state.next_number, 17);
        assert_eq!(
            cfg.export.gitlab.unwrap().project.as_deref(),
            Some("acme/tix")
        );
        assert_eq!(cfg.export.linear, None);
    }

    #[test]
    fn empty_columns_rejected_as_config_error() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), "[kanban.scratch]\ncolumns = []\n");
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
        assert!(err.to_string().contains("kanban.scratch.columns"));
    }

    #[test]
    fn duplicate_columns_rejected_as_config_error() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "[kanban.scratch]\ncolumns = [\"todo\", \"todo\"]\n",
        );
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
        assert!(err.to_string().contains("duplicate"));
    }

    #[test]
    fn blank_column_name_rejected() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "[kanban.scratch]\ncolumns = [\"todo\", \" \"]\n",
        );
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
    }

    #[test]
    fn done_column_must_be_in_columns() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "[kanban.scratch]\ncolumns = [\"todo\", \"in progress\"]\ndone_column = \"in review\"\n",
        );
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
        assert!(err.to_string().contains("kanban.scratch.done_column"));
    }

    #[test]
    fn hidden_columns_must_be_subset_of_columns() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "[kanban.scratch]\ncolumns = [\"todo\", \"done\"]\nhidden_columns = [\"nope\"]\n",
        );
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
        assert!(err.to_string().contains("kanban.scratch.hidden_columns"));
    }

    #[test]
    fn hidden_done_column_loads_fine() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "[kanban.scratch]\ncolumns = [\"todo\", \"done\"]\ndone_column = \"done\"\nhidden_columns = [\"done\"]\n",
        );
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        let board = cfg.kanban.configurations.get("scratch").unwrap();
        assert_eq!(board.done_column.as_deref(), Some("done"));
        assert_eq!(board.hidden_columns, ["done"]);
    }

    #[test]
    fn legacy_top_level_keys_rejected() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), "columns = [\"todo\", \"done\"]\n");
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
        assert!(err.to_string().contains("tix.toml"));
        assert!(err.to_string().contains("columns"));
    }

    #[test]
    fn token_warning_fires_once_per_remote_with_token() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            r#"[export.gitlab]
project = "a/b"
token = "gl-secret"

[export.linear]
team = "Eng"
token = "lin-secret"
"#,
        );
        let mut warnings: Vec<String> = Vec::new();
        let cfg = Config::load_with_warning(&path, |w| warnings.push(w.to_string())).unwrap();
        assert_eq!(warnings.len(), 2);
        assert!(warnings[0].contains("GITLAB_TOKEN"));
        assert!(warnings[1].contains("LINEAR_TOKEN"));
        // token values must never leak into the warning
        for w in &warnings {
            assert!(!w.contains("secret"));
        }
        assert_eq!(
            cfg.export.gitlab.unwrap().token.as_deref(),
            Some("gl-secret")
        );
    }

    #[test]
    fn no_token_means_no_warning() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), "issues_dir = \"docs/issues\"\n");
        let mut fired = false;
        Config::load_with_warning(&path, |_| fired = true).unwrap();
        assert!(!fired);
    }

    #[test]
    fn save_never_writes_the_state_section() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("tix.toml");
        // Simulate a legacy load: `[state].next_number` is kept in memory
        // but must never be written back out (issue #52).
        let mut cfg = Config::default();
        cfg.state.next_number = 42;
        cfg.save(&path).unwrap();

        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(reloaded.state.next_number, 0, "state is never persisted");
        assert_eq!(
            reloaded.default_config().columns,
            cfg.default_config().columns
        );

        let on_disk = std::fs::read_to_string(&path).unwrap();
        assert!(
            !on_disk.contains("next_number"),
            "next_number leaked into tix.toml:\n{on_disk}"
        );
        assert!(
            !on_disk.contains("[state]"),
            "state section written:\n{on_disk}"
        );
    }

    #[test]
    fn multi_config_roundtrip_preserves_declaration_order() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            r#"issues_dir = "docs/issues"

[kanban.release]
columns = ["planned", "in progress", "done"]
done_column = "done"
show_mismatch = true

[kanban.personal]
columns = ["todo", "done"]
done_column = "done"
hidden_columns = ["done"]
"#,
        );
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        let names: Vec<&str> = cfg.configs().map(|(n, _)| n).collect();
        assert_eq!(names, ["release", "personal"]);

        // default_config falls back to the first declared when no "default".
        assert_eq!(
            cfg.default_config().columns,
            ["planned", "in progress", "done"]
        );

        cfg.save(&path).unwrap();
        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(
            cfg, reloaded,
            "order and values survive save/load round trip"
        );
        let names2: Vec<&str> = reloaded.configs().map(|(n, _)| n).collect();
        assert_eq!(names2, ["release", "personal"]);
    }

    #[test]
    fn save_never_serializes_tokens_back_out() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("tix.toml");
        let mut cfg = Config::default();
        cfg.export.gitlab = Some(RemoteConfig {
            token: Some("secret".into()),
            project: Some("a/b".into()),
            ..RemoteConfig::default()
        });
        cfg.save(&path).unwrap();

        let on_disk = std::fs::read_to_string(&path).unwrap();
        assert!(
            !on_disk.contains("secret"),
            "token leaked to disk:\n{on_disk}"
        );
        assert!(
            on_disk.contains("a/b"),
            "non-secret fields survive:\n{on_disk}"
        );

        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(reloaded.export.gitlab.unwrap().token, None);
    }

    #[test]
    fn save_is_atomic_and_leaves_no_temp_file() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("tix.toml");
        Config::default().save(&path).unwrap();
        let entries: Vec<_> = std::fs::read_dir(tmp.path())
            .unwrap()
            .filter_map(|e| e.ok())
            .collect();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].file_name().to_string_lossy(), "tix.toml");
    }

    #[test]
    fn default_loadwrites_are_idempotent() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("tix.toml");
        let cfg = Config::default();
        cfg.save(&path).unwrap();
        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(cfg, reloaded);
    }

    #[test]
    fn effective_done_column_falls_back_to_last() {
        let board = BoardConfiguration {
            columns: vec!["todo".into(), "later".into()],
            done_column: None,
            ..Default::default()
        };
        assert_eq!(board.effective_done_column(), Some("later"));

        let with_done = BoardConfiguration {
            columns: vec!["todo".into(), "done".into(), "later".into()],
            done_column: None,
            ..Default::default()
        };
        assert_eq!(with_done.effective_done_column(), Some("done"));
    }

    #[test]
    fn project_root_walks_up_the_tree() {
        let tmp = TempDir::new().unwrap();
        let nested = tmp.path().join("a").join("b");
        std::fs::create_dir_all(&nested).unwrap();
        std::fs::write(tmp.path().join("tix.toml"), "issues_dir = \"tix\"\n").unwrap();

        assert_eq!(
            Config::project_root(&nested),
            Some(tmp.path().to_path_buf())
        );
        assert_eq!(
            Config::project_root(tmp.path()),
            Some(tmp.path().to_path_buf())
        );
    }

    #[test]
    fn project_root_is_none_when_no_toml_exists() {
        let tmp = TempDir::new().unwrap();
        assert_eq!(Config::project_root(tmp.path()), None);
    }

    #[test]
    fn order_by_parses_all_names_and_defaults_to_desc() {
        let tmp = TempDir::new().unwrap();
        for name in ["created_at_desc", "created_at_asc", "none"] {
            let path = write_toml(
                tmp.path(),
                &format!(
                    "[kanban.x]\ncolumns = [\"todo\", \"done\"]\ndone_column = \"done\"\norder_by = \"{name}\"\n"
                ),
            );
            let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
            let board = cfg.kanban.configurations.get("x").unwrap();
            assert_eq!(board.order_by.as_str(), name);
        }
        assert_eq!(OrderBy::default(), OrderBy::CreatedAtDesc);
        assert_eq!(OrderBy::CreatedAtDesc.next(), OrderBy::CreatedAtAsc);
        assert_eq!(OrderBy::CreatedAtAsc.next(), OrderBy::None);
        assert_eq!(OrderBy::None.next(), OrderBy::CreatedAtDesc);
    }

    #[test]
    fn zero_title_lines_rejected_as_config_error() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "[kanban.scratch]\ncolumns = [\"todo\", \"done\"]\ndone_column = \"done\"\ntitle_lines = 0\n",
        );
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
        assert!(
            err.to_string().contains("kanban.scratch.title_lines"),
            "error names the offending field: {err}"
        );
    }

    #[test]
    fn unknown_order_by_rejected_as_config_error() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "[kanban.scratch]\ncolumns = [\"todo\", \"done\"]\ndone_column = \"done\"\norder_by = \"bogus\"\n",
        );
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
    }

    #[test]
    fn board_without_display_keys_loads_default_display_settings() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "[kanban.default]\ncolumns = [\"todo\", \"done\"]\n",
        );
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        let board = cfg.default_config();
        assert!(board.wrap_titles);
        assert_eq!(board.title_lines, 3);
        assert_eq!(board.order_by, OrderBy::CreatedAtDesc);
    }

    #[test]
    fn display_settings_roundtrip_through_save() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("tix.toml");
        let mut cfg = Config::default();
        {
            let board = cfg.kanban.configurations.get_mut("default").unwrap();
            board.wrap_titles = false;
            board.title_lines = 5;
            board.order_by = OrderBy::None;
        }
        cfg.save(&path).unwrap();
        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(
            reloaded, cfg,
            "display settings survive save/load round trip"
        );
        let on_disk = std::fs::read_to_string(&path).unwrap();
        for key in ["wrap_titles", "title_lines", "order_by"] {
            assert!(on_disk.contains(key), "missing `{key}` in:\n{on_disk}");
        }
    }
}