tix-tracker 0.10.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
//! `tix initiative` and `tix roadmap`: the CLI surface over WP01–WP03 (mission
//! `roadmap-initiatives-01M3C8SX`, WP04; FR-001–FR-005, C-001–C-008).
//!
//! This module is a **thin adapter**, exactly as [`crate::commands::project`] and
//! [`crate::commands::epic`] are:
//!
//! | concern | owner | how this module reaches it |
//! |---|---|---|
//! | record identity, name uniqueness, dates, reference shape | [`crate::roadmap::registry`] | `create_initiative`, `edit_initiative`, `delete_initiative` |
//! | resolution (stable id first, name convenience) | [`crate::roadmap::registry`] | [`registry::resolve_initiative_id`] |
//! | association + idempotence | [`crate::roadmap::registry`] | [`registry::associate`], [`registry::dissociate`] |
//! | filtering, ordering, summary values, diagnostics | [`crate::roadmap`] | [`RoadmapFilter`], [`projection::project`] |
//! | the atomic write boundary | [`crate::roadmap::registry`] | every mutating call |
//!
//! Four properties are deliberate and are the ones a surface loses most easily:
//!
//! - **Every listing shows the id.** An id is how everything is selected, so
//!   [`initiative_listing_lines`] prints it in a column of its own; a rename can
//!   never be mistaken for a new initiative (C-002).
//! - **The rules live in the service.** This module parses what a user typed and
//!   renders what a service returned; it re-derives no identity, name uniqueness,
//!   date validation, reference shape, ordering, filtering or summary value.
//! - **Plan before write.** Every mutating command validates the whole change
//!   through the registry's atomic boundary, so a refusal leaves `tix.toml`
//!   byte-identical (C-008).
//! - **Join, never blend.** The roadmap rows are rendered straight from the
//!   projection's source-attributed [`InitiativeSummary`] — one contribution per
//!   referenced source entity, with its own value and policy version — never a
//!   locally-derived aggregate (C-004).
//!
//! [`tix initiative`] mutates `tix.toml`, so it is routed by [`crate::cli::run`],
//! the process boundary that owns the mutable config, exactly as `tix project` and
//! `tix epic` are. `tix roadmap` is read-only and is dispatched from
//! [`crate::commands::dispatch`].
//!
//! The renderers ([`initiative_listing_lines`], [`initiative_record_lines`],
//! [`roadmap_row_lines`], [`roadmap_list_lines`], [`roadmap_filter_line`]) are
//! `pub` because they are the **reference** the TUI (WP05) and MCP (WP06) reuse
//! rather than writing a second rendering (contract `cli-surface.md`).

use std::collections::HashSet;
use std::io::IsTerminal;

use super::parse_csv_list;
use crate::cli::{ExitCode, InitiativeCommand, RoadmapCommand};
use crate::config::{Config, InitiativeConfiguration, InitiativeId};
use crate::error::{Result, TixError};
use crate::model::{Issue, Priority};
use crate::projects::Patch;
use crate::roadmap::RoadmapDiagnostic;
use crate::roadmap::filter::RoadmapFilter;
use crate::roadmap::projection::{
    self, ProgressValue, RoadmapProjection, RoadmapRow, RoadmapSources, SummaryContribution,
};
use crate::roadmap::registry::{self, AssociationKind, InitiativeEdit, NewInitiative};
use crate::storage::Store;

// ---------------------------------------------------------------------------
// `tix initiative`
// ---------------------------------------------------------------------------

