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
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
//! `tix triage` — the inbox queue views and the four decisions (WP05, T023–T027).
//!
//! ```text
//! tix triage list [--age] [--count]
//! tix triage status
//! tix triage accept   <issue> [--reason <text>] [--to <column>] [--actor <id>]
//! tix triage decline  <issue> --reason <text>  [--actor <id>]
//! tix triage duplicate <issue> --of <issue> --reason <text> [--actor <id>]
//! tix triage defer    <issue> --reason <text>  [--actor <id>]
//! tix triage batch --select <list>|--filter <query> --decision <kind> ... [--apply]
//! ```
//!
//! ## This module parses and routes; it validates nothing
//!
//! Every rule a decision carries — which ones need a reason, whether the issue is
//! still in the inbox, whether #183 allows the move, whether the duplicate target
//! exists — is [`crate::triage::decision::DecisionService`]'s, and it is asked
//! through `service.apply`. The CLI's own checks are the ones about *this command
//! line*: two selection grammars, `--to` on a decision that has no target, `--of`
//! naming a duplicate. That split is what makes NFR-003 checkable: the same
//! refusal text and the same stable kind reach `tix`, the TUI and MCP because none
//! of them computes it.
//!
//! ## Queue views are read-only by construction
//!
//! `list` and `status` build one [`crate::search::Corpus`] and call
//! [`crate::triage::inbox::collect`] once. Nothing in their path holds a
//! `&mut Issue`, so "a query writes no files or History" (contract §Queue query)
//! is a property of the types rather than a promise in a comment.
//!
//! ## `--apply`, and why a no-op is not a failure
//!
//! The preview is the default; `--apply` is the confirmation. And an apply in
//! which every item was already in the requested state exits **0**: spec §4's
//! invariant "re-running a batch does not duplicate History events" makes the
//! re-run a supported operation, and a supported operation that reports failure
//! would make the invariant its own bug report. Rejected and failed items still
//! exit non-zero (T026), and every outcome is printed either way.

use std::cmp::Ordering;
use std::collections::BTreeMap;

use crate::bulk::{ApplyReport, FieldChange, ItemOutcome, SelectionScope, SelectionSource};
use crate::cli::{ExitCode, TriageAction};
use crate::commands::bulk::{self, SelectionRequest};
use crate::error::{Result, TixError};
use crate::search::Corpus;
use crate::storage::Store;
use crate::triage::batch;
use crate::triage::inbox::{self, InboxScope, QueueEntry, QueueMetrics};
use crate::triage::{
    DecisionKind, DecisionOutcome, DecisionService, DuplicateTarget, TriageDecision, TriagePlan,
};

// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------

/// Route one `tix triage` action. Returns the exit code because a **batch** has
/// a status rather than an error: a partial apply completes, prints one outcome
/// per selected issue and exits non-zero (T026), which `Result<()>` could not
/// express without throwing the output away.
pub fn run(store: &Store, action: &TriageAction) -> Result<ExitCode> {
    match action {
        TriageAction::List { age, count } => {
            print!("{}", render_list(store, *age, *count)?);
            Ok(ExitCode::Success)
        }
        TriageAction::Status => {
            print!("{}", render_status(store)?);
            Ok(ExitCode::Success)
        }
        TriageAction::Accept {
            issue,
            reason,
            to,
            actor,
        } => decide(
            store,
            DecisionKind::Accept,
            issue,
            reason.as_deref(),
            actor.as_deref(),
            to.as_deref(),
            None,
        ),
        TriageAction::Decline {
            issue,
            reason,
            actor,
        } => decide(
            store,
            DecisionKind::Decline,
            issue,
            reason.as_deref(),
            actor.as_deref(),
            None,
            None,
        ),
        TriageAction::Duplicate {
            issue,
            of,
            reason,
            actor,
        } => decide(
            store,
            DecisionKind::Duplicate,
            issue,
            reason.as_deref(),
            actor.as_deref(),
            None,
            Some(of),
        ),
        TriageAction::Defer {
            issue,
            reason,
            actor,
        } => decide(
            store,
            DecisionKind::Defer,
            issue,
            reason.as_deref(),
            actor.as_deref(),
            None,
            None,
        ),
        TriageAction::Batch {
            select,
            filter,
            decision,
            reason,
            actor,
            of,
            to,
            apply,
        } => run_batch(
            store,
            BatchFlags {
                select: select.as_deref(),
                filter: filter.as_deref(),
                decision,
                reason: reason.as_deref(),
                actor: actor.as_deref(),
                of: of.as_deref(),
                to: to.as_deref(),
                apply: *apply,
            },
        ),
    }
}

