tix-tracker 0.12.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
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
//! `tix health`: the CLI surface over the health library (mission
//! `project-issue-health-status-01M3C8HX`, WP05 T025-T027).
//!
//! # A thin adapter, on purpose
//!
//! Every value this module prints comes from [`crate::health`]'s one DTO — the
//! projection for an issue's own value, the rollup for a scope, the portable document
//! for the whole repository. Nothing here computes a health value, compares two
//! states to decide which is worse, or reads a `health:` block itself: the formula is
//! [`crate::health::HealthPolicy`]'s and the projection is
//! [`crate::health::project`]'s, so the CLI, the TUI and MCP cannot disagree about
//! what a scope's health *is* (C-007).
//!
//! # Mutations are refused before they are applied
//!
//! `set` and `override` build a [`HealthUpdate`], hand it to
//! [`crate::health::validate`], and only then call [`crate::health::apply`] — which
//! is the crate's single health writer. A change missing its actor, its date or its
//! rationale is refused by name having written **nothing**: not the frontmatter, not
//! the History, not `updated` (C-004's "never untracked" rule, read in both
//! directions).
//!
//! # Read-only by default
//!
//! `show`, `rollup`, `history` and `board` read. `override` additionally requires
//! `--confirm`, because layering an override over derived health is a deliberate act
//! about a whole scope, not a correction of one issue.

use std::collections::BTreeMap;

use crate::cli::HealthAction;
use crate::commands::export::run_health_core;
use crate::config::Config;
use crate::error::{Result, TixError};
use crate::health::{
    HealthPolicy, HealthScope, HealthSource, HealthState, HealthUpdate, PortableHealth,
    PortableScopeHealth, apply, project, validate,
};
use crate::model::today;
use crate::storage::{Store, actor_identity};

/// The policy this build implements. A stored value under another version is reported
/// as a `policy_mismatch` diagnostic by the projection, never re-interpreted.
fn policy() -> HealthPolicy {
    HealthPolicy::v1()
}

/// Run one `tix health` action.
pub fn run(config: &Config, store: &Store, action: &HealthAction) -> Result<()> {
    match action {
        HealthAction::Set {
            issue,
            state,
            actor,
            date,
            rationale,
        } => set(
            store,
            issue,
            state,
            actor.as_deref(),
            date.as_deref(),
            rationale.as_deref(),
        ),
        HealthAction::Show { issue } => show(config, store, issue),
        HealthAction::Rollup { scope, id } => {
            let scope = parse_scope(scope, id)?;
            let document = run_health_core(config)?;
            print!("{}", render_rollup(&document, &scope));
            Ok(())
        }
        HealthAction::Override {
            scope,
            id,
            state,
            actor,
            date,
            rationale,
            confirm,
        } => override_scope(
            store,
            scope,
            id,
            state,
            actor.as_deref(),
            date.as_deref(),
            rationale.as_deref(),
            *confirm,
        ),
        HealthAction::History { scope } => {
            let scope = parse_scope("", scope)?;
            let document = run_health_core(config)?;
            print!("{}", render_history(&document, &scope));
            Ok(())
        }
        HealthAction::Board => {
            let document = run_health_core(config)?;
            print!("{}", render_board(&document));
            Ok(())
        }
    }
}

/// `tix health set <issue> --state … --actor … --date … --rationale …`
#[allow(clippy::too_many_arguments)]
fn set(
    store: &Store,
    issue: &str,
    state: &str,
    actor: Option<&str>,
    date: Option<&str>,
    rationale: Option<&str>,
) -> Result<()> {
    let number = store.resolve_issue(issue)?.number;
    mutate(
        store,
        HealthScope::Issue(number),
        state,
        actor,
        date,
        rationale,
        HealthSource::Current,
    )
}

/// `tix health override --scope … --id … --state … --confirm`
#[allow(clippy::too_many_arguments)]
fn override_scope(
    store: &Store,
    scope: &str,
    id: &str,
    state: &str,
    actor: Option<&str>,
    date: Option<&str>,
    rationale: Option<&str>,
    confirm: bool,
) -> Result<()> {
    if !confirm {
        return Err(TixError::InvalidInput(
            "refusing to override derived health without --confirm: an override is an \
             explicit act about a whole scope, and it layers over the derived value \
             rather than replacing it"
                .to_string(),
        ));
    }
    let scope = parse_scope(scope, id)?;
    mutate(
        store,
        scope,
        state,
        actor,
        date,
        rationale,
        HealthSource::Override,
    )
}

/// Record one health value, through the crate's single writer.
///
/// The CLI's `set`/`override`, the TUI's form and MCP's `health_record` all call this,
/// so a value recorded from any surface is the same value, written the same way, in
/// the same History entry — and a refusal leaves every surface's files untouched
/// (C-004, C-007).
///
/// `from` is read through the projection rather than passed in, so the entry's
/// "was → is" cannot disagree with what a surface displayed a moment earlier.
pub fn record(
    store: &Store,
    scope: HealthScope,
    state: &str,
    actor: &str,
    date: &str,
    rationale: &str,
    source: HealthSource,
) -> Result<crate::health::AppliedHealth> {
    let HealthScope::Issue(number) = scope.clone() else {
        return Err(TixError::InvalidInput(format!(
            "`{scope}` has no first-class record in this build, so a health value \
             written for it would have nowhere to live; only an issue carries a \
             `health:` block"
        )));
    };
    let to = HealthState::parse(state).map_err(|error| TixError::InvalidInput(error.render()))?;
    let current = store
        .get(crate::storage::IssueSelector::Number(number))
        .map(|issue| project(&issue, &policy()).state)
        .unwrap_or(HealthState::Unknown);
    let mut update = HealthUpdate::new(
        scope,
        to,
        actor.to_string(),
        date.to_string(),
        rationale.to_string(),
    )
    .from(current);
    update.policy_version = policy().version().to_string();
    update.source = source;
    validate(&update, &policy()).map_err(|error| TixError::InvalidInput(error.render()))?;
    apply(store, number, &update, &policy())
}

/// The one write path: validate, then apply, then say what happened.
#[allow(clippy::too_many_arguments)]
fn mutate(
    store: &Store,
    scope: HealthScope,
    state: &str,
    actor: Option<&str>,
    date: Option<&str>,
    rationale: Option<&str>,
    source: HealthSource,
) -> Result<()> {
    // One writer, and it writes an issue's file: a project, epic, cycle or milestone
    // has no first-class record in this build (mission `saving-…`/`#178`), so a value
    // for one would have nowhere to be recorded and nothing to read it back. That is a
    // refusal naming the fact, not a fabricated store (C-009 forbids undocumented
    // automatic health).
    let HealthScope::Issue(number) = scope.clone() else {
        return Err(TixError::InvalidInput(format!(
            "`{scope}` has no first-class record in this build, so a health value \
             written for it would have nowhere to live; `health set`/`health override` \
             record an issue's health (`--scope issue --id <n>`), and a parent's \
             derived rollup is what `tix health rollup` reports"
        )));
    };
    // Through the shared writer: the CLI, the TUI's form and MCP's `health_record`
    // call the same function, so the three surfaces cannot record a different value
    // or a different History entry.
    let actor = actor.map(str::to_string).unwrap_or_else(actor_identity);
    let date = date.map(str::to_string).unwrap_or_else(today);
    let applied = record(
        store,
        scope,
        state,
        &actor,
        &date,
        rationale.unwrap_or_default(),
        source,
    )?;
    let stored = applied
        .issue
        .health
        .as_ref()
        .and_then(|health| health.state.clone())
        .unwrap_or_default();
    print!(
        "{}",
        render_mutation(number, &stored, source, policy().version())
    );
    Ok(())
}

/// `tix health show <issue>` — the issue's own value, and, when it has children, its
/// derived rollup next to it.
fn show(config: &Config, store: &Store, issue: &str) -> Result<()> {
    let number = store.resolve_issue(issue)?.number;
    let document = run_health_core(config)?;
    let scope = HealthScope::Issue(number);
    if document.scope(&scope).is_none() {
        return Err(TixError::NotFound(format!(
            "no issue #{number} in the health document"
        )));
    }
    print!("{}", render_show(&document, &scope));
    Ok(())
}

/// One scope's value, its derived layer and its diagnostics — the text `tix health
/// show` prints, and the text MCP's `health_scope` returns.
///
/// Shared rather than reimplemented, because the parity contract is about *this*
/// string: an agent reading MCP and a person reading the CLI must see the same
/// characters, and two renderers is how they stop agreeing.
pub fn render_show(document: &PortableHealth, scope: &HealthScope) -> String {
    let mut out = match document.scope(scope) {
        Some(entry) => render_scope(entry),
        None => format!("{}: no health value\n", scope.as_str()),
    };
    match document.scope(scope) {
        Some(entry) if entry.rollup.is_some() => {
            let derived = entry.rollup.as_ref().expect("checked");
            out.push_str(&format!("derived: {}\n", render_derived(derived)));
        }
        Some(_) => out.push_str("derived: (nothing contributes)\n"),
        None => out.push_str("derived: (nothing contributes)\n"),
    }
    for diagnostic in document.diagnostics_for(scope) {
        out.push_str(&format!("{}\n", diagnostic.to_diagnostic().render()));
    }
    out
}

/// The text a mutation prints, shared with MCP's `health_record`.
pub fn render_mutation(
    number: u32,
    state: &str,
    source: HealthSource,
    policy_version: &str,
) -> String {
    format!(
        "issue:{number} {state} {} {policy_version}\nhistory: 1 entry appended\n",
        source.as_str()
    )
}

/// The scope a `--scope`/`--id` pair names.
///
/// `issue` requires a number; the rest take a stable id verbatim, because a project,
/// epic, cycle or milestone id *is* the name this repository stores (C-002).
fn parse_scope(scope: &str, id: &str) -> Result<HealthScope> {
    let kind = if scope.trim().is_empty() {
        // `tix health history <scope-id>` passes the canonical spelling in one
        // argument, which is the form the document uses.
        return HealthScope::parse(id).ok_or_else(|| {
            TixError::InvalidInput(format!(
                "`{id}` is not a scope; expected issue:<n>, project:<id>, epic:<id>, \
                 cycle:<id> or milestone:<id>"
            ))
        });
    } else {
        scope.trim().to_ascii_lowercase()
    };
    let id = id.trim();
    if id.is_empty() {
        return Err(TixError::InvalidInput(format!(
            "--scope {kind} needs a non-empty --id"
        )));
    }
    match kind.as_str() {
        "issue" => id
            .parse::<u32>()
            .map(HealthScope::Issue)
            .map_err(|_| TixError::InvalidInput(format!("`{id}` is not an issue number"))),
        "project" => Ok(HealthScope::Project(id.to_string())),
        "epic" => Ok(HealthScope::Epic(id.to_string())),
        "cycle" => Ok(HealthScope::Cycle(id.to_string())),
        "milestone" => Ok(HealthScope::Milestone(id.to_string())),
        other => Err(TixError::InvalidInput(format!(
            "unknown health scope `{other}`; expected issue, project, epic, cycle or \
             milestone"
        ))),
    }
}

/// One scope's line: state, layer, policy version, the raw value when unreadable.
pub fn render_scope(entry: &PortableScopeHealth) -> String {
    let mut line = format!(
        "{:<16} {:<16} {:<8} {}",
        entry.scope,
        entry.state,
        entry.source,
        entry
            .recorded_policy_version
            .as_deref()
            .unwrap_or("(no policy version recorded)")
    );
    if let Some(recorded) = &entry.recorded {
        if recorded != &entry.state {
            line.push_str(&format!(" recorded `{recorded}`"));
        }
    }
    if let Some(updated) = &entry.updated_at {
        line.push_str(&format!(" updated {updated}"));
    }
    let mut out = format!("{line}\n");
    for event in &entry.events {
        out.push_str(&format!(
            "  {} {} {} {}\n",
            event.timestamp, event.actor, event.kind, event.detail
        ));
    }
    out
}

/// One derived rollup's line: the state, its policy version, its contributors.
pub fn render_derived(rollup: &crate::health::PortableRollup) -> String {
    let contributors: Vec<String> = rollup
        .contributors
        .iter()
        .map(|contributor| format!("#{} {}", contributor.number, contributor.state))
        .collect();
    format!(
        "{} ({}, {}, {} contributor{}: {})",
        rollup.state,
        rollup.policy_version,
        rollup.source,
        rollup.contributors.len(),
        if rollup.contributors.len() == 1 {
            ""
        } else {
            "s"
        },
        if contributors.is_empty() {
            "nothing contributes yet".to_string()
        } else {
            contributors.join(", ")
        }
    )
}

/// `tix health rollup --scope … --id …`
pub fn render_rollup(document: &PortableHealth, scope: &HealthScope) -> String {
    let Some(entry) = document.scope(scope) else {
        // No row for this scope — an issue number nothing in the repository carries.
        // Its *diagnostics* still exist and are what a reader needs, so they are
        // printed rather than replaced by a shrug (C-005).
        let mut out = format!("{}: no health value and no contributors\n", scope.as_str());
        for diagnostic in document.diagnostics_for(scope) {
            out.push_str(&format!("{}\n", diagnostic.to_diagnostic().render()));
        }
        return out;
    };
    let mut out = format!("{}\n", render_scope(entry).trim_end());
    if let Some(derived) = &entry.rollup {
        out.push_str(&format!("derived: {}\n", render_derived(derived)));
    } else {
        out.push_str("derived: (nothing contributes)\n");
    }
    for diagnostic in document.diagnostics_for(scope) {
        out.push_str(&format!("{}\n", diagnostic.to_diagnostic().render()));
    }
    out
}

/// `tix health history <scope>` — the append-only entries, oldest first.
pub fn render_history(document: &PortableHealth, scope: &HealthScope) -> String {
    let Some(entry) = document.scope(scope) else {
        return format!("{}: no health history\n", scope.as_str());
    };
    if entry.events.is_empty() {
        return format!(
            "{}: no health history ({} {} {})\n",
            entry.scope, entry.state, entry.source, "unknown until someone records it"
        );
    }
    let mut out = format!("{}: {} entries\n", entry.scope, entry.events.len());
    for event in &entry.events {
        out.push_str(&format!(
            "{}  {}  {}  {}\n",
            event.timestamp, event.actor, event.kind, event.detail
        ));
    }
    out
}

/// `tix health board` — every scope, its state, and what contributes to it.
pub fn render_board(document: &PortableHealth) -> String {
    let mut out = format!("HEALTH  policy {}\n", document.policy_version);
    let mut with_rollup: Vec<(&PortableScopeHealth, String)> = Vec::new();
    for entry in &document.scopes {
        match &entry.rollup {
            Some(derived) => with_rollup.push((entry, render_derived(derived))),
            None => out.push_str(&format!(
                "{:<16} {:<16} {:<8}\n",
                entry.scope, entry.state, entry.source
            )),
        }
    }
    for (entry, derived) in with_rollup {
        out.push_str(&format!(
            "{:<16} {:<16} {:<8} {}\n",
            entry.scope, entry.state, entry.source, derived
        ));
    }
    if !document.diagnostics.is_empty() {
        out.push_str(&format!("\n{} diagnostics\n", document.diagnostics.len()));
        for diagnostic in &document.diagnostics {
            out.push_str(&format!("{}\n", diagnostic.to_diagnostic().render()));
        }
    }
    out
}

/// The counts a `tix status --health` summary prints, from the same document the
/// other surfaces render (C-007).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct HealthSummary {
    /// How many issue scopes exist.
    pub issues: usize,
    /// How many are in each state, in the vocabulary's order.
    pub by_state: BTreeMap<&'static str, usize>,
    /// How many are derived rollups rather than the issue's own value.
    pub derived: usize,
    /// How many diagnostics the document carries.
    pub diagnostics: usize,
    /// The policy version the document was computed under.
    pub policy_version: String,
}

impl HealthSummary {
    /// Count a document's issue scopes.
    pub fn of(document: &PortableHealth) -> Self {
        let mut summary = Self {
            policy_version: document.policy_version.clone(),
            diagnostics: document.diagnostics.len(),
            ..Self::default()
        };
        for state in HealthState::ALL {
            summary.by_state.insert(state.as_str(), 0);
        }
        summary
            .by_state
            .entry(HealthState::Unknown.as_str())
            .or_insert(0);
        for entry in &document.scopes {
            if !entry.scope.starts_with("issue:") {
                continue;
            }
            summary.issues += 1;
            if entry.source == HealthSource::Derived.as_str() {
                summary.derived += 1;
            }
            let key = HealthState::ALL
                .into_iter()
                .find(|state| state.as_str() == entry.state)
                .unwrap_or(HealthState::Unknown)
                .as_str();
            *summary.by_state.entry(key).or_insert(0) += 1;
        }
        summary
    }

    /// The one line `tix status` and MCP's `board_status` both print.
    pub fn render(&self) -> String {
        let states: Vec<String> = HealthState::ALL
            .into_iter()
            .map(|state| {
                format!(
                    "{} {}",
                    self.by_state.get(state.as_str()).copied().unwrap_or(0),
                    state.as_str()
                )
            })
            .collect();
        // The policy version belongs in the line, not only in the data: a reader
        // comparing two repositories' health has to be able to tell whether the two
        // numbers were derived under the same formula (FR-004, C-005).
        format!(
            "Health ({}): {} issue{} ({}) — {} diagnostic{}\n",
            self.policy_version,
            self.issues,
            if self.issues == 1 { "" } else { "s" },
            states.join(", "),
            self.diagnostics,
            if self.diagnostics == 1 { "" } else { "s" }
        )
    }
}

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

    #[test]
    fn parse_scope_reads_every_scope_kind_and_refuses_the_rest() {
        assert_eq!(parse_scope("issue", "42").unwrap(), HealthScope::Issue(42));
        assert_eq!(
            parse_scope("Project", "p-1").unwrap(),
            HealthScope::Project("p-1".to_string())
        );
        assert_eq!(
            parse_scope("cycle", "2026-10").unwrap(),
            HealthScope::Cycle("2026-10".to_string())
        );
        // The one-argument form the document uses.
        assert_eq!(
            parse_scope("", "milestone:m1").unwrap(),
            HealthScope::Milestone("m1".to_string())
        );
        for (scope, id) in [("issue", "not-a-number"), ("team", "x"), ("issue", "  ")] {
            assert!(parse_scope(scope, id).is_err(), "{scope} {id}");
        }
        assert!(parse_scope("", "nonsense").is_err());
    }

    #[test]
    fn health_summary_counts_every_state_from_the_document() {
        let document = PortableHealth::from_json(
            r#"{"format":"tix-health","version":1,"policy_version":"health-v1",
                "scopes":[
                  {"scope":"issue:1","state":"on_track","source":"current"},
                  {"scope":"issue:2","state":"at_risk","source":"current"},
                  {"scope":"issue:3","state":"unknown","source":"current"},
                  {"scope":"issue:4","state":"at_risk","source":"derived",
                   "rollup":{"state":"at_risk","policy_version":"health-v1",
                             "source":"derived","contributors":[
                               {"number":5,"state":"at_risk"}]}},
                  {"scope":"cycle:2026-10","state":"on_track","source":"derived"}
                ],
                "diagnostics":[]}"#,
        )
        .expect("reads");
        let summary = HealthSummary::of(&document);
        assert_eq!(summary.issues, 4, "only issue scopes are counted");
        assert_eq!(summary.derived, 1);
        assert_eq!(summary.by_state["on_track"], 1);
        assert_eq!(summary.by_state["at_risk"], 2);
        assert_eq!(summary.by_state["unknown"], 1);
        assert_eq!(summary.by_state["needs_attention"], 0);
        let line = summary.render();
        assert!(line.contains("4 issues"), "{line}");
        assert!(line.contains("2 at_risk"), "{line}");
        assert!(line.contains("health-v1"), "{line}");
    }

    #[test]
    fn render_derived_names_contributors_and_the_version() {
        let derived = crate::health::PortableRollup {
            state: "at_risk".to_string(),
            policy_version: "health-v1".to_string(),
            source: "derived".to_string(),
            contributors: vec![
                crate::health::PortableContribution {
                    number: 2,
                    state: "on_track".to_string(),
                    recorded: None,
                },
                crate::health::PortableContribution {
                    number: 3,
                    state: "at_risk".to_string(),
                    recorded: None,
                },
            ],
        };
        let line = render_derived(&derived);
        assert!(
            line.contains("at_risk (health-v1, derived, 2 contributors"),
            "{line}"
        );
        assert!(line.contains("#2 on_track, #3 at_risk"), "{line}");

        let none = crate::health::PortableRollup {
            contributors: Vec::new(),
            ..derived
        };
        assert!(render_derived(&none).contains("nothing contributes yet"));
    }
}