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
//! The optional `[triage]` section: which normal columns make up the inbox.
//!
//! Contract `triage-state.md` §Configuration, data-model §1. The section is
//! **omitted when absent** — a legacy `tix.toml` loads and saves byte-identically
//! and manual triage stays opt-in through normal status configuration — so
//! [`Config::triage`] is `None` rather than a defaulted section.
//!
//! Every named column is validated through the #183 service and nowhere else
//! (C-002). Nothing here compares a status string against a literal, defines a
//! completion rule, or recognises a column by name: the board's
//! [`CategoryResolution`] is the only thing that knows what a column means.

use serde::{Deserialize, Serialize};

use crate::config::Config;
use crate::error::{Result, TixError};
use crate::workflow::{self, WorkflowCategory};

/// `[triage]`: the normal board columns that make up the triage inbox.
///
/// ```toml
/// [triage]
/// entry_status = "triage"
/// declined_status = "wontfix"
/// # accepted_status = "todo"        # optional
/// # deferred_status = "triage"      # optional; defaults to entry_status
/// ```
///
/// Every field is optional at the serde layer so that even an empty `[triage]`
/// table parses, and [`validate`] is what decides what "present" means. Defaults
/// live in the *meaning* of a field rather than in a materialized value, so a
/// config that relies on one writes no key for it (T005).
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct TriageConfig {
    /// The column that places an issue in the inbox. Required when the section
    /// exists.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub entry_status: Option<String>,
    /// The normal target for an accepted issue, when one is configured.
    ///
    /// Optional by design: accept has an explicit target of its own (WP03) and a
    /// project that has not chosen a distinct one needs no key here.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub accepted_status: Option<String>,
    /// The distinct column a declined issue moves to. Required when the section
    /// exists, and must map to the `canceled` category (C-003).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub declined_status: Option<String>,
    /// The column an issue sits in while deferred.
    ///
    /// Optional: it defaults to [`Self::entry_status`], which is why the default
    /// needs no key on disk — data-model §1 allows the two to be equal, and
    /// equality is the normal case.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deferred_status: Option<String>,
}

impl TriageConfig {
    /// The column an issue sits in while deferred: the configured one, else the
    /// entry status.
    ///
    /// The single place that default is expressed, so validation, the inbox query
    /// (WP02), and the defer decision (WP03) cannot drift into three subtly
    /// different answers about which column is the deferred one.
    #[must_use]
    pub fn effective_deferred_status(&self) -> Option<&str> {
        self.deferred_status
            .as_deref()
            .or(self.entry_status.as_deref())
    }
}

/// Validate `[triage]` against the active board, through #183 (C-002, C-003).
///
/// Called **last** by [`Config::validate`], after the vocabulary and every
/// board's `category_map` have been checked. The order is load-bearing:
/// [`workflow::resolution`] documents its `unreachable!` as reachable only from
/// an unvalidated vocabulary, so running first would hand it precisely the input
/// that fires it.
///
/// An absent section is not a thing to check. `Config::triage == None` *is* the
/// statement that this project does not use the inbox.
pub fn validate(config: &Config) -> Result<()> {
    let Some(triage) = config.triage.as_ref() else {
        return Ok(());
    };

    let entry = required(triage.entry_status.as_deref(), "entry_status")?;
    let declined = required(triage.declined_status.as_deref(), "declined_status")?;

    // Only what was actually written down. `deferred_status` defaults to
    // `entry_status`, which is already in the list, so checking the default again
    // would report one mistake twice — and `accepted_status` is optional, so a
    // config that does not name one has nothing to check.
    let mut named = vec![("entry_status", entry), ("declined_status", declined)];
    if let Some(accepted) = triage.accepted_status.as_deref() {
        named.push(("accepted_status", accepted));
    }
    if let Some(deferred) = triage.deferred_status.as_deref() {
        named.push(("deferred_status", deferred));
    }

    let (board, resolution) = workflow::active_resolution(config);
    for (field, value) in named {
        if resolution.resolve(value).is_none() {
            return Err(TixError::Config(format!(
                "unknown_column: `[triage].{field}` names `{value}`, which is not a \
                 column on board `{board}` ({})",
                resolution.column_list()
            )));
        }
    }

    // T004. `canceled` is terminal and **not** completion, and that pairing is
    // what makes decline a move: a `completed` decline would report the issue as
    // finished, and an archive or delete would answer a different question
    // entirely (C-003). Declining is a column change with a recorded reason.
    let category = resolution
        .resolve(declined)
        .expect("`declined_status` was checked against this resolution above");
    if category != WorkflowCategory::Canceled {
        return Err(TixError::Config(format!(
            "`[triage].declined_status` must map to the `{}` category, but \
             `{declined}` maps to `{}`",
            WorkflowCategory::Canceled.key(),
            category.key()
        )));
    }

    Ok(())
}