/// The inbox, or the refusal every `tix triage` subcommand shares.
///
/// One message for all of them rather than one per verb: the question is the
/// same ("does this project have an inbox?"), and a user who typed `status`
/// instead of `list` should not be told about a defect they would have hit
/// anyway. `inbox::scope` does the validation; this only turns "absent" into an
/// error, because a queue command on a project with no queue is a request
/// nothing can satisfy — not an empty answer.
fn scope_of(store: &Store) -> Result<InboxScope> {
    inbox::scope(&store.config)?.ok_or_else(|| {
        TixError::InvalidInput(
            "`tix triage` needs a `[triage]` section in tix.toml, and this project has none"
                .to_string(),
        )
    })
}

// ---------------------------------------------------------------------------
// T023 — the read-only views
// ---------------------------------------------------------------------------

/// `tix triage list`: the queue, or its counts with `--count`.
///
/// Built from one snapshot and one [`crate::triage::inbox::collect`] pass, so the
/// header's `awaiting`/`deferred` figures cannot disagree with the rows below
/// them (NFR-001: one pass, one set of numbers).
pub fn render_list(store: &Store, by_age: bool, counts_only: bool) -> Result<String> {
    let scope = scope_of(store)?;
    let corpus = Corpus::build(store)?;
    let today = crate::model::today();
    let metrics = inbox::collect(&corpus.issues, &scope, &today);

    let mut out = summary_line(&metrics);
    out.push('\n');
    if counts_only {
        return Ok(out);
    }

    let mut entries: Vec<&QueueEntry<'_>> = metrics.entries.iter().collect();
    if by_age {
        entries.sort_by(|a, b| match (a.age_days, b.age_days) {
            // Oldest first. An unknown age sorts **last** on both ends rather
            // than being coerced to 0: `None` is "nobody recorded when this
            // entered", and sorting it as "entered today" would put the entries
            // nobody can age at the trusted end of an age-ordered queue.
            (Some(x), Some(y)) => y.cmp(&x),
            (Some(_), None) => Ordering::Less,
            (None, Some(_)) => Ordering::Greater,
            (None, None) => Ordering::Equal,
        });
    }
    out.push_str(&row("NUM", "AGE", "TITLE"));
    for entry in entries {
        out.push_str(&row(
            &entry.issue.number.to_string(),
            &age_cell(entry.age_days),
            &entry.issue.title,
        ));
    }
    Ok(out)
}

/// `tix triage status`: the summary the queue view's header is one line of, plus
/// the decision counts and the age histogram.
///
/// Every figure is the service's own — `accepted` is `is_completed`, `declined`
/// is the `canceled` category — so this cannot drift from `tix status` or from
/// what `tix mv` would report (C-002).
pub fn render_status(store: &Store) -> Result<String> {
    let scope = scope_of(store)?;
    let corpus = Corpus::build(store)?;
    let today = crate::model::today();
    let metrics = inbox::collect(&corpus.issues, &scope, &today);

    let mut out = summary_line(&metrics);
    out.push('\n');
    for (label, count) in [
        ("awaiting", metrics.awaiting),
        ("deferred", metrics.deferred),
        ("accepted", metrics.accepted),
        ("declined", metrics.declined),
        ("duplicated", metrics.duplicated),
        ("unknown age", metrics.unknown_age),
    ] {
        out.push_str(&format!("  {label}: {count}\n"));
    }
    let distribution: Vec<String> = metrics
        .age_distribution
        .iter()
        .map(|bucket| format!("{} {}", bucket.label, bucket.count))
        .collect();
    out.push_str(&format!("  age: {}\n", distribution.join(", ")));
    Ok(out)
}