/// Run one `tix initiative` subcommand.
///
/// A thin adapter over [`crate::roadmap::registry`]: each lifecycle verb is one
/// service call through the atomic boundary, and each listing is a renderer over
/// what the service already decided.
pub fn run_initiative(
    config: &mut Config,
    store: &Store,
    command: &InitiativeCommand,
) -> Result<ExitCode> {
    match command {
        InitiativeCommand::Create {
            name,
            outcome,
            owner,
            status,
            priority,
            labels,
            target_date,
            projects,
            epics,
            milestones,
        } => create(
            config,
            store,
            name,
            outcome.as_deref(),
            owner.as_deref(),
            status.as_deref(),
            priority.as_deref(),
            labels.as_deref(),
            target_date.as_deref(),
            projects.as_deref(),
            epics.as_deref(),
            milestones.as_deref(),
        ),
        InitiativeCommand::Edit {
            reference,
            name,
            outcome,
            owner,
            status,
            priority,
            labels,
            target_date,
            projects,
            epics,
            milestones,
        } => edit(
            config,
            store,
            reference,
            name.as_deref(),
            outcome.as_deref(),
            owner.as_deref(),
            status.as_deref(),
            priority.as_deref(),
            labels.as_deref(),
            target_date.as_deref(),
            projects.as_deref(),
            epics.as_deref(),
            milestones.as_deref(),
        ),
        InitiativeCommand::List => {
            for line in initiative_listing_lines(config) {
                println!("{line}");
            }
            Ok(ExitCode::Success)
        }
        InitiativeCommand::Show { reference } => show(config, reference),
        InitiativeCommand::Delete { reference, yes } => delete(config, store, reference, *yes),
        InitiativeCommand::Associate {
            reference,
            project,
            epic,
            milestone,
        } => associate_or_dereference(
            config,
            store,
            reference,
            "associate",
            project.as_deref(),
            epic.as_deref(),
            milestone.as_deref(),
        ),
        InitiativeCommand::Dereference {
            reference,
            project,
            epic,
            milestone,
        } => associate_or_dereference(
            config,
            store,
            reference,
            "dereference",
            project.as_deref(),
            epic.as_deref(),
            milestone.as_deref(),
        ),
    }
}

/// `tix initiative create <name> [flags]`.
#[allow(clippy::too_many_arguments)]
fn create(
    config: &mut Config,
    store: &Store,
    name: &str,
    outcome: Option<&str>,
    owner: Option<&str>,
    status: Option<&str>,
    priority: Option<&str>,
    labels: Option<&str>,
    target_date: Option<&str>,
    projects: Option<&str>,
    epics: Option<&str>,
    milestones: Option<&str>,
) -> Result<ExitCode> {
    let new = NewInitiative {
        name: name.to_string(),
        outcome: trim_optional(outcome),
        owner: trim_optional(owner),
        status: trim_optional(status),
        priority: priority
            .map(str::trim)
            .filter(|value| !value.is_empty())
            .map(loose_priority),
        labels: labels.map(parse_csv_list).unwrap_or_default(),
        target_date: trim_optional(target_date),
        projects: projects.map(parse_csv_list).unwrap_or_default(),
        epics: epics.map(parse_csv_list).unwrap_or_default(),
        milestones: milestones.map(parse_csv_list).unwrap_or_default(),
        extensions: crate::roadmap::registry::InitiativeExtensions::default(),
    };
    let path = crate::commands::views::config_path(store);
    let id = registry::create_initiative(config, &path, &new)?;
    println!("Created {} ({id})", new.name);
    Ok(ExitCode::Success)
}

