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
//! The portable health document: one versioned DTO carrying everything health
//! knows, so the CLI, the TUI, MCP, and an export file all describe the same facts
//! (mission `project-issue-health-status-01M3C8HX`, WP04 T020/T021).
//!
//! # One DTO, or four opinions
//!
//! C-007 requires the CLI, the TUI, MCP, and the portable surfaces to consume **one**
//! health DTO. This is it. A surface renders it; a surface does not recompute it. The
//! consequence that matters is that `tix health --json`, the MCP `health` tool, and
//! `tix export --target health` cannot disagree, because there is no second
//! implementation to drift.
//!
//! # Loss-aware, not lossless-by-accident
//!
//! The document preserves the current state, its raw recorded value even when this
//! build cannot read it, the policy version, the events, the derived rollup with its
//! contributors, and every diagnostic. It also carries the fields a *future* build
//! adds: `#[serde(flatten)] extensions` keeps unknown keys verbatim, exactly as the
//! views document does for the same reason — a round trip through a build that
//! predates a field must not delete it (C-008).
//!
//! # Round trips are idempotent
//!
//! `document → JSON → document → JSON` is byte-stable: [`PortableHealth::from_json`]
//! re-derives the diagnostics this build can see from the data it read and merges
//! them into the ones the document carried, *recognizing* an equivalent diagnostic
//! rather than appending a duplicate ([`HealthDiagnostic::same_as`]). Without that,
//! every round trip would grow the diagnostic list — which is the difference between
//! a document that can be committed and one that cannot.

use serde::{Deserialize, Serialize};
use toml::Table;

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

use super::diagnostics::{HealthDiagnostic, HealthDiagnosticKind, RemoteTarget};
use super::events::{HealthScope, HealthSource, project};
use super::index::HealthIndex;
use super::policy::HealthPolicy;
use super::rollup::{Contribution, HealthRollup, rollup};
use super::state::HealthState;

/// The document's format marker.
pub const FORMAT: &str = "tix-health";

/// The document's format version. Bumped when the shape changes incompatibly.
pub const VERSION: u32 = 1;

/// Everything health knows, in one versioned document (T020).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PortableHealth {
    /// The format marker: [`FORMAT`].
    pub format: String,
    /// The format version: [`VERSION`].
    pub version: u32,
    /// The policy version every derived value in this document was computed under.
    pub policy_version: String,
    /// One entry per scope, in a stable order.
    #[serde(default)]
    pub scopes: Vec<PortableScopeHealth>,
    /// Every diagnostic, in a stable order.
    #[serde(default)]
    pub diagnostics: Vec<PortableHealthDiagnostic>,
    /// Keys this build does not interpret, preserved verbatim.
    #[serde(flatten)]
    pub extensions: Table,
}

/// One scope's health, as a surface or a file sees it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PortableScopeHealth {
    /// The scope's canonical spelling (`issue:42`, `cycle:2026-10`). A stable id,
    /// never a display name (C-002).
    pub scope: String,
    /// The state to display.
    pub state: String,
    /// How the value was obtained (`current`, `derived`, `override`).
    pub source: String,
    /// The policy version the *file* records, when it records one.
    #[serde(default)]
    pub recorded_policy_version: Option<String>,
    /// When the value was last updated, when the file says.
    #[serde(default)]
    pub updated_at: Option<String>,
    /// The raw stored value — including one this build cannot read, so a round trip
    /// through this build preserves what it does not understand (C-008).
    #[serde(default)]
    pub recorded: Option<String>,
    /// The health History entries about this scope, verbatim.
    #[serde(default)]
    pub events: Vec<PortableHealthEvent>,
    /// The derived rollup, when the scope has contributors.
    #[serde(default)]
    pub rollup: Option<PortableRollup>,
}

/// One health History entry, preserved exactly as the issue records it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PortableHealthEvent {
    /// The entry's kind (`health_updated`, `health_overridden`).
    pub kind: String,
    /// When it happened, RFC 3339, as recorded.
    pub timestamp: String,
    /// Who did it, as recorded.
    pub actor: String,
    /// The entry's detail, verbatim — this build does not re-parse it, so it cannot
    /// lose what it does not understand.
    pub detail: String,
}

