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
//! `tix lint`: validate frontmatter option values in every issue file
//! (`contracts/cli.md` §lint, FR-015..FR-018).
//!
//! Checks per issue (FR-016): `status` ∈ `tix.toml [columns]`, `priority` ∈
//! {low, medium, high}, `created`/`updated` parse as `YYYY-MM-DD`, `estimate`
//! absent-or-numeric, `number` integer. Unknown frontmatter keys are never
//! flagged.
//!
//! Lint walks the store itself (mirroring [`crate::storage::Store::list`]
//! layout: one segment level + flat root, skipping `.tix-tmp-*` dirs and
//! non-`.md` files) instead of calling [`Store::list`], because `list` abort
//! on the first malformed file. Lint must keep scanning and report each
//! broken file as a `missing`/`parse` diagnostic — never a panic (FR-018).
//!
//! Diagnostics render through `annotate-snippets` (C-004): one rustc-style
//! block per finding, and every block names the file, line, offending value
//! and valid set in a single reading (NFR-006). Diagnostics go to **stderr**;
//! stdout stays parseable and only carries the `Lint OK: N issues checked.`
//! summary on a healthy store. Exit semantics live at the CLI boundary
//! (`cli::run_lint`): `0` healthy, `1` findings, `2` usage/internal.

use std::fs;
use std::ops::Range;
use std::path::Path;

use annotate_snippets::{AnnotationKind, Group, Level, Renderer, Snippet};

use crate::config::Config;
use crate::error::{Result, TixError};
use crate::model::{Issue, Priority};
use crate::storage::Store;

/// One lint finding, carrying enough location to render a rustc-style
/// diagnostic (NFR-006). `line`/`column` are 1-based; file-level findings
/// (`missing`/`parse`) use `line == 0`.
#[derive(Debug)]
pub struct TixIssueFinding {
    /// Issue file, relative to the issues dir.
    pub file: String,
    /// 1-based line of the offending value; `0` for file-level findings.
    pub line: usize,
    /// 1-based column of the offending value; `0` for file-level findings.
    pub column: usize,
    /// The offending value (or an empty string for file-level findings).
    pub value: String,
    /// `status`/`priority`/`created`/`updated`/`estimate`/`number`/`missing`/`parse`.
    pub kind: String,
    /// Human message, e.g. the valid set or the parse error.
    pub message: String,
}

/// Lint every issue file in the store.
///
/// Returns `true` when at least one finding was reported (the CLI boundary
/// turns that into exit `1`; `false` stays exit `0`).
pub fn run(config: &Config, store: &Store) -> Result<bool> {
    let findings = collect(config, store)?;
    if findings.is_empty() {
        println!("Lint OK: {} issues checked.", issue_files(store)?.len());
        return Ok(false);
    }
    for finding in &findings {
        render_diagnostic(&store.issues_dir, finding);
    }
    Ok(true)
}

/// The lint core (WP03): walk every issue file and return the raw
/// [`TixIssueFinding`] vector — no rendering, no printing (C-005).
///
/// This is what MCP's `lint_issues` tool (WP04) calls, mapping findings to
/// `structuredContent`. The validation walk continues past malformed files
/// (`missing`/`parse` findings, FR-018) exactly as the CLI path did; the
/// `annotate-snippets` rendering and the exit-bool semantics stay in [`run`].
pub fn collect(config: &Config, store: &Store) -> Result<Vec<TixIssueFinding>> {
    let files = issue_files(store)?;
    let mut findings: Vec<TixIssueFinding> = Vec::new();
    for rel in &files {
        collect_for_file(config, store, rel, &mut findings)?;
    }
    Ok(findings)
}

/// Lint a single issue file by relative path.
pub fn collect_file(config: &Config, store: &Store, rel: &str) -> Result<Vec<TixIssueFinding>> {
    let mut findings = Vec::new();
    collect_for_file(config, store, rel, &mut findings)?;
    Ok(findings)
}