/// A required `[triage]` key, named as `[triage].<field>` in its own message.
///
/// Required **when the section exists**, absent when it does not. Writing a
/// default `entry_status` for a project that never asked for an inbox would be
/// the configuration inventing a workflow nobody configured (data-model §1), so
/// the section is checked rather than defaulted.
fn required<'a>(value: Option<&'a str>, field: &str) -> Result<&'a str> {
    match value.map(str::trim) {
        None => Err(TixError::Config(format!(
            "`[triage].{field}` is required when the `[triage]` section is present"
        ))),
        Some("") => Err(TixError::Config(format!(
            "`[triage].{field}` must not be blank"
        ))),
        Some(value) => Ok(value),
    }
}

#[cfg(test)]
mod tests {
    #[allow(clippy::wildcard_imports)]
    use super::*;
    use std::path::Path;
    use tempfile::TempDir;

    /// A board with a column for every decision the inbox can reach.
    ///
    /// The shipped default board has no `canceled` column, and that is deliberate:
    /// decline is opt-in. A fixture needs one, so this declares the `category_map`
    /// a real project would write — including exactly one `completed` column,
    /// which [`crate::config::Config::validate`] requires of any board that
    /// declares a map at all.
    ///
    /// Written as `tix.toml` rather than assembled in Rust so the tests exercise
    /// the same parse → resolve → validate path a user's file takes.
    const BOARD: &str = r#"issues_dir = "docs/issues"

[kanban.default]
columns = ["triage", "todo", "in progress", "in review", "done", "wontfix"]
done_column = "done"
category_map = { triage = "backlog", todo = "unstarted", "in progress" = "active", "in review" = "active", done = "completed", wontfix = "canceled" }
"#;

    /// [`BOARD`] plus a `[triage]` section, ready to validate.
    fn config_with(section: &str) -> Config {
        let text = format!("{BOARD}{section}");
        toml::from_str(&text).expect("fixture is a well-formed tix.toml")
    }

    /// A pre-triage `tix.toml` in the canonical `toml` pretty form.
    ///
    /// Byte-for-byte the shape `legacy_file_roundtrips_byte_identical` in
    /// `config.rs` pins: `tix` may reformat a hand-written file on its first save,
    /// but never again after that, and never by adding a key. The board carries
    /// no key equal to the loader's default — `done_column` is inferred from
    /// `columns` — so the save path omits all of them (#1415).
    const LEGACY: &str = "issues_dir = \"docs/issues\"\n\n\
        [kanban.default]\n\
        columns = [\n    \"todo\",\n    \"in progress\",\n    \"in review\",\n    \"done\",\n]\n";