/// A derived rollup, with its contributors.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PortableRollup {
    /// The derived state.
    pub state: String,
    /// The policy version it was derived under.
    pub policy_version: String,
    /// How the state was obtained.
    pub source: String,
    /// The contributors, in issue order.
    #[serde(default)]
    pub contributors: Vec<PortableContribution>,
}

/// One contributor to a rollup.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PortableContribution {
    /// The contributing issue.
    pub number: u32,
    /// The state it carries.
    pub state: String,
    /// The raw stored value, when it could not be read.
    #[serde(default)]
    pub recorded: Option<String>,
}

/// One diagnostic, in the wire vocabulary (C-007's shared DTO).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PortableHealthDiagnostic {
    /// The stable contract name (see [`HealthDiagnosticKind::ALL`]).
    pub kind: String,
    /// The scope's canonical spelling.
    pub scope: String,
    /// The unresolved reference, when there is one.
    #[serde(default)]
    pub reference: Option<String>,
    /// The field the problem sits at, when there is one.
    #[serde(default)]
    pub field: Option<String>,
    /// The remote target, when the problem is about a mapping.
    #[serde(default)]
    pub target: Option<String>,
    /// The raw recorded state, when the file records one this build cannot read.
    #[serde(default)]
    pub state: Option<String>,
    /// What is wrong.
    pub message: String,
    /// What to do about it.
    #[serde(default)]
    pub remedy: Option<String>,
}

impl PortableHealthDiagnostic {
    /// Project a diagnostic into the wire vocabulary.
    pub fn from_diagnostic(diagnostic: &HealthDiagnostic) -> Self {
        Self {
            kind: diagnostic.kind.as_str().to_string(),
            scope: diagnostic.scope.as_str(),
            reference: diagnostic.reference.clone(),
            field: diagnostic.field.clone(),
            target: diagnostic.target.map(|target| target.as_str().to_string()),
            state: diagnostic.state.clone(),
            message: diagnostic.message.clone(),
            remedy: diagnostic.remedy.clone(),
        }
    }

    /// Read the wire vocabulary back into a diagnostic.
    ///
    /// A kind this build does not know is read as [`HealthDiagnosticKind::PolicyMismatch`]
    /// — the value is kept, and the fact that this build cannot interpret it is
    /// itself the diagnostic — never dropped (C-008).
    pub fn to_diagnostic(&self) -> HealthDiagnostic {
        let kind = HealthDiagnosticKind::ALL
            .into_iter()
            .find(|kind| kind.as_str() == self.kind)
            .unwrap_or(HealthDiagnosticKind::PolicyMismatch);
        // A scope spelling this build does not know is kept as a reference rather
        // than dropped: the diagnostic survives, and it says which scope it could
        // not read (C-008).
        let scope = HealthScope::parse(&self.scope).unwrap_or(HealthScope::Issue(0));
        let target = RemoteTarget::ALL
            .into_iter()
            .find(|candidate| Some(candidate.as_str().to_string()) == self.target);
        let mut diagnostic = HealthDiagnostic::new(kind, scope, self.message.clone());
        diagnostic.reference = self.reference.clone().or_else(|| {
            HealthScope::parse(&self.scope)
                .is_none()
                .then(|| self.scope.clone())
        });
        diagnostic.field = self.field.clone();
        diagnostic.target = target;
        diagnostic.state = self.state.clone();
        diagnostic.remedy = self.remedy.clone();
        diagnostic
    }

    /// Whether two entries describe the same diagnostic.
    pub fn same_as(&self, other: &Self) -> bool {
        self == other
    }
}