/// Every issue file in the store, mirroring the storage layout exactly:
/// `.md` files at the flat root plus one level of segment dirs, skipping
/// `.tix-tmp-*` marker dirs.
fn issue_files(store: &Store) -> Result<Vec<String>> {
    let mut files: Vec<String> = Vec::new();
    for entry in fs::read_dir(&store.issues_dir)? {
        let entry = entry?;
        let name = entry.file_name().to_string_lossy().to_string();
        let path = entry.path();
        if path.is_dir() {
            if name.starts_with(".tix-tmp-") {
                continue;
            }
            for child in fs::read_dir(&path)? {
                let child = child?;
                if !child.path().is_file() {
                    continue;
                }
                let child_name = child.file_name().to_string_lossy().to_string();
                if !child_name.ends_with(".md") {
                    continue;
                }
                files.push(format!("{name}/{child_name}"));
            }
        } else if path.is_file() && name.ends_with(".md") {
            files.push(name);
        }
    }
    files.sort();
    Ok(files)
}

/// Collect every finding for one issue file: a `missing`/`parse` diagnostic
/// when the file cannot be parsed, otherwise value validation (FR-016).
fn collect_for_file(
    config: &Config,
    store: &Store,
    rel: &str,
    findings: &mut Vec<TixIssueFinding>,
) -> Result<()> {
    let text = match fs::read_to_string(store.issues_dir.join(rel)) {
        Ok(text) => text,
        Err(err) if err.kind() == std::io::ErrorKind::InvalidData => {
            // Non-UTF-8 bytes: a clean diagnostic, keep scanning (FR-018).
            findings.push(TixIssueFinding {
                file: rel.to_string(),
                line: 0,
                column: 0,
                value: String::new(),
                kind: "parse".to_string(),
                message: "file is not valid UTF-8".to_string(),
            });
            return Ok(());
        }
        Err(err) => return Err(TixError::Io(err)),
    };
    let issue = match Issue::parse(&text) {
        Ok(issue) => issue,
        Err(TixError::Parse(msg)) => {
            findings.push(TixIssueFinding {
                file: rel.to_string(),
                line: 0,
                column: 0,
                value: String::new(),
                kind: if text.starts_with("---\n") {
                    "parse".to_string()
                } else {
                    "missing".to_string()
                },
                message: msg,
            });
            return Ok(());
        }
        Err(other) => return Err(other),
    };
    validate_issue(config, rel, &text, &issue, findings);
    Ok(())
}

/// Value validation over the parsed issue; unknown keys are never flagged.
fn validate_issue(
    config: &Config,
    rel: &str,
    text: &str,
    issue: &Issue,
    findings: &mut Vec<TixIssueFinding>,
) {
    let status = issue.status.display();
    let columns = &config.default_config().columns;
    if !columns.iter().any(|c| c == status) {
        findings.push(value_finding(
            rel,
            text,
            "status",
            status,
            format!("valid options: {}", columns.join(", ")),
        ));
    }
    if issue.title.trim().is_empty() {
        findings.push(value_finding(
            rel,
            text,
            "title",
            &issue.title,
            "title is required".to_string(),
        ));
    }
    if let Priority::Other(unknown) = &issue.priority {
        findings.push(value_finding(
            rel,
            text,
            "priority",
            unknown,
            "valid options: low, medium, high".to_string(),
        ));
    }
    if !is_iso_date(&issue.created) {
        findings.push(value_finding(
            rel,
            text,
            "created",
            &issue.created,
            "expected a date in `YYYY-MM-DD` format".to_string(),
        ));
    }
    if !is_iso_date(&issue.updated) {
        findings.push(value_finding(
            rel,
            text,
            "updated",
            &issue.updated,
            "expected a date in `YYYY-MM-DD` format".to_string(),
        ));
    }
    if let Some(estimate) = &issue.estimate
        && estimate.parse::<f64>().is_err()
    {
        findings.push(value_finding(
            rel,
            text,
            "estimate",
            estimate,
            "estimate must be numeric".to_string(),
        ));
    }
    for link in &issue.links {
        if link.parse::<u32>().is_err() {
            findings.push(value_finding(
                rel,
                text,
                "links",
                link,
                "links must be issue numbers".to_string(),
            ));
        }
    }
}