/// The header line `list`, `list --count` and `status` all lead with.
fn summary_line(metrics: &QueueMetrics<'_>) -> String {
    format!(
        "inbox: {} entr{} ({} awaiting, {} deferred)",
        metrics.total,
        if metrics.total == 1 { "y" } else { "ies" },
        metrics.awaiting,
        metrics.deferred
    )
}

/// One aligned `NUM AGE TITLE` row, including the header.
fn row(num: &str, age: &str, title: &str) -> String {
    format!("{num:<4} {age:<8} {title}\n")
}

/// The age cell: a number of days, `today` for zero, `unknown` for no stamp.
///
/// `unknown` rather than `0` or `-`: a reader who sees `0` believes the issue
/// arrived today, and the whole point of [`crate::triage::EntryTime`] is that a
/// missing stamp must not become a confident answer.
fn age_cell(age: Option<i64>) -> String {
    match age {
        Some(0) => "today".to_string(),
        Some(days) => format!("{days}d"),
        None => "unknown".to_string(),
    }
}

// ---------------------------------------------------------------------------
// T024 — one decision, one issue
// ---------------------------------------------------------------------------

/// Apply one decision to one issue and print its outcome and its History line.
///
/// The write is a single [`crate::storage::Store::update`] carrying the issue as
/// the service left it **plus** the typed relation, for the reason WP04's
/// `apply_one` gives: two calls would either double-log the edge or wipe it, and
/// SC-003 counts exactly one event per applied decision.
///
/// A service refusal is reported in the **same per-item shape the batch uses** —
/// `#1 Alpha -> refused: <refusal>` on stdout, exit 1 — rather than as this
/// command's top-level error (tix #1488). The state was already identical on
/// every surface; the two spellings merely disagreed about presentation, and the
/// single-issue spelling was the odd one out (the MCP tools follow the batch
/// shape). A refusal that is *not* about the decision — an unresolvable selector,
/// a missing `[triage]` section — stays a top-level error, because it is about
/// reaching the decision at all rather than about the decision's answer.
#[allow(clippy::too_many_arguments)]
fn decide(
    store: &Store,
    kind: DecisionKind,
    selector: &str,
    reason: Option<&str>,
    actor: Option<&str>,
    to: Option<&str>,
    of: Option<&str>,
) -> Result<ExitCode> {
    let scope = scope_of(store)?;
    let issue = store.resolve_issue(selector)?;

    // The duplicate target, resolved the way every other command resolves a
    // selector: not-found and ambiguity are *this* CLI's existing diagnostics,
    // propagated unwrapped, so `tix triage duplicate 1 --of nope` names the
    // problem the same way `tix view nope` does. The service is handed the
    // identity that resolved, which is what [`DuplicateTarget`] exists for.
    let target = match of {
        Some(raw) => Some(store.resolve_issue(raw)?),
        None => None,
    };

    let service = DecisionService::new(
        &store.config,
        scope,
        match target.as_ref() {
            Some(target) => DuplicateTarget::Resolved(target),
            None => DuplicateTarget::Unknown,
        },
    )?;

    let mut request = TriageDecision::new(
        kind,
        crate::model::utc_now_rfc3339(),
        actor
            .map(str::to_string)
            .unwrap_or_else(crate::storage::actor_identity),
        reason.unwrap_or_default(),
    );
    request.target_status = to.map(str::to_string);
    request.target_issue = target.as_ref().map(|target| target.number);

    // Every refusal below — `missing_reason`, `not_in_triage`,
    // `invalid_transition`, … — is the service's, and it is raised **before**
    // anything is written: `apply` judges first and returns the issue it would
    // write, so a rejected decision cannot have touched a file. It is reported
    // per item, exactly as the batch reports it.
    let outcome = match service.apply(&issue, &request) {
        Ok(outcome) => outcome,
        Err(refusal) => {
            println!(
                "{}",
                ItemOutcome::Rejected(refusal.to_string()).as_line(issue.number, &issue.title)
            );
            return Ok(ExitCode::UsageConfig);
        }
    };
    match outcome {
        DecisionOutcome::NoOp => {
            // No History line: SC-003 says a no-op appends none, and printing
            // one would describe an event that does not exist.
            println!("{}", ItemOutcome::NoOp.as_line(issue.number, &issue.title));
            Ok(ExitCode::Success)
        }
        DecisionOutcome::Applied {
            issue: updated,
            event,
            relation,
        } => {
            let mut written = updated;
            if let Some(relation) = relation {
                written.relationships.push(relation);
            }
            let number = written.number;
            let title = written.title.clone();
            let filename = written.filename.clone();
            // One transaction for the decision's write (#1580): `update` writes
            // the file and then reconciles its location, so the two mutations are
            // one unit and a failed reconcile does not leave the decision
            // committed at the old path.
            let filename = store.transaction(|| store.update(&filename, &written))?;
            println!(
                "{}",
                ItemOutcome::Applied { filename }.as_line(number, &title)
            );
            println!("history: {} ({})", event.kind.as_str(), event.detail);
            Ok(ExitCode::Success)
        }
    }
}