impl PortableHealth {
    /// Build the document from a repository's issues (T020).
    ///
    /// One pass builds the index; every scope with contributors gets a rollup; and
    /// each issue's health History entries are carried verbatim. Nothing is
    /// recomputed from the remote, and no file is written.
    pub fn build(
        issues: &[Issue],
        cycles: &[String],
        milestones: &[String],
        policy: &HealthPolicy,
    ) -> Self {
        let index = HealthIndex::build(issues, cycles, milestones, policy);
        let mut scopes: Vec<PortableScopeHealth> = Vec::new();

        // A scope per issue that records anything, plus every scope with contributors.
        for issue in issues {
            let view = project(issue, policy);
            let scope = HealthScope::of_issue(issue.number);
            let events: Vec<PortableHealthEvent> = issue
                .history
                .events()
                .into_iter()
                .filter(|entry| {
                    matches!(
                        entry.kind,
                        crate::model::HistoryEventKind::HealthUpdated
                            | crate::model::HistoryEventKind::HealthOverridden
                    )
                })
                .map(|entry| PortableHealthEvent {
                    kind: entry.kind.as_str().to_string(),
                    timestamp: entry.timestamp.clone(),
                    actor: entry.actor.clone(),
                    detail: entry.detail.clone(),
                })
                .collect();
            // Every issue is in the document, including one that records nothing:
            // C-006 requires a legacy issue to display an explicit `unknown`, and a
            // document that omitted it would leave every consumer to invent that
            // entry — which is how four surfaces come to disagree.
            let recorded = view.recorded.clone();
            scopes.push(PortableScopeHealth {
                scope: scope.as_str(),
                state: view.state.as_str().to_string(),
                source: view.source.as_str().to_string(),
                recorded_policy_version: view.policy_version.clone(),
                updated_at: view.updated_at.clone(),
                recorded,
                events,
                rollup: None,
            });
        }

        // One row per issue the repository *has*, plus one per contributing scope (a
        // cycle, a milestone). An issue number the files only mention — a `parent:` that
        // no longer resolves — gets its diagnostic and no row: giving it a row would
        // make a summary count a scope that does not exist.
        let known: std::collections::BTreeSet<u32> =
            issues.iter().map(|issue| issue.number).collect();
        for scope in index.scopes() {
            if let HealthScope::Issue(number) = scope {
                if !known.contains(&number) {
                    continue;
                }
            }
            let derived = rollup(&index, &scope, policy);
            let entry = PortableScopeHealth::from_rollup(&derived);
            match scopes
                .iter_mut()
                .find(|entry| entry.scope == scope.as_str())
            {
                Some(existing) => existing.rollup = entry.rollup,
                None => scopes.push(entry),
            }
        }
        scopes.sort_by(|left, right| left.scope.cmp(&right.scope));

        let mut document = Self {
            format: FORMAT.to_string(),
            version: VERSION,
            policy_version: policy.version().to_string(),
            scopes,
            diagnostics: index
                .diagnostics()
                .iter()
                .map(PortableHealthDiagnostic::from_diagnostic)
                .collect(),
            extensions: Table::new(),
        };
        document.refresh_diagnostics();
        document
    }

    /// Serialize as compact, byte-stable JSON.
    pub fn to_json(&self) -> Result<String> {
        serde_json::to_string(self)
            .map_err(|error| TixError::Parse(format!("portable health document: {error}")))
    }

    /// Serialize as indented JSON — what a human reads.
    pub fn to_json_pretty(&self) -> Result<String> {
        serde_json::to_string_pretty(self)
            .map_err(|error| TixError::Parse(format!("portable health document: {error}")))
    }

    /// Read a portable document, re-deriving what this build can see (T021).
    pub fn from_json(text: &str) -> Result<Self> {
        let mut document: Self = serde_json::from_str(text)
            .map_err(|error| TixError::Parse(format!("portable health document: {error}")))?;
        document.refresh_diagnostics();
        Ok(document)
    }