/// A value finding, located by scanning the raw frontmatter (serde_yaml
/// loses spans, so the line/column come from the source text itself).
fn value_finding(
    rel: &str,
    text: &str,
    kind: &str,
    value: &str,
    message: String,
) -> TixIssueFinding {
    let (line, column) = locate_value(text, kind)
        .map(|l| (l.line, l.column))
        .unwrap_or((0, 0));
    TixIssueFinding {
        file: rel.to_string(),
        line,
        column,
        value: value.to_string(),
        kind: kind.to_string(),
        message,
    }
}

/// The 1-based line/column of the raw `key:` value inside the frontmatter
/// block (before the closing `---` delimiter), if present.
fn locate_value(text: &str, key: &str) -> Option<Located> {
    let prefix = format!("{key}:");
    let fm_end = text[4..].find("\n---").map(|i| i + 4).unwrap_or(text.len());
    let fm = &text[..fm_end];
    let mut line_start = 0usize;
    for (idx, line) in fm.split_inclusive('\n').enumerate() {
        let content = line.trim_end_matches(['\n', '\r']);
        if let Some(rest) = content.trim_start().strip_prefix(&prefix) {
            let pad = content.len() - content.trim_start().len();
            let value_skip = rest.len() - rest.trim_start().len();
            let start = line_start + pad + prefix.len() + value_skip;
            return Some(Located {
                line: idx + 1,
                column: start - line_start + 1,
                start,
                end: line_start + content.len(),
            });
        }
        line_start += line.len();
    }
    None
}

/// Byte location of a value within a frontmatter block.
struct Located {
    line: usize,
    column: usize,
    start: usize,
    end: usize,
}

/// A strict `YYYY-MM-DD` calendar-date check (shape + month 1..=12, day
/// 1..=31), so `2026-13-99` is flagged as malformed.
fn is_iso_date(s: &str) -> bool {
    let b = s.as_bytes();
    if b.len() != 10 || b[4] != b'-' || b[7] != b'-' {
        return false;
    }
    for &c in &b[0..4] {
        if !c.is_ascii_digit() {
            return false;
        }
    }
    for &c in &[b[5], b[6], b[8], b[9]] {
        if !c.is_ascii_digit() {
            return false;
        }
    }
    let month = u32::from(b[5] - b'0') * 10 + u32::from(b[6] - b'0');
    let day = u32::from(b[8] - b'0') * 10 + u32::from(b[9] - b'0');
    (1..=12).contains(&month) && (1..=31).contains(&day)
}

/// Render one finding as a rustc-style diagnostic to stderr (C-004). The
/// header names the field/value; the origin and annotation label name the
/// file, line and valid set in a single reading (NFR-006).
fn render_diagnostic(issues_dir: &Path, f: &TixIssueFinding) {
    let renderer = Renderer::styled();
    let title = match f.kind.as_str() {
        "missing" => "missing frontmatter".to_string(),
        "parse" => "parse error".to_string(),
        _ => format!("invalid {} value '{}'", f.kind, f.value),
    };
    let text = fs::read_to_string(issues_dir.join(&f.file)).ok();
    let group = match text {
        Some(text) => Level::ERROR.primary_title(title).id("E-tix-lint").element(
            Snippet::source(text.clone())
                .line_start(1)
                .path(&f.file)
                .annotation(
                    AnnotationKind::Primary
                        .span(span_for(f, &text))
                        .label(&f.message),
                ),
        ),
        None => Group::with_title(
            Level::ERROR
                .primary_title(format!("{}: {title}", f.file))
                .id("E-tix-lint"),
        ),
    };
    eprintln!("{}", renderer.render(&[group]));
}