// ---------------------------------------------------------------------------
// T025/T026 — one decision, many issues
// ---------------------------------------------------------------------------

/// The `tix triage batch` flags, bundled so the runner is a two-argument
/// function. Borrowed from the parsed command, so nothing is copied that the
/// parser still owns.
struct BatchFlags<'a> {
    select: Option<&'a str>,
    filter: Option<&'a str>,
    decision: &'a str,
    reason: Option<&'a str>,
    actor: Option<&'a str>,
    of: Option<&'a str>,
    to: Option<&'a str>,
    apply: bool,
}

/// `tix triage batch`: resolve one selection, build one read-only plan, and —
/// only under `--apply` — confirm and run it.
///
/// The plan/confirm/apply sequence is [`crate::triage::batch`]'s, which is
/// #173's core (C-005). Nothing here re-implements a preview or an apply; what
/// is added is the command line that reaches them and the text that comes back.
fn run_batch(store: &Store, flags: BatchFlags<'_>) -> Result<ExitCode> {
    let request = selection_request(flags.select, flags.filter)?;
    let kind: DecisionKind = flags.decision.parse()?;

    // `--to` names an accept target. Ignoring it on a decline would let a user
    // believe they had chosen where the issue lands — the same reason
    // `triage::batch::build_plan` refuses `--of` on a non-duplicate.
    if flags.to.is_some() && kind != DecisionKind::Accept {
        return Err(TixError::InvalidInput(format!(
            "`--to` names an accept target, and this batch is a {kind} decision"
        )));
    }

    let mut decision = TriageDecision::new(
        kind,
        crate::model::utc_now_rfc3339(),
        flags
            .actor
            .map(str::to_string)
            .unwrap_or_else(crate::storage::actor_identity),
        flags.reason.unwrap_or_default(),
    );
    // `--to` names the accept target. It is assigned **here**, before the blank
    // filter below: the filter's whole rule ("a flag that carried only whitespace
    // named no column") is about a field that was never assigned, so `--to` was
    // silently dropped on the batch path while `tix triage accept --to` honoured it —
    // `--to "in progress"` landed the issue in the configured `accepted_status`
    // instead, and `--to ghost` wrote the configured target where the single-command
    // path refuses `unknown_column`. Found from WP08's cross-surface matrix, whose MCP
    // half was the correct one.
    if kind == DecisionKind::Accept {
        decision.target_status = flags.to.map(str::to_string);
    }
    // A flag that carried only whitespace named no column — the reading
    // `DecisionService::plan` gives it, applied here first so the preview cannot
    // show a destination the service will ignore.
    if decision
        .target_status
        .as_deref()
        .is_some_and(|target| target.trim().is_empty())
    {
        decision.target_status = None;
    }
    // Name the target the service is going to use, so both the preview and the
    // report say where an accept lands. This reads the *same* config field the
    // service reads, at the same moment, so it restates the outcome rather than
    // proposing a second rule: when there is no configured target either, the
    // service still refuses `missing_target` per item.
    if decision.target_status.is_none() && kind == DecisionKind::Accept {
        decision.target_status = store
            .config
            .triage
            .as_ref()
            .and_then(|triage| triage.accepted_status.clone());
    }

    let selection = bulk::resolve(store, &request)?;
    let mut plan = batch::build_plan(store, selection, decision, flags.of)?;

    if !flags.apply {
        print!("{}", render_plan(&plan));
        return Ok(exit_code_for_plan(&plan));
    }

    // The confirmation is issued here, from the plan in front of us, so
    // `batch::apply` re-checks the membership it was authorized for and refuses
    // a plan that changed underneath it.
    plan.confirm();
    let report = batch::apply(store, &plan)?;
    print!("{}", render_report(&report, &plan));
    Ok(exit_code_for_report(&report))
}