/// `tix initiative edit <id> [--field …]`.
///
/// A `--name` change is a **label change only**: [`registry::edit_initiative`]
/// touches the record, never the registry key, so nothing is re-keyed and every
/// association and derived value survives (C-002). An optional text/date flag with
/// a blank value clears it (`--owner ""`), the convention `tix edit` uses.
#[allow(clippy::too_many_arguments)]
fn edit(
    config: &mut Config,
    store: &Store,
    reference: &str,
    name: Option<&str>,
    outcome: Option<&str>,
    owner: Option<&str>,
    status: Option<&str>,
    priority: Option<&str>,
    labels: Option<&str>,
    target_date: Option<&str>,
    projects: Option<&str>,
    epics: Option<&str>,
    milestones: Option<&str>,
) -> Result<ExitCode> {
    if name.is_none()
        && outcome.is_none()
        && owner.is_none()
        && status.is_none()
        && priority.is_none()
        && labels.is_none()
        && target_date.is_none()
        && projects.is_none()
        && epics.is_none()
        && milestones.is_none()
    {
        return Err(initiative_edit_requires_a_field());
    }
    let id = registry::resolve_initiative_id(config, reference)?;
    let edit = InitiativeEdit {
        name: name.map_or(Patch::Unchanged, |value| Patch::Set(value.to_string())),
        outcome: text_patch(outcome),
        owner: text_patch(owner),
        status: text_patch(status),
        priority: priority.map_or(Patch::Unchanged, |value| {
            if value.trim().is_empty() {
                Patch::Clear
            } else {
                Patch::Set(loose_priority(value.trim()))
            }
        }),
        labels: reference_patch(labels),
        target_date: text_patch(target_date),
        projects: reference_patch(projects),
        epics: reference_patch(epics),
        milestones: reference_patch(milestones),
    };
    let path = crate::commands::views::config_path(store);
    registry::edit_initiative(config, &path, &id, &edit)?;
    println!("Updated initiative {id}");
    Ok(ExitCode::Success)
}

/// `tix initiative show <id>` — the record, its metadata and its references.
fn show(config: &Config, reference: &str) -> Result<ExitCode> {
    let id = registry::resolve_initiative_id(config, reference)?;
    let record = registry::get(config, &id).ok_or_else(|| unknown_initiative(reference))?;
    for line in initiative_record_lines(&id, record) {
        println!("{line}");
    }
    Ok(ExitCode::Success)
}

/// `tix initiative delete <id> [--yes]`.
///
/// Removes the registry entry **only**: the record's own references are printed and
/// nothing cascades, so no source entity is touched and no association is silently
/// repaired. Confirmation follows [`crate::commands::delete`] and
/// `tix project delete`: `--yes` skips the prompt and a non-TTY stdin deletes
/// immediately, so the command is scriptable and TTY-free.
fn delete(config: &mut Config, store: &Store, reference: &str, yes: bool) -> Result<ExitCode> {
    let id = registry::resolve_initiative_id(config, reference)?;
    let record = registry::get(config, &id)
        .cloned()
        .ok_or_else(|| unknown_initiative(reference))?;

    let mut confirmed = yes || !std::io::stdin().is_terminal();
    if !confirmed {
        eprint!("Delete initiative '{}' ({id})? [y/N] ", record.name);
        let mut line = String::new();
        std::io::stdin()
            .read_line(&mut line)
            .map_err(TixError::Io)?;
        confirmed = line.trim().eq_ignore_ascii_case("y");
        if !confirmed {
            eprintln!("aborted");
        }
    }
    if !confirmed {
        return Ok(ExitCode::Success);
    }

    let path = crate::commands::views::config_path(store);
    registry::delete_initiative(config, &path, &id)?;
    println!("Deleted initiative {} ({id})", record.name);
    println!(
        "Removed references (nothing cascades): {}",
        reference_inventory(&record)
    );
    Ok(ExitCode::Success)
}