/// The byte span (into the full file text) the diagnostic points at.
fn span_for(f: &TixIssueFinding, text: &str) -> Range<usize> {
    if f.line > 0 {
        if let Some(loc) = locate_value(text, &f.kind) {
            return loc.start..loc.end;
        }
        return 0..text.len();
    }
    // File-level findings (missing/parse) annotate the first line.
    let first = text.lines().next().map(str::len).unwrap_or(0);
    0..if first > 0 { first } else { text.len() }
}

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

    fn make_store() -> (TempDir, Store) {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("issues");
        fs::create_dir_all(&dir).unwrap();
        let config_path = tmp.path().join("tix.toml");
        let config = crate::config::Config {
            issues_dir: dir.clone(),
            ..crate::config::Config::default()
        };
        config.save(&config_path).unwrap();
        let config = crate::config::Config::load_with_warning(&config_path, |_| {}).unwrap();
        (
            tmp,
            Store {
                issues_dir: dir,
                config,
            },
        )
    }

    fn write(store: &Store, name: &str, contents: &str) {
        if let Some(dir) = name.rsplit_once('/').map(|(d, _)| d) {
            fs::create_dir_all(store.issues_dir.join(dir)).unwrap();
        }
        fs::write(store.issues_dir.join(name), contents).unwrap();
    }

    const CLEAN: &str = "---\nnumber: 1\ntitle: \"A clean issue\"\nstatus: todo\npriority: medium\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody.\n";

    #[test]
    fn collect_is_empty_on_a_clean_store() {
        let (tmp, store) = make_store();
        let _ = tmp;
        write(&store, "alice/2026-01-01-clean.md", CLEAN);
        let findings = collect(&store.config, &store).unwrap();
        assert!(findings.is_empty());
    }

    #[test]
    fn collect_flags_invalid_status_and_priority() {
        let (tmp, store) = make_store();
        let _ = tmp;
        write(
            &store,
            "alice/2026-01-01-broken.md",
            "---\nnumber: 2\ntitle: \"Broken\"\nstatus: shipped\npriority: critical\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody.\n",
        );
        let findings = collect(&store.config, &store).unwrap();
        let kinds: Vec<&str> = findings.iter().map(|f| f.kind.as_str()).collect();
        assert!(
            kinds.contains(&"status"),
            "unknown status must be flagged, got {kinds:?}"
        );
        assert!(
            kinds.contains(&"priority"),
            "unknown priority must be flagged, got {kinds:?}"
        );
        assert!(
            findings.iter().any(|f| f.kind == "status"
                && f.message
                    .contains("valid options: todo, in progress, in review, done")),
            "status finding must name the valid set, got {findings:?}"
        );
    }

    #[test]
    fn collect_flags_non_numeric_link_entries() {
        let (tmp, store) = make_store();
        let _ = tmp;
        write(
            &store,
            "alice/2026-01-01-linked.md",
            "---\nnumber: 3\ntitle: \"Linked\"\nstatus: todo\npriority: medium\nlinks:\n- '12'\n- task-7\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody.\n",
        );
        let findings = collect(&store.config, &store).unwrap();
        let links_findings: Vec<&TixIssueFinding> =
            findings.iter().filter(|f| f.kind == "links").collect();
        assert_eq!(links_findings.len(), 1, "got {findings:?}");
        assert_eq!(links_findings[0].value, "task-7");
        assert!(
            links_findings[0].line > 0,
            "links finding must be located in the frontmatter"
        );
        assert!(
            findings.iter().all(|f| f.kind == "links"
                || ["status", "priority", "created", "updated", "number"]
                    .contains(&f.kind.as_str())),
            "numeric links entries must not be flagged, got {findings:?}"
        );
    }

    #[test]
    fn collect_reports_unparseable_file_as_missing_finding() {
        let (tmp, store) = make_store();
        let _ = tmp;
        write(
            &store,
            "alice/2026-01-01-not-frontmatter.md",
            "Just prose, no frontmatter.\n",
        );
        let findings = collect(&store.config, &store).unwrap();
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].kind, "missing");
        assert_eq!(findings[0].file, "alice/2026-01-01-not-frontmatter.md");
    }
}