/// The one selection grammar the user named, refused when they named none or
/// both.
///
/// `--select` and `--filter` are different grammars, and a batch that guessed
/// would decide on a different set of issues than the one on screen. The
/// diagnostic names the flags **this** command has; going through
/// [`SelectionRequest::new`] instead would have named `--search`, which
/// `tix triage batch` does not offer and a user could not type.
fn selection_request(select: Option<&str>, filter: Option<&str>) -> Result<SelectionRequest> {
    let select = select.map(str::trim).filter(|raw| !raw.is_empty());
    let filter = filter.map(str::trim).filter(|raw| !raw.is_empty());
    let (source, query) = match (select, filter) {
        (Some(_), None) => (SelectionSource::Explicit, None),
        (None, Some(raw)) => (SelectionSource::Filter, Some(raw.to_string())),
        (Some(_), Some(_)) => {
            return Err(TixError::InvalidInput(
                "name exactly one of --select or --filter — they are different grammars, \
                 so a triage batch will not guess which issues you meant"
                    .to_string(),
            ));
        }
        (None, None) => {
            return Err(TixError::InvalidInput(
                "name one of --select or --filter so the batch knows which issues to \
                 decide on"
                    .to_string(),
            ));
        }
    };
    let selectors = match select {
        Some(raw) => raw
            .split(',')
            .map(str::trim)
            .filter(|raw| !raw.is_empty())
            .map(str::to_string)
            .collect(),
        None => Vec::new(),
    };
    if selectors.is_empty() && query.is_none() {
        return Err(TixError::InvalidInput(
            "the selection names no issue — a selector list like `--select 1,2,3` needs \
             at least one selector"
                .to_string(),
        ));
    }
    Ok(SelectionRequest {
        source,
        selectors,
        query,
        scope: SelectionScope::Active,
    })
}

/// The preview body. Pure, so a surface can be tested without a process and a
/// report can never disagree with the plan it describes.
pub fn render_plan(plan: &TriagePlan) -> String {
    let mut out = render_selection(plan);
    out.push_str(&render_decision(plan));
    for item in &plan.items {
        out.push_str(&format!("#{} {}\n", item.number, item.title));
        // A refused item shows the refusal and nothing else: a preview that
        // lists a change above the line saying it will not happen is worse than
        // no preview, because the change is the part that gets read.
        if let Some(diagnostic) = &item.diagnostic {
            out.push_str(&format!(
                "    refused [{}]: {}\n",
                diagnostic.field, diagnostic.message
            ));
            continue;
        }
        if item.is_noop() {
            out.push_str("    no change\n");
            continue;
        }
        for (field, change) in &item.changes {
            out.push_str(&format!("    {field}: {}\n", render_change(change)));
        }
        if let Some(path) = &item.path_change {
            out.push_str(&format!("    path: {} -> {}\n", path.from, path.to));
        }
        for intent in &item.history {
            out.push_str(&format!(
                "    history: {} ({})\n",
                intent.kind, intent.detail
            ));
        }
    }
    for duplicate in plan.selection.duplicates() {
        out.push_str(&format!(
            "note: selector '{duplicate}' named an issue already selected\n"
        ));
    }
    out.push_str(&format!("{}\n", plan.summary()));
    out
}