    fn valid_section() -> &'static str {
        "\n[triage]\nentry_status = \"triage\"\ndeclined_status = \"wontfix\"\n"
    }

    /// The rejection a `[triage]` mistake produces, as text.
    ///
    /// Every assertion below reads the message rather than just `is_err()`,
    /// because a config that fails for the *wrong* reason is a test that passes
    /// while the rule it names is unwritten.
    fn err(config: &Config) -> String {
        config
            .validate()
            .expect_err("this fixture must be rejected")
            .to_string()
    }

    // -- T001: schema --------------------------------------------------------

    #[test]
    fn triage_config_valid_section_loads_and_validates() {
        let config = config_with(valid_section());
        let triage = config.triage.as_ref().expect("the section was written");
        assert_eq!(triage.entry_status.as_deref(), Some("triage"));
        assert_eq!(triage.declined_status.as_deref(), Some("wontfix"));
        assert_eq!(triage.accepted_status, None, "accepted stays optional");
        config.validate().expect("every named column resolves");
    }

    #[test]
    fn triage_config_absent_section_never_materializes() {
        // C-001 / T005: a legacy file must save byte-identically, so the section
        // is `None` rather than a defaulted one that would serialize as `[triage]`.
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("tix.toml");
        std::fs::write(&path, BOARD).unwrap();

        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        assert!(
            config.triage.is_none(),
            "a file with no `[triage]` loads as no inbox"
        );
        config
            .validate()
            .expect("no section means nothing to check");

        config.save(&path).unwrap();
        let first = std::fs::read_to_string(&path).unwrap();
        assert!(
            !first.contains("[triage]") && !first.contains("entry_status"),
            "saving must not add a `[triage]` section:\n{first}"
        );

        // Load → save is a fixpoint: the file does not drift on every run.
        let again = Config::load_with_warning(&path, |_| {}).unwrap();
        again.save(&path).unwrap();
        let second = std::fs::read_to_string(&path).unwrap();
        assert_eq!(
            second, first,
            "a config with no inbox must save byte-stable"
        );
    }

    /// T005, the strongest form: the canonical bytes of a legacy file must come
    /// back byte-identical, `[triage]` included (i.e. absent).
    #[test]
    fn triage_config_legacy_bytes_are_unchanged_by_a_load_save_cycle() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("tix.toml");
        std::fs::write(&path, LEGACY).unwrap();

        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        config.save(&path).unwrap();
        let after = std::fs::read_to_string(&path).unwrap();
        assert_eq!(
            after, LEGACY,
            "the legacy fixture must save byte-identical; no `[triage]` key"
        );
    }

    #[test]
    fn triage_config_rejects_an_unrecognized_key() {
        // A typo must not be silently ignored: an inbox quietly reading the wrong
        // column is worse than a config that refuses to load.
        let result = toml::from_str::<TriageConfig>("entry_staust = \"triage\"");
        assert!(
            result.is_err(),
            "`[triage]` is `deny_unknown_fields`, so `entry_staust` is refused"
        );
    }

    #[test]
    fn triage_config_requires_entry_and_declined_when_section_present() {
        // Present but empty: both required keys are reported by name, one at a
        // time, rather than defaulted to a column nobody configured.
        let config = config_with("\n[triage]\n");
        let message = err(&config);
        assert!(
            message.contains("`[triage].entry_status` is required"),
            "first missing key, got: {message}"
        );

        let config = config_with("\n[triage]\nentry_status = \"triage\"\n");
        let message = err(&config);
        assert!(
            message.contains("`[triage].declined_status` is required"),
            "entry alone is not enough, got: {message}"
        );
    }

    #[test]
    fn triage_config_rejects_a_blank_named_status() {
        let config =
            config_with("\n[triage]\nentry_status = \"   \"\ndeclined_status = \"wontfix\"\n");
        let message = err(&config);
        assert!(
            message.contains("`[triage].entry_status` must not be blank"),
            "whitespace is not a column, got: {message}"
        );
    }

    #[test]
    fn triage_config_rejects_an_unknown_column_and_lists_the_real_ones() {
        let config = config_with(
            "\n[triage]\nentry_status = \"no-such-column\"\ndeclined_status = \"wontfix\"\n",
        );
        let message = err(&config);
        assert!(
            message.contains("unknown_column: "),
            "reuse #183's diagnostic name rather than inventing one, got: {message}"
        );
        assert!(
            message.contains("`[triage].entry_status` names `no-such-column`"),
            "name the field and the value, got: {message}"
        );
        assert!(
            message.contains("triage, todo, in progress, in review, done, wontfix"),
            "a refusal has to say what to type instead, got: {message}"
        );
    }

    #[test]
    fn triage_config_deferred_defaults_to_entry_and_writes_no_key() {
        let triage: TriageConfig =
            toml::from_str("entry_status = \"triage\"\ndeclined_status = \"wontfix\"")
                .expect("parses");
        assert_eq!(
            triage.effective_deferred_status(),
            Some("triage"),
            "an unset deferred status is the entry status (data-model §1)"
        );

        let serialized = toml::to_string_pretty(&triage).expect("serializes");
        assert!(
            !serialized.contains("deferred_status"),
            "the default must not materialize a key (T005):\n{serialized}"
        );

        let triage: TriageConfig = toml::from_str(
            "entry_status = \"triage\"\ndeclined_status = \"wontfix\"\ndeferred_status = \"todo\"",
        )
        .expect("parses");
        assert_eq!(
            triage.effective_deferred_status(),
            Some("todo"),
            "an explicit deferred status wins"
        );
    }

    // -- T004: the declined mapping -----------------------------------------

    #[test]
    fn triage_config_declined_must_map_to_canceled_not_completion() {
        // `done` is the board's completion column: the exact mistake that would
        // make a decline report the issue as finished work.
        let config =
            config_with("\n[triage]\nentry_status = \"triage\"\ndeclined_status = \"done\"\n");
        let message = err(&config);
        assert!(
            message.contains("`[triage].declined_status` must map to the `canceled` category"),
            "a completed decline is refused, got: {message}"
        );
        assert!(
            message.contains("`completed`"),
            "say what it maps to instead, got: {message}"
        );
    }

    #[test]
    fn triage_config_canceled_is_terminal_but_is_never_completion() {
        // The property behind "declining never deletes or archives": `canceled`
        // is where a declined card goes, and it is not `completed`. A declined
        // issue therefore stays an issue — nothing is removed — and is not
        // counted as finished.
        let canceled = WorkflowCategory::Canceled;
        assert!(canceled.is_terminal(), "canceled ends the workflow");
        assert!(
            !canceled.is_complete(),
            "canceled is not completion — the only definition of `complete`"
        );
        assert_ne!(
            canceled,
            WorkflowCategory::Completed,
            "decline and completion are different categories"
        );
    }

    #[test]
    fn triage_config_accepted_is_optional_but_checked_when_named() {
        let config = config_with(valid_section());
        config
            .validate()
            .expect("an unconfigured accept target is fine");

        let text = format!(
            "{BOARD}\n[triage]\nentry_status = \"triage\"\n\
             accepted_status = \"ghost\"\ndeclined_status = \"wontfix\"\n"
        );
        let config: Config = toml::from_str(&text).expect("fixture parses");
        let message = err(&config);
        assert!(
            message.contains("`[triage].accepted_status` names `ghost`"),
            "a named column is checked like any other, got: {message}"
        );
    }

    // -- T005: round trip ----------------------------------------------------

    #[test]
    fn triage_config_section_survives_a_save_and_reload() {
        let config = config_with(valid_section());
        config.validate().expect("validates");

        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("tix.toml");
        config.save(&path).unwrap();

        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(
            reloaded.triage, config.triage,
            "the section round-trips through disk"
        );
        reloaded
            .validate()
            .expect("and still validates after the trip");
    }

    #[test]
    fn triage_config_partial_section_writes_only_what_was_set() {
        // T005: defaults must not materialize keys. `accepted_status` and
        // `deferred_status` are unset here, so neither may appear on disk.
        let config = config_with(valid_section());
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("tix.toml");
        config.save(&path).unwrap();

        let on_disk = std::fs::read_to_string(&path).unwrap();
        let section = on_disk
            .split("[triage]")
            .nth(1)
            .expect("the configured section is written");
        assert!(
            section.contains("entry_status") && section.contains("declined_status"),
            "the required keys are present:\n{on_disk}"
        );
        assert!(
            !section.contains("accepted_status") && !section.contains("deferred_status"),
            "unset optional keys must stay unwritten:\n{on_disk}"
        );
    }

    #[test]
    fn triage_config_save_is_atomic_and_leaves_no_temp_file_behind() {
        // `Config::save` is the atomic temp+rename path; a `[triage]` section
        // must not take a different one.
        let config = config_with(valid_section());
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("tix.toml");
        config.save(&path).unwrap();
        config.save(&path).unwrap();

        let leftovers: Vec<String> = std::fs::read_dir(tmp.path())
            .unwrap()
            .filter_map(|e| e.ok())
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .filter(|name| name.contains(".tmp-"))
            .collect();
        assert!(
            leftovers.is_empty(),
            "a temp file survived the rename: {leftovers:?}"
        );
        assert!(Path::new(&path).exists(), "and the target is intact");
    }
}