    /// The diagnostics this document's own data implies.
    ///
    /// Derived, never stored: a rollup's silent contributors and a scope's own
    /// findings are facts about the data, so a document that arrives without them
    /// gains them on read rather than being trusted to have carried them.
    pub fn derived_diagnostics(&self) -> Vec<HealthDiagnostic> {
        let mut derived: Vec<HealthDiagnostic> = Vec::new();
        for scope in &self.scopes {
            let Some(rollup) = &scope.rollup else {
                continue;
            };
            for contributor in &rollup.contributors {
                if contributor.state != HealthState::Unknown.as_str() {
                    continue;
                }
                let scope_id = HealthScope::parse(&scope.scope).unwrap_or(HealthScope::Issue(0));
                let message = match &contributor.recorded {
                    Some(raw) => format!(
                        "issue #{} records health `{raw}`, which this build cannot read",
                        contributor.number
                    ),
                    None => format!("issue #{} records no health", contributor.number),
                };
                let mut diagnostic =
                    HealthDiagnostic::new(HealthDiagnosticKind::UnknownHealth, scope_id, message);
                diagnostic.state = contributor.recorded.clone();
                derived.push(diagnostic);
            }
        }
        derived
    }

    /// Merge the derived diagnostics into the carried ones, without duplicating.
    ///
    /// Idempotent by design (T021): a diagnostic a previous round trip stored is
    /// recognized rather than appended again, so the document stabilizes after one
    /// write instead of growing on every read.
    pub fn refresh_diagnostics(&mut self) {
        let derived = self.derived_diagnostics();
        let derived_wire: Vec<PortableHealthDiagnostic> = derived
            .iter()
            .map(PortableHealthDiagnostic::from_diagnostic)
            .collect();
        let mut merged: Vec<PortableHealthDiagnostic> =
            Vec::with_capacity(self.diagnostics.len() + derived_wire.len());
        for diagnostic in self.diagnostics.iter().chain(derived_wire.iter()) {
            if !merged.iter().any(|seen| seen.same_as(diagnostic)) {
                merged.push(diagnostic.clone());
            }
        }
        self.diagnostics = merged;
    }

    /// One scope's entry.
    pub fn scope(&self, scope: &HealthScope) -> Option<&PortableScopeHealth> {
        let id = scope.as_str();
        self.scopes.iter().find(|entry| entry.scope == id)
    }

    /// The diagnostics about one scope.
    pub fn diagnostics_for(&self, scope: &HealthScope) -> Vec<&PortableHealthDiagnostic> {
        let id = scope.as_str();
        self.diagnostics
            .iter()
            .filter(|diagnostic| diagnostic.scope == id)
            .collect()
    }

    /// Whether this document carries data this build cannot interpret — a newer
    /// policy version, or an unknown diagnostic kind. A surface says so rather than
    /// rendering a value it cannot vouch for (C-008).
    pub fn carries_unknown_data(&self) -> bool {
        let known = HealthDiagnosticKind::ALL.map(HealthDiagnosticKind::as_str);
        self.diagnostics
            .iter()
            .any(|diagnostic| !known.contains(&diagnostic.kind.as_str()))
    }
}

impl PortableScopeHealth {
    /// A scope entry carrying only a derived rollup.
    pub fn from_rollup(derived: &HealthRollup) -> Self {
        Self {
            scope: derived.scope.as_str(),
            state: derived.state.as_str().to_string(),
            source: HealthSource::Derived.as_str().to_string(),
            recorded_policy_version: None,
            updated_at: None,
            recorded: None,
            events: Vec::new(),
            rollup: Some(PortableRollup {
                state: derived.state.as_str().to_string(),
                policy_version: derived.policy_version.clone(),
                source: derived.source.as_str().to_string(),
                contributors: derived.contributions.iter().map(contribution).collect(),
            }),
        }
    }
}