/// `tix initiative associate|dereference <id> --project|--epic|--milestone <ref>`.
///
/// Exactly one kind flag is required: the association kind is part of the record's
/// shape, so guessing which one was meant is worse than asking. The target is
/// shape-checked and — deliberately — **never** resolved: a well-formed id that
/// names nothing is stored and stays diagnosable (C-005). Both verbs are
/// idempotent, through [`registry::associate`]/[`registry::dissociate`].
fn associate_or_dereference(
    config: &mut Config,
    store: &Store,
    reference: &str,
    verb: &str,
    project: Option<&str>,
    epic: Option<&str>,
    milestone: Option<&str>,
) -> Result<ExitCode> {
    let (kind, target) = association_target(verb, project, epic, milestone)?;
    let id = registry::resolve_initiative_id(config, reference)?;
    let path = crate::commands::views::config_path(store);
    if verb == "associate" {
        let changed = registry::associate(config, &path, id.as_str(), kind, &target)?;
        if changed {
            println!("Associated {kind} {target} with initiative {id}");
        } else {
            println!("Already associated: {kind} {target} with initiative {id}");
        }
    } else {
        let changed = registry::dissociate(config, &path, id.as_str(), kind, &target)?;
        if changed {
            println!("Dereferenced {kind} {target} from initiative {id}");
        } else {
            println!("Not associated: {kind} {target} with initiative {id}");
        }
    }
    Ok(ExitCode::Success)
}

// ---------------------------------------------------------------------------
// `tix roadmap`
// ---------------------------------------------------------------------------

/// Run one `tix roadmap` subcommand. Read-only: it borrows `config` and the store.
pub fn run_roadmap(config: &Config, store: &Store, command: &RoadmapCommand) -> Result<ExitCode> {
    match command {
        RoadmapCommand::List {
            from,
            to,
            owner,
            status,
            labels,
            query,
        } => list(
            config,
            store,
            &build_filter(from, to, owner, status, labels, query),
        ),
        RoadmapCommand::Show { reference } => show_roadmap(config, store, reference),
    }
}

/// `tix roadmap list [--from … --to … --owner … --status … --label … --query …]`.
fn list(config: &Config, store: &Store, filter: &RoadmapFilter) -> Result<ExitCode> {
    // The filter's syntax is validated **before** any source snapshot is built or
    // any initiative is projected, so a malformed value refuses with a named
    // diagnostic and no work done (C-007).
    filter.validate()?;
    let issues = store.list_all()?;
    let sources = build_sources(config, store, &issues)?;
    let projection = projection::project(config, &sources, filter)?;
    if let Some(line) = roadmap_filter_line(filter) {
        println!("{line}");
    }
    for line in roadmap_list_lines(&projection) {
        println!("{line}");
    }
    Ok(ExitCode::Success)
}

/// `tix roadmap show <id>` — the single-row detail, in the same rendering as the
/// `list` row so the two cannot disagree.
fn show_roadmap(config: &Config, store: &Store, reference: &str) -> Result<ExitCode> {
    let id = registry::resolve_initiative_id(config, reference)?;
    let issues = store.list_all()?;
    let sources = build_sources(config, store, &issues)?;
    let projection = projection::project(config, &sources, &RoadmapFilter::default())?;
    let row = projection
        .initiatives
        .iter()
        .find(|row| row.id == id.as_str())
        .ok_or_else(|| unknown_initiative(reference))?;
    for line in roadmap_row_lines(row) {
        println!("{line}");
    }
    Ok(ExitCode::Success)
}

/// Build the one normalized filter from the CLI flags (contract §Normalized filter).
fn build_filter(
    from: &Option<String>,
    to: &Option<String>,
    owner: &Option<String>,
    status: &Option<String>,
    labels: &[String],
    query: &Option<String>,
) -> RoadmapFilter {
    RoadmapFilter {
        period_from: from.clone(),
        period_to: to.clone(),
        owner: owner.clone(),
        status: status.clone(),
        labels: labels.to_vec(),
        query: query.clone(),
    }
}

/// Build the once-per-read source snapshot by consuming each owner's read.
///
/// The derived facts are gathered here from their owning services — the planning
/// overdue read, the relationship graph's blocked state, the project assigned
/// read — and never recomputed, exactly as
/// [`crate::commands::view::project_reports`] gathers the project inputs.
///
/// `pub` because every surface that reads a roadmap gathers the **same** inputs
/// here rather than keeping a copy: the CLI's `roadmap list`/`show`, MCP
/// (`roadmap_list`/`roadmap_show`/`roadmap_summary`), the TUI's tab and the
/// portable document (`crate::commands::export::run_roadmap_core`) all call this,
/// and the `tests/mcp.rs` parity rows call it as their by-value reference. A
/// second gathering would be a second definition of the roadmap waiting to drift
/// from the first, which is the equivalence C-007 requires.
pub fn build_sources<'a>(
    config: &Config,
    store: &Store,
    issues: &'a [Issue],
) -> Result<RoadmapSources<'a>> {
    let policy = config.health.policy()?;
    let root = Config::project_root(&store.issues_dir).unwrap_or_else(|| store.issues_dir.clone());
    let planner = crate::planning::Planner::from_config(config.clone(), root);
    let targets = crate::epics::ReferenceTargets::from_planner(&planner)?;
    let overdue: HashSet<u32> = planner
        .overdue_batch(store, &crate::model::today())
        .iter()
        .map(|issue| issue.number)
        .collect();
    let assigned = crate::projects::assigned_keys(issues);
    let (graph_issues, done_column) = store.graph_source()?;
    let views: Vec<crate::relationships::IssueView<'_>> =
        graph_issues.iter().map(Issue::issue_view).collect();
    let graph = crate::relationships::RelationshipGraph::new(&views, &done_column);
    let blocked: HashSet<u32> = graph_issues
        .iter()
        .filter(|issue| graph.blocked_state(issue.number).is_blocked)
        .map(|issue| issue.number)
        .collect();
    let consumed = crate::roadmap::RoadmapConsumed {
        targets,
        done_column,
        assigned,
        overdue,
        blocked,
    };
    Ok(RoadmapSources::new(config, issues, &policy, consumed))
}

// ---------------------------------------------------------------------------
// Renderers — the reference WP05/WP06 reuse
// ---------------------------------------------------------------------------

/// `tix initiative list` rows: `id<TAB>name<TAB>target date<TAB>status`.
///
/// The id is a column of its own rather than a decoration, because selecting by id
/// is the contract and a listing that hides the id makes a rename look like a new
/// initiative (C-002). The target date and status are the metadata that matters for
/// scanning; an absent value is `-`, never blank. One tab-separated row per
/// initiative is greppable and deterministic.
#[must_use]
pub fn initiative_listing_lines(config: &Config) -> Vec<String> {
    registry::ids(config)
        .map(|id| {
            let record = &config.initiatives[id];
            let date = record.target_date.as_deref().unwrap_or("-");
            let status = record.status.as_deref().unwrap_or("-");
            format!("{id}\t{}\t{date}\t{status}", record.name)
        })
        .collect()
}

/// `tix initiative show <id>` lines: one `key: value` line per record field, with
/// an absent optional value rendered `-` and a list joined by `, `.
///
/// The references are shown as recorded, **unresolved**: whether a project, epic or
/// milestone exists is the roadmap projection's and `tix lint`'s job, not this
/// record view's.
#[must_use]
pub fn initiative_record_lines(id: &InitiativeId, record: &InitiativeConfiguration) -> Vec<String> {
    vec![
        format!("id: {id}"),
        format!("name: {}", record.name),
        format!(
            "target date: {}",
            record.target_date.as_deref().unwrap_or("-")
        ),
        format!("status: {}", record.status.as_deref().unwrap_or("-")),
        format!("owner: {}", record.owner.as_deref().unwrap_or("-")),
        format!(
            "priority: {}",
            record
                .priority
                .as_ref()
                .map_or_else(|| "-".to_string(), ToString::to_string)
        ),
        format!("outcome: {}", record.outcome.as_deref().unwrap_or("-")),
        format!("labels: {}", join_or_dash(&record.labels)),
        format!("projects: {}", join_or_dash(&record.projects)),
        format!("epics: {}", join_or_dash(&record.epics)),
        format!("milestones: {}", join_or_dash(&record.milestones)),
    ]
}

/// `tix roadmap list` lines: the ordered rows, each as
/// [`roadmap_row_lines`], separated by one blank line; when the filter selects
/// nothing, the explicit empty state.
#[must_use]
pub fn roadmap_list_lines(projection: &RoadmapProjection) -> Vec<String> {
    if projection.initiatives.is_empty() {
        return vec!["(no initiatives match the roadmap filter)".to_string()];
    }
    let mut lines = Vec::new();
    for (index, row) in projection.initiatives.iter().enumerate() {
        if index > 0 {
            lines.push(String::new());
        }
        lines.extend(roadmap_row_lines(row));
    }
    lines
}

/// One roadmap row's lines, shared by `list` and `show`.
///
/// The header is `id<TAB>name<TAB>target date<TAB>summary state`. The target date
/// is the record's own `YYYY-MM-DD` or the literal **`undated`** — never a blank
/// and never an invented period (C-003). Each contribution line carries the source
/// entity's `<kind>:<id>` provenance, its derived label, its resolution (so a
/// **missing** reference is visible on the row, C-005), its owning service's own
/// progress value, its risk, and its shared policy version — a join, never a
/// blended figure (C-004). An initiative that records nothing prints its explicit
/// empty state rather than a bare header.
#[must_use]
pub fn roadmap_row_lines(row: &RoadmapRow) -> Vec<String> {
    let date = row.target_date.as_deref().unwrap_or("undated");
    let mut lines = vec![format!(
        "{}\t{}\t{}\t{}",
        row.id,
        row.name,
        date,
        row.summary.state.as_str()
    )];
    if row.summary.contributions.is_empty() {
        lines.push(format!(
            "  ({}: no source references)",
            row.summary.state.as_str()
        ));
    } else {
        lines.extend(row.summary.contributions.iter().map(contribution_line));
    }
    lines.extend(row.diagnostics.iter().map(diagnostic_line));
    lines
}

/// The normalized filter context line for `tix roadmap list`, or `None` when the
/// filter narrows nothing (the documented "no filter" value).
///
/// Only the criteria that are set are printed, in a fixed order, so two equal
/// filters render identically on every surface.
#[must_use]
pub fn roadmap_filter_line(filter: &RoadmapFilter) -> Option<String> {
    if filter.is_empty() {
        return None;
    }
    let mut parts: Vec<String> = Vec::new();
    if let Some(value) = &filter.period_from {
        parts.push(format!("from={value}"));
    }
    if let Some(value) = &filter.period_to {
        parts.push(format!("to={value}"));
    }
    if let Some(value) = &filter.owner {
        parts.push(format!("owner={value}"));
    }
    if let Some(value) = &filter.status {
        parts.push(format!("status={value}"));
    }
    if !filter.labels.is_empty() {
        parts.push(format!("labels={}", filter.labels.join(",")));
    }
    if let Some(value) = filter.query.as_deref().filter(|q| !q.trim().is_empty()) {
        parts.push(format!("query={value}"));
    }
    Some(format!("filter: {}", parts.join(" ")))
}

/// One summary contribution line: provenance, label, resolution, the owning
/// service's own value, its risk and its policy version.
fn contribution_line(contribution: &SummaryContribution) -> String {
    let value = match &contribution.progress {
        Some(ProgressValue::Project(report)) => {
            format!("{}/{}", report.progress.done, report.progress.total)
        }
        Some(ProgressValue::Epic(rollup)) => {
            format!("{}/{}", rollup.progress.done, rollup.progress.total)
        }
        None => "-".to_string(),
    };
    let risk = contribution
        .risk
        .as_ref()
        .map_or("-", |rollup| rollup.state.as_str());
    let policy = contribution.policy_version.as_deref().unwrap_or("-");
    format!(
        "  {} ({}) [{}] progress={value} risk={risk} policy={policy}",
        contribution.source_entity(),
        contribution.label,
        contribution.resolution.as_str(),
    )
}

/// One diagnostic line: `! <kind>: <field> <reference> <message>`.
fn diagnostic_line(diagnostic: &RoadmapDiagnostic) -> String {
    let mut location = String::new();
    if let Some(field) = &diagnostic.field {
        location.push_str(&format!(" {field}:"));
    }
    if let Some(reference) = &diagnostic.reference {
        location.push_str(&format!(" `{reference}`"));
    }
    format!(
        "  ! {}:{location} {}",
        diagnostic.kind.as_str(),
        diagnostic.message
    )
}

// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------

/// The refusal `tix initiative edit` prints when no field flag was given.
///
/// A caller with no field change has asked for nothing; naming the flags is better
/// than silently rewriting (or not rewriting) the record.
#[must_use]
pub fn initiative_edit_requires_a_field() -> TixError {
    TixError::InvalidInput("`tix initiative edit` requires at least one field flag".to_string())
}

/// The one-flag association kind, refusing zero or several flags.
fn association_target(
    verb: &str,
    project: Option<&str>,
    epic: Option<&str>,
    milestone: Option<&str>,
) -> Result<(AssociationKind, String)> {
    match (project, epic, milestone) {
        (Some(value), None, None) => Ok((AssociationKind::Project, value.to_string())),
        (None, Some(value), None) => Ok((AssociationKind::Epic, value.to_string())),
        (None, None, Some(value)) => Ok((AssociationKind::Milestone, value.to_string())),
        (None, None, None) => Err(TixError::InvalidInput(format!(
            "`tix initiative {verb}` requires exactly one of `--project`, `--epic`, or `--milestone`"
        ))),
        _ => Err(TixError::InvalidInput(format!(
            "`tix initiative {verb}` accepts only one of `--project`, `--epic`, or `--milestone`"
        ))),
    }
}

/// The `unknown initiative` refusal, worded once so `show`/`delete` agree.
fn unknown_initiative(reference: &str) -> TixError {
    TixError::InvalidInput(format!("unknown initiative `{reference}`"))
}

/// The record's own references, `<field>: <values>`, for the delete report.
///
/// `pub` so the MCP delete tool returns the CLI's own sentence rather than
/// keeping a second rendering of the same inventory (C-007).
#[must_use]
pub fn reference_inventory(record: &InitiativeConfiguration) -> String {
    format!(
        "projects: {}; epics: {}; milestones: {}",
        join_or_dash(&record.projects),
        join_or_dash(&record.epics),
        join_or_dash(&record.milestones),
    )
}

/// The elements joined by `, `, or `-` when the list is empty.
fn join_or_dash(values: &[String]) -> String {
    if values.is_empty() {
        "-".to_string()
    } else {
        values.join(", ")
    }
}

/// A trimmed, non-blank optional string, or `None`.
fn trim_optional(value: Option<&str>) -> Option<String> {
    value
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(str::to_string)
}

/// A blank value clears an optional text field; a written one sets it.
fn text_patch(value: Option<&str>) -> Patch<String> {
    match value {
        None => Patch::Unchanged,
        Some(value) if value.trim().is_empty() => Patch::Clear,
        Some(value) => Patch::Set(value.trim().to_string()),
    }
}

/// A blank value clears a reference list; a written one replaces it.
fn reference_patch(value: Option<&str>) -> Patch<Vec<String>> {
    match value {
        None => Patch::Unchanged,
        Some(value) if value.trim().is_empty() => Patch::Clear,
        Some(value) => Patch::Set(parse_csv_list(value)),
    }
}

/// Parse a priority allowing the forward-compatible unknown spelling.
///
/// The record keeps an unknown priority verbatim (the shared [`Priority`] shape),
/// so validation of the *spelling* is not this adapter's rule.
fn loose_priority(value: &str) -> Priority {
    match value.parse() {
        Ok(priority) => priority,
        Err(never) => match never {},
    }
}