/// The apply body: one outcome per selected issue, in selection order, then the
/// counts — every count named, including the zeros, so a batch that silently
/// skipped 200 issues cannot read like one that decided them.
///
/// The resulting column comes from the **plan** item that was just applied, which
/// is the same service's answer to the same inputs; the report's own `applied`
/// line carries the path the file is actually at. T026 asks for "final
/// state/path where relevant", and this is where both are relevant.
pub fn render_report(report: &ApplyReport, plan: &TriagePlan) -> String {
    let mut out = render_selection(plan);
    out.push_str(&render_decision(plan));
    let by_number: BTreeMap<u32, &crate::bulk::ItemPlan> =
        plan.items.iter().map(|item| (item.number, item)).collect();
    for (number, outcome) in &report.outcomes {
        let item = by_number.get(number);
        let title = item.map(|item| item.title.as_str()).unwrap_or_default();
        out.push_str(&outcome.as_line(*number, title));
        out.push('\n');
        if outcome.is_applied() {
            if let Some(change) = item.and_then(|item| item.changes.get("status")) {
                out.push_str(&format!("    status: {}\n", render_change(change)));
            }
        }
    }
    out.push_str(&format!("{}\n", report.summary()));
    out
}

/// The selection header, read from the **plan** rather than passed separately —
/// so the header and the items it describes cannot be two different sources.
fn render_selection(plan: &TriagePlan) -> String {
    let selection = &plan.selection;
    let mut out = format!(
        "selection: {} issue{} ({}, {} scope)\n",
        selection.len(),
        if selection.len() == 1 { "" } else { "s" },
        selection.source().as_str(),
        selection.scope().as_str()
    );
    let listing: Vec<String> = selection
        .issues()
        .iter()
        .map(|issue| format!("    #{} {}", issue.number, issue.title))
        .collect();
    if !listing.is_empty() {
        out.push_str(&listing.join("\n"));
        out.push('\n');
    }
    out
}

/// The decision line: what was asked for, and where it lands when the request
/// itself named a destination.
fn render_decision(plan: &TriagePlan) -> String {
    let mut out = format!("decision: {}", plan.decision.kind);
    if let Some(target) = plan
        .decision
        .target_status
        .as_deref()
        .map(str::trim)
        .filter(|target| !target.is_empty())
    {
        out.push_str(&format!(" -> {target}"));
    }
    if let Some(of) = plan.duplicate_of.as_deref() {
        out.push_str(&format!(" of {of}"));
    }
    out.push('\n');
    out
}

/// `status: "triage" -> "wontfix"`, the shape `tix bulk` prints.
///
/// Local rather than reused: `commands::bulk`'s twin is private to that module,
/// and WP05 owns neither that file nor the right to make its helpers public for
/// this. Three lines of formatting are a cheaper thing to duplicate than a
/// cross-module visibility change in a work package that does not own the file.
fn render_change(change: &FieldChange) -> String {
    match change {
        FieldChange::Set { from, to } => format!("{from:?} -> {to}"),
        FieldChange::Clear { from } => format!("{from:?} -> (empty)"),
        FieldChange::NoChange { value } => format!("{value:?} (already in that state)"),
    }
}

// ---------------------------------------------------------------------------
// Exit codes
// ---------------------------------------------------------------------------

/// The status of a preview: non-zero when an item will be refused, so a script
/// reading the status knows before it applies.
pub fn exit_code_for_plan(plan: &TriagePlan) -> ExitCode {
    if plan.blocked().next().is_some() {
        ExitCode::UsageConfig
    } else {
        ExitCode::Success
    }
}

/// The status of an applied batch: non-zero when an item was **rejected or
/// failed**, and zero when every item either applied or was already there.
///
/// A no-op counts as satisfied, and that is a deliberate difference from
/// `commands::bulk::exit_code_for_report`. Spec §4 lists "re-running a batch does
/// not duplicate History events" as an invariant, so the re-run is an operation
/// this feature supports — and an operation that exits non-zero every time would
/// make the invariant its own bug report. Rejected and failed items still report
/// non-zero (T026), and `summary()` counts them separately either way.
pub fn exit_code_for_report(report: &ApplyReport) -> ExitCode {
    if report.rejected() + report.failed() > 0 {
        ExitCode::UsageConfig
    } else {
        ExitCode::Success
    }
}