fn contribution(value: &Contribution) -> PortableContribution {
    PortableContribution {
        number: value.number,
        state: value.state.as_str().to_string(),
        recorded: value.recorded.clone(),
    }
}

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

    fn issue(number: u32, parent: Option<u32>, health: Option<&str>) -> Issue {
        let parent = parent.map_or(String::new(), |p| format!("parent: {p}\n"));
        let health = health
            .map(|state| format!("health:\n  state: {state}\n"))
            .unwrap_or_default();
        let contents = format!(
            "---\nnumber: {number}\ntitle: \"Issue {number}\"\nstatus: \"todo\"\n\
             created: \"2026-01-01\"\nupdated: \"2026-01-01\"\n{parent}{health}---\n\nBody.\n"
        );
        let mut issue = Issue::parse(&contents).expect("the fixture parses");
        issue.filename = format!("issue-{number}.md");
        issue
    }

    #[test]
    fn portable_health_round_trips_and_is_idempotent() {
        let policy = HealthPolicy::v1();
        let issues = vec![
            issue(1, None, Some("on_track")),
            issue(2, Some(1), Some("at_risk")),
            issue(3, Some(1), None),
        ];
        let document = PortableHealth::build(&issues, &[], &[], &policy);
        assert_eq!(document.format, FORMAT);
        assert_eq!(document.version, VERSION);
        assert_eq!(document.policy_version, "health-v1");

        let first = document.to_json().expect("serializes");
        let read = PortableHealth::from_json(&first).expect("reads back");
        assert_eq!(
            read, document,
            "the document is a fixed point of the round trip"
        );
        let second = read.to_json().expect("serializes again");
        assert_eq!(first, second, "JSON is byte-stable across round trips");
        assert_eq!(read.diagnostics.len(), document.diagnostics.len());

        // The parent's derived rollup carries its contributors, and the child with
        // no health is named rather than dropped.
        let parent = document.scope(&HealthScope::Issue(1)).expect("the parent");
        let rollup = parent.rollup.as_ref().expect("a derived rollup");
        assert_eq!(rollup.state, "at_risk");
        assert_eq!(rollup.contributors.len(), 2);
        assert_eq!(rollup.contributors[0].number, 2);
        assert!(
            document
                .diagnostics
                .iter()
                .any(|d| d.kind == "unknown_health" && d.scope == "issue:1")
        );
    }

    #[test]
    fn portable_health_preserves_what_this_build_cannot_read() {
        let policy = HealthPolicy::v1();
        let issues = vec![
            issue(1, None, Some("on_track")),
            issue(2, Some(1), Some("from_the_future")),
        ];
        let document = PortableHealth::build(&issues, &[], &[], &policy);
        let child = document.scope(&HealthScope::Issue(2)).expect("the child");
        assert_eq!(child.recorded.as_deref(), Some("from_the_future"));
        assert_eq!(child.state, "unknown");
        assert!(
            document
                .diagnostics
                .iter()
                .any(|d| d.kind == "invalid_state")
        );

        // And an unknown top-level key survives the round trip verbatim.
        let json = document.to_json().expect("serializes");
        let widened = json.replace(
            "\"policy_version\"",
            "\"future_section\":{\"nested\":7},\"policy_version\"",
        );
        let read = PortableHealth::from_json(&widened).expect("reads a newer document");
        assert!(
            read.extensions.contains_key("future_section"),
            "an unknown key is kept, not dropped"
        );
        assert!(
            read.to_json()
                .expect("serializes")
                .contains("future_section")
        );
    }

    #[test]
    fn portable_health_reads_an_unknown_diagnostic_kind_without_losing_it() {
        let document = PortableHealth::from_json(
            r#"{"format":"tix-health","version":1,"policy_version":"health-v9",
                "scopes":[],
                "diagnostics":[{"kind":"invented_by_a_newer_build","scope":"issue:4",
                                "message":"something this build does not know"}]}"#,
        )
        .expect("reads");
        assert!(document.carries_unknown_data());
        let diagnostic = document.diagnostics[0].to_diagnostic();
        assert_eq!(diagnostic.message, "something this build does not know");
        assert_eq!(diagnostic.scope, HealthScope::Issue(4));
        assert_eq!(
            diagnostic.kind,
            HealthDiagnosticKind::PolicyMismatch,
            "an unrecognized kind is reported, not dropped"
        );
    }
}