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
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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
//! `tix bulk` — the batch command surface (WP06).
//!
//! Four subcommands, and the shape of the surface is the contract's:
//!
//! ```text
//! tix bulk edit   --select <selectors|filter|search> <patch flags> [--apply]
//! tix bulk link   --select <...> --target <selector> [--apply]
//! tix bulk unlink --select <...> --target <selector> [--apply]
//! tix bulk archive --select <...> [--apply]
//! ```
//!
//! ## Preview is the default, and that is a default not a courtesy
//!
//! `--apply` is required to write. A user who types `tix bulk edit --select 1,2,3
//! --status wip` and gets a **table** has been told what would happen and has not
//! changed anything; a user who expected a write has lost nothing. The reverse default
//! would make a bulk mistake — and a bulk mistake is a mistake multiplied by the
//! selection size — the default outcome of a plausible command line.
//!
//! ## A partial batch exits non-zero and keeps every outcome
//!
//! `contracts/cli-surface.md`: "A partial batch returns a non-zero status while
//! retaining all outcomes; do not imply rollback."
//!
//! The exit code is **1**, and the choice is worth stating because the table is
//! frozen: 0 is "everything requested happened"; 2 is a *whole-command* selection
//! failure (not-found or ambiguous); 3 is an external tool. A partial batch is none
//! of those, and 1 — "usage/config", read as "the request was not fully honoured" —
//! is the only code left. Inventing a fifth code would break a frozen contract to
//! name a situation 1 already describes.
//!
//! And the output says `0 write failures` even when it is zero, because a batch that
//! silently skipped 200 items must not read like one that wrote them.
//!
//! ## Nothing here re-implements an apply
//!
//! The field path is `bulk::apply`, the pair path is `bulk::pair`, the archive path
//! is `bulk::archive`. This module resolves a selection, builds a plan, routes it, and
//! renders. The single-archive-state rule and the R7 outcome-shape rule are the other
//! missions' to keep, and the only way to keep them from here is to not write a
//! second one.

use std::collections::BTreeMap;
use std::path::Path;

use crate::bulk::plan::BatchPlan;
use crate::bulk::{
    self, ApplyReport, ArchiveRequest, Confirmation, IssuePatch, PairOutcome, PatchValue,
    RelationshipOp, Selection, SelectionScope, SelectionSource,
};
use crate::cli::ExitCode;
use crate::commands::parse_priority;
use crate::error::{Result, TixError};
use crate::model::Priority;
use crate::storage::Store;

/// The selection the user asked for, and which grammar they used.
///
/// Three separate flags rather than one `--select` whose value might be a filter:
/// the contract's `--select <selectors|filter|search>` is ambiguous about which
/// grammar a value belongs to, and a bulk operation that guesses wrong edits a
/// different set of issues than the user read on screen. One flag per grammar, exactly
/// one required.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SelectionRequest {
    pub source: SelectionSource,
    /// Comma-separated selectors, already split and trimmed.
    pub selectors: Vec<String>,
    /// The query, for `Filter` and `Search`.
    pub query: Option<String>,
    pub scope: SelectionScope,
}

impl SelectionRequest {
    /// Build a request, refusing anything that is not exactly one grammar.
    ///
    /// Zero grammars and two grammars are the same error, because both mean the
    /// command line does not say which set of issues to act on. The message names
    /// all three so a user does not have to guess what else to try.
    pub fn new(
        selectors: &[String],
        filter: Option<&str>,
        search: Option<&str>,
        scope: SelectionScope,
    ) -> Result<Self> {
        let named: Vec<(&str, &str)> = [
            (
                "--select",
                selectors.first().map(|s| s.as_str()).unwrap_or(""),
            ),
            ("--filter", filter.unwrap_or("")),
            ("--search", search.unwrap_or("")),
        ]
        .into_iter()
        .filter(|(_, value)| !value.trim().is_empty())
        .collect();
        if named.len() != 1 {
            return Err(TixError::InvalidInput(format!(
                "name exactly one of --select, --filter or --search \
                 ({} given) — they are different grammars, so a bulk operation will \
                 not guess which issues you meant",
                if named.is_empty() {
                    "none".to_string()
                } else {
                    named
                        .iter()
                        .map(|(flag, _)| *flag)
                        .collect::<Vec<_>>()
                        .join(" and ")
                }
            )));
        }
        let (source, query) = match named[0].0 {
            "--select" => (SelectionSource::Explicit, None),
            "--filter" => (SelectionSource::Filter, Some(named[0].1.trim().to_string())),
            _ => (SelectionSource::Search, Some(named[0].1.trim().to_string())),
        };
        Ok(Self {
            source,
            selectors: split_selectors(selectors),
            query,
            scope,
        })
    }
}

/// Split and trim a comma-separated selector list, dropping empty entries.
///
/// Drops empties rather than carrying them, because a trailing comma is a typo and
/// `parse_selector("")` would refuse it with a message about an empty selector, which
/// names a problem the user did not have.
fn split_selectors(raw: &[String]) -> Vec<String> {
    raw.iter()
        .flat_map(|value| value.split(','))
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_string)
        .collect()
}

/// The patch flags, exactly the confirmed typed fields.
///
/// A closed list, in the same sense `IssuePatch` is: there is no `--set key=value`, so
/// there is no route by which `--set number=99` or `--set body=…` reaches the code.
/// `contracts/cli-surface.md`: "Patch flags are limited to the confirmed typed fields."
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PatchFlags {
    pub status: Option<String>,
    pub priority: Option<String>,
    pub assignee: Option<String>,
    pub labels: Option<String>,
    pub start_date: Option<String>,
    pub due_date: Option<String>,
    pub estimate: Option<String>,
    pub cycles: Option<String>,
    pub milestones: Option<String>,
    /// `--clear <field>`, for the fields that support clearing.
    pub clear: Vec<String>,
}

/// Which fields `--clear` accepts, and the diagnostic for anything else.
///
/// A closed list, and the error names it — so `--clear body` says what *can* be
/// cleared rather than "unknown field". `body` is not clearable, and a bulk operation
/// that emptied a body would be doing something no single-issue command can.
const CLEARABLE: [&str; 8] = [
    "priority",
    "assignee",
    "labels",
    "start-date",
    "due-date",
    "estimate",
    "cycles",
    "milestones",
];

// `status` is absent on purpose and for a stated reason: a column is not a field a
// bulk operation may empty, `Issue::status` is not optional, and a `Clear` on it has
// no meaning. It is named in the diagnostic rather than silently absent, so a user
// who tries `--clear status` is told it is not clearable and why it is not a
// "clearable field" — the list is the accepted set, and the message quotes it.

impl PatchFlags {
    /// The diagnostic listing every clearable field.
    pub fn clearable() -> &'static [&'static str] {
        &CLEARABLE
    }

    /// The flag rows, in the contract's field order, plus `clear`.
    ///
    /// The **one** list, so the TUI's `tab` order, the CLI's help and a test's
    /// "every field is reachable" case cannot disagree. `clear` is last because it is
    /// the one row that is not a *set* — it empties a field, and a user tabbing
    /// through expects to set values first and clear one afterwards.
    pub fn field_rows() -> &'static [&'static str] {
        &[
            "status",
            "priority",
            "assignee",
            "labels",
            "start-date",
            "due-date",
            "estimate",
            "cycles",
            "milestones",
            "clear",
        ]
    }

    /// Whether a field name can be cleared.
    pub fn is_clearable(field: &str) -> bool {
        CLEARABLE.contains(&field)
    }

    /// Whether any patch flag was given at all.
    pub fn is_empty(&self) -> bool {
        self.status.is_none()
            && self.priority.is_none()
            && self.assignee.is_none()
            && self.labels.is_none()
            && self.start_date.is_none()
            && self.due_date.is_none()
            && self.estimate.is_none()
            && self.cycles.is_none()
            && self.milestones.is_none()
            && self.clear.is_empty()
    }

    /// Build the typed patch.
    ///
    /// A **blank** flag value is `Unchanged`, not `Clear` and not `Set("")`. A flag
    /// with no value is a flag the user did not mean, and treating it as "set it to
    /// the empty string" is the class of bug `PatchValue` exists to prevent — reached
    /// through the CLI this time rather than through the type.
    pub fn to_patch(&self) -> Result<IssuePatch> {
        let text = |value: &Option<String>| -> PatchValue<String> {
            match value {
                Some(v) if !v.trim().is_empty() => PatchValue::Set(v.trim().to_string()),
                _ => PatchValue::Unchanged,
            }
        };
        let priority = match &self.priority {
            Some(v) if !v.trim().is_empty() => {
                // The **same core** a single `tix edit --priority` uses, so a bulk
                // priority cannot be a value a single edit would reject.
                PatchValue::Set(parse_priority(v.trim())?)
            }
            _ => PatchValue::Unchanged,
        };
        let list = |value: &Option<String>| -> PatchValue<Vec<String>> {
            match value {
                Some(v) if !v.trim().is_empty() => PatchValue::Set(
                    v.split(',')
                        .map(str::trim)
                        .filter(|s| !s.is_empty())
                        .map(str::to_string)
                        .collect(),
                ),
                _ => PatchValue::Unchanged,
            }
        };
        let mut patch = IssuePatch {
            status: text(&self.status),
            priority,
            assignee: text(&self.assignee),
            labels: list(&self.labels),
            start_date: text(&self.start_date),
            due_date: text(&self.due_date),
            estimate: text(&self.estimate),
            cycles: list(&self.cycles),
            milestones: list(&self.milestones),
            ..IssuePatch::default()
        };
        for field in &self.clear {
            if !Self::is_clearable(field) {
                return Err(TixError::InvalidInput(format!(
                    "cannot clear '{field}' — clearable fields: {}",
                    CLEARABLE.join(", ")
                )));
            }
            // The *typed* slot, so a clear is a `Clear` in the same enum the type
            // promises and not a `Set` of an empty string.
            match field.as_str() {
                "priority" => patch.priority = PatchValue::Clear,
                "assignee" => patch.assignee = PatchValue::Clear,
                "labels" => patch.labels = PatchValue::Clear,
                "start-date" => patch.start_date = PatchValue::Clear,
                "due-date" => patch.due_date = PatchValue::Clear,
                "estimate" => patch.estimate = PatchValue::Clear,
                "cycles" => patch.cycles = PatchValue::Clear,
                "milestones" => patch.milestones = PatchValue::Clear,
                // Unreachable: `is_clearable` gates this loop over the same list.
                // Named rather than `_` so adding a field to `CLEARABLE` without
                // adding an arm is a compile error rather than a silent no-op.
                _ => unreachable!("CLEARABLE and this match must list the same fields"),
            }
        }
        Ok(patch)
    }
}

/// What the surface should do with a plan.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    /// Report and change nothing. The default.
    Preview,
    /// Report and apply.
    Apply,
}

impl Mode {
    /// The word the output uses for an item, so a preview never says it did
    /// something.
    pub fn verb(self, done: &'static str) -> &'static str {
        match self {
            Self::Preview => {
                let _ = done;
                "would"
            }
            Self::Apply => done,
        }
    }
}

/// The per-item result a surface reports, in the shared outcome vocabulary.
///
/// A re-export rather than a new type: `contracts/surface-parity.md` requires the
/// same accept/reject decision on every surface, and the cheapest way to guarantee one
/// outcome vocabulary is not to have two.
pub type BulkOutcome = bulk::ItemOutcome;

/// Run `tix bulk edit`.
pub fn run_edit(
    store: &Store,
    request: &SelectionRequest,
    flags: &PatchFlags,
    mode: Mode,
) -> Result<ExitCode> {
    let patch = flags.to_patch()?;
    if patch.is_empty() {
        return Err(TixError::InvalidInput(format!(
            "no fields to change — name at least one of: {}",
            IssuePatch::field_names().join(", ")
        )));
    }
    let selection = resolve(store, request)?;
    let plan = build(store, selection, patch)?;
    if mode == Mode::Preview {
        print!("{}", render_plan(&plan, Mode::Preview));
        return Ok(exit_code_for_plan(&plan));
    }
    let mut confirmed = plan.clone();
    confirmed.confirmation = Some(Confirmation::issue(&plan));
    let report = bulk::apply_fields(store, &confirmed, &crate::storage::actor_identity(), None)?;
    print!("{}", render_report(&report, &confirmed, Mode::Apply));
    Ok(exit_code_for_report(&report))
}

/// Run `tix bulk link` or `tix bulk unlink`.
///
/// The selection is the set of issues a `from` is drawn from, and `--target` is the
/// other end. A pair is two named endpoints (WP04), so `--select` may name several
/// issues and each becomes a pair with the target — and a missing target is a
/// diagnostic for the pairs that name it, not a whole-command failure, which is why
/// this delegates per pair rather than resolving the target once.
pub fn run_pair(
    store: &Store,
    request: &SelectionRequest,
    target: Option<&str>,
    kind: Option<&str>,
    link: bool,
    mode: Mode,
) -> Result<ExitCode> {
    let kind = crate::commands::link::require_kind(kind)?;
    let selection = resolve(store, request)?;
    if selection.is_empty() {
        return Err(TixError::NotFound(
            "the selection is empty, so there is nothing to pair".to_string(),
        ));
    }
    let mut outcomes: Vec<(String, PairOutcome)> = Vec::new();
    let mut refused = 0usize;
    for issue in selection.issues() {
        let op = if link {
            RelationshipOp::link(issue.number.to_string(), target.unwrap_or_default(), kind)
        } else {
            RelationshipOp::unlink(issue.number.to_string(), target.unwrap_or_default(), kind)
        };
        let mut plan = build(
            store,
            Selection::from_issues(vec![issue.clone()], request.source, request.scope),
            IssuePatch {
                relationship: Some(op.clone()),
                ..IssuePatch::default()
            },
        )?;
        if mode == Mode::Preview {
            let resolution = bulk::pair::resolve_pair(store, &op);
            match &resolution.diagnostic {
                Some(diagnostic) => {
                    refused += 1;
                    println!(
                        "#{} {} -> refused: {}",
                        issue.number,
                        issue.title,
                        resolution.requested.verb()
                    );
                    let _ = diagnostic;
                }
                None => println!(
                    "#{} {} -> would {} {} #{} ({})",
                    issue.number,
                    issue.title,
                    op.verb(),
                    issue.number,
                    resolution.edge.expect("checked").to,
                    kind.as_str()
                ),
            }
            continue;
        }
        plan.confirmation = Some(Confirmation::issue(&plan));
        let outcome = bulk::apply_pair(store, &plan)?;
        if matches!(outcome, PairOutcome::Refused(_)) {
            refused += 1;
        }
        outcomes.push((format!("#{} {}", issue.number, issue.title), outcome));
    }
    if mode == Mode::Preview {
        return Ok(if refused > 0 {
            ExitCode::UsageConfig
        } else {
            ExitCode::Success
        });
    }
    for (label, outcome) in &outcomes {
        println!("{label} -> {}", outcome.as_line());
    }
    let applied = outcomes.iter().filter(|(_, o)| o.is_applied()).count();
    println!(
        "{} relationship operation{} applied, {refused} refused",
        applied,
        if applied == 1 { "" } else { "s" }
    );
    Ok(if refused > 0 || applied < outcomes.len() {
        ExitCode::UsageConfig
    } else {
        ExitCode::Success
    })
}

/// Run `tix bulk archive`.
///
/// Preview reports the plan and writes nothing. Apply delegates each selected issue
/// to the store's archive service through [`bulk::apply_archive`], then reports one
/// line per item and the counts — the same shape a field batch reports, because the
/// per-item outcomes are the same shared vocabulary.
pub fn run_archive(store: &Store, request: &SelectionRequest, mode: Mode) -> Result<ExitCode> {
    let selection = resolve(store, request)?;
    let plan = build(
        store,
        selection.clone(),
        IssuePatch {
            archive: Some(ArchiveRequest::archive()),
            ..IssuePatch::default()
        },
    )?;
    if mode == Mode::Preview {
        print!("{}", render_plan(&plan, Mode::Preview));
        return Ok(exit_code_for_plan(&plan));
    }
    let mut confirmed = plan.clone();
    confirmed.confirmation = Some(Confirmation::issue(&plan));
    let report = bulk::apply_archive(store, &confirmed)?;
    print!("{}", render_report(&report, &confirmed, Mode::Apply));
    Ok(exit_code_for_report(&report))
}

/// Resolve a request to a selection, the one path every surface uses.
///
/// `pub` because the MCP handlers (WP08 T036) need it and must not grow a second
/// resolution: `Selection::resolve` is what applies the existing filter and search
/// grammars, and a second path would be a second grammar — which C-003 calls an
/// escalation trigger.
pub fn resolve(store: &Store, request: &SelectionRequest) -> Result<Selection> {
    Selection::resolve(
        store,
        &request.selectors,
        request.query.as_deref(),
        request.source,
        request.scope,
    )
}

/// Build the shared plan, the one path every surface uses.
///
/// `pub` for the same reason as [`resolve`]: a surface that built its own plan would
/// be a second implementation of the preview, and C-004's "a preview is read-only"
/// would be a claim about one of them.
pub fn build(store: &Store, selection: Selection, patch: IssuePatch) -> Result<BatchPlan> {
    let mut plan = bulk::plan::build_plan(
        &store.config,
        &store.issues_dir,
        selection,
        patch,
        |op: &RelationshipOp| bulk::pair::plan_for(store, op),
    )?;
    // WP07 T035: the WIP decisions, evaluated against the **store's** issues — a
    // column's usage counts every card in it, not only the selected ones.
    crate::wip::bulk::annotate_plan(&mut plan, &store.config, &store.list()?);
    Ok(plan)
}

// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------

/// The preview body. Pure: takes the plan, returns the text, 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: &BatchPlan, mode: Mode) -> String {
    let mut out = String::new();
    out.push_str(&render_selection(plan));
    for item in &plan.items {
        if item.changes.is_empty() && item.diagnostic.is_none() {
            continue;
        }
        out.push_str(&format!("#{} {}\n", item.number, item.title));
        // A **refused** item shows the refusal and nothing else.
        //
        // The first version printed the proposed changes, the path and the History
        // intents *and then* the diagnostic, so a preview showed a refused item with
        // `status: "abandoned" -> review` and `history: transition_accepted` above the
        // refusal explaining that neither would happen. A preview that shows a change
        // it will not make is worse than no preview, because the change is the part a
        // user reads.
        if let Some(diagnostic) = &item.diagnostic {
            out.push_str(&format!(
                "    refused [{}]: {}\n",
                diagnostic.field, diagnostic.message
            ));
            continue;
        }
        for (field, change) in &item.changes {
            out.push_str(&format!("    {field}: {}\n", render_change(change)));
        }
        if let Some(move_path) = &item.path_change {
            out.push_str(&format!(
                "    path: {} -> {}\n",
                move_path.from, move_path.to
            ));
        }
        for intent in &item.history {
            out.push_str(&format!(
                "    history: {} ({})\n",
                intent.kind, intent.detail
            ));
        }
        // WP07 T035 (mission `configurable-wip-limits-01M3C6WX`): what the shared WIP
        // policy says about **this** item, from the projection the plan evaluated in
        // plan order. An `allow` prints nothing — a preview that said "wip: allow" on
        // every line of a limit-free batch would be noise — and the first diagnostic
        // carries the sentence, which is what a reader acts on.
        if let Some(wip) = &item.wip
            && wip.decision.outcome != crate::wip::WipOutcome::Allow
        {
            let first = crate::wip::render_decision(&wip.decision);
            let head = first.lines().next().unwrap_or_default();
            out.push_str(&format!("    wip: {head}\n"));
            // **Every** diagnostic, not only the first: the second one is usually the
            // one that says what to do about it ("an authorized override is
            // required"), and a preview that showed only "over the limit" would leave
            // the reader with the problem and not the remedy.
            for diagnostic in &wip.decision.diagnostics {
                // The **kind** beside the sentence, the shape `tix recurring detect`
                // uses for its notes: a script branches on `override_required` and a
                // person reads the sentence beside it.
                out.push_str(&format!(
                    "        {}: {}\n",
                    diagnostic.kind.as_str(),
                    diagnostic.message
                ));
            }
        }
        let _ = mode;
    }
    if let Some(pair) = &plan.pair {
        match (&pair.from, &pair.to) {
            (Ok(from), Ok(to)) => {
                out.push_str(&format!("pair: {} #{from} -> #{to}\n", pair.verb()))
            }
            _ => {
                if let Some(diagnostic) = &pair.diagnostic {
                    out.push_str(&format!("pair: refused — {diagnostic}\n"));
                } else {
                    out.push_str(&format!("pair: refused — {}\n", pair.verb()));
                }
            }
        }
    }
    if let Some(archive) = &plan.archive {
        // The count is the plan's own selection size, not a literal: a preview that
        // under-reported the selection ("would archive 1 issue" for two selected)
        // would be the one thing a preview exists to get right.
        let count = plan.selection.len();
        out.push_str(&format!(
            "archive: would {} {count} issue{}\n",
            if archive.archive {
                "archive"
            } else {
                "restore"
            },
            if count == 1 { "" } else { "s" }
        ));
    }
    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 line per item, then the counts, then the final paths.
pub fn render_report(report: &ApplyReport, plan: &BatchPlan, mode: Mode) -> String {
    let mut out = String::new();
    out.push_str(&render_selection(plan));
    let by_number: BTreeMap<u32, &str> = plan
        .items
        .iter()
        .map(|i| (i.number, i.title.as_str()))
        .collect();
    for (number, outcome) in &report.outcomes {
        let title = by_number.get(number).copied().unwrap_or("");
        out.push_str(&outcome.as_line(*number, title));
        out.push('\n');
    }
    // Every count, even the zeros: a batch that silently skipped 200 items must not
    // read like one that wrote them.
    out.push_str(&format!("{}\n", report.summary()));
    // The final paths, because "applied" without "where" leaves a user hunting.
    let moved: Vec<String> = report
        .outcomes
        .iter()
        .filter_map(|(n, o)| match o {
            BulkOutcome::Applied { filename } => Some(format!("#{n} -> {filename}")),
            _ => None,
        })
        .collect();
    if !moved.is_empty() {
        out.push_str("final paths:\n");
        for line in moved {
            out.push_str(&format!("    {line}\n"));
        }
    }
    let _ = mode;
    out
}

/// The selection header, read from the **plan** rather than from a second value.
///
/// The first version took the selection as a second parameter, so the header and the
/// plan's own items were two sources for the same facts — and a caller that passed a
/// different selection would print a header describing issues the plan does not
/// contain. The plan already carries `selection`.
fn render_selection(plan: &BatchPlan) -> 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(|i| format!("    #{} {}", i.number, i.title))
        .collect();
    if !listing.is_empty() {
        out.push_str(&listing.join("\n"));
        out.push('\n');
    }
    out
}

fn render_change(change: &bulk::FieldChange) -> String {
    use bulk::FieldChange::{Clear, NoChange, Set};
    match change {
        Set { from, to } => format!("{from:?} -> {to}"),
        Clear { from } => format!("{from:?} -> (empty)"),
        NoChange { value } => format!("{value:?} (already in that state)"),
    }
}

/// The exit code for a plan: non-zero if any item was refused, so a preview of a
/// batch that will partly fail says so in the status as well as the text.
///
/// An archive or a pair plan is not itself a failure: its per-item verdicts come from
/// the apply, and a preview that exited non-zero for a performable operation would say
/// the operation is unavailable. The refusals a preview can see are a blocked field
/// item and a pair whose endpoints do not resolve.
pub fn exit_code_for_plan(plan: &BatchPlan) -> ExitCode {
    let refused = plan.blocked().count()
        + usize::from(plan.pair.as_ref().is_some_and(|p| p.diagnostic.is_some()));
    if refused > 0 {
        ExitCode::UsageConfig
    } else {
        ExitCode::Success
    }
}

/// The exit code for an applied batch: non-zero unless every item did what was
/// asked.
pub fn exit_code_for_report(report: &ApplyReport) -> ExitCode {
    let not_applied = report.noop() + report.rejected() + report.failed();
    if not_applied > 0 {
        ExitCode::UsageConfig
    } else {
        ExitCode::Success
    }
}

/// The agents.rs documentation for the batch surface.
///
/// Generated rather than hand-written so the documented surface and the implemented one
/// cannot drift — the same reason `tix init-agents` exists, and the same failure it
/// was built to prevent.
///
/// Every list in the output comes from [`crate::bulk::metadata`] or from the flag
/// struct, never from a literal here. A hand-written list would be a fifth
/// description of the whitelist, and the previous four already disagreed at least
/// once: WP06's `--estimate ""` finding was a flag, a schema and a doc treating a
/// blank value three different ways.
pub fn agents_doc() -> String {
    use crate::bulk::metadata;
    let operations = metadata::BulkOperation::ALL
        .iter()
        .map(|op| {
            let mut line = format!("tix bulk {:<8} --select <list>", op.as_str());
            if op.needs_target() {
                line.push_str(" --target <sel>");
            }
            if op.needs_kind() {
                line.push_str(" --type <kind>");
            }
            if op.is_field_patch() {
                line.push_str(" <patch flags>");
            }
            line.push_str(" [--apply]");
            line
        })
        .collect::<Vec<_>>()
        .join("\n");
    let out = format!(
        "### `tix bulk`\n\n\
         Batch editing over a selection. **Preview is the default**; `--apply` writes.\n\n\
         ```text\n\
         {operations}\n\
         ```\n\n\
         - Name **exactly one** of `--select <list>`, `--filter <query>` or\n  \
           `--search <query>`. They are different grammars, so a bulk operation will\n  \
           not guess which issues you meant.\n\
         - Patch flags (the whole whitelist):\n  {}\n  \
           `title` and `body` are deliberately **not** in it: a batch title rewrite is\n  \
           the one operation nobody has asked for and everybody would regret.\n\
         - `--clear <field>` takes one of:\n  {}\n  \
           One per invocation — a second is refused rather than silently dropped. A\n  \
           **blank** flag value is *unchanged*, never \"set to empty\": to empty a field,\n  \
           name it in `--clear`.\n\
         - `archive` delegates to the store's archive service: each selected issue's\n  \
           file is renamed **in place** to a dot-prefixed name and exactly one History\n  \
           event records it. `number`, `status` and every other frontmatter field are\n  \
           left byte-identical, re-running reports the no-op, and nothing is deleted.\n\
         - A **partial** batch exits non-zero and prints one outcome per selected\n  \
           issue. Items that failed are **not** rolled back, and the output does not\n  \
           imply that they are. Re-running is idempotent and reports the no-op.\n\
         - Per-item statuses are the same four words on every surface:\n  {}\n",
        metadata::field_names().join(", "),
        metadata::clearable_field_names().join(", "),
        metadata::OUTCOME_STATUSES
            .iter()
            .map(|s| format!("`{s}`"))
            .collect::<Vec<_>>()
            .join(", "),
    );
    out
}

/// The entry point `tix bulk` dispatches to: parse the action, build the request and
/// the flags, and route.
///
/// The selection flags arrive as `Option<&str>` and the scope as a **string**, so the
/// vocabulary lives in one place — [`SelectionScope::parse`] — and a new scope word
/// cannot be accepted on one surface and not another.
pub fn run(
    store: &Store,
    action: &crate::cli::BulkAction,
    flags: &crate::cli::BulkSelection,
    mode: Mode,
) -> Result<ExitCode> {
    let scope = match flags.scope.as_deref() {
        Some(raw) => SelectionScope::parse(raw)?,
        None => SelectionScope::Active,
    };
    let request = SelectionRequest::new(
        &[flags.select.clone().unwrap_or_default()],
        flags.filter.as_deref(),
        flags.search.as_deref(),
        scope,
    )?;
    match action {
        crate::cli::BulkAction::Edit {
            selection: _,
            status,
            priority,
            assignee,
            labels,
            start_date,
            due_date,
            estimate,
            cycles,
            milestones,
            clear,
        } => run_edit(
            store,
            &request,
            &PatchFlags {
                status: status.clone(),
                priority: priority.clone(),
                assignee: assignee.clone(),
                labels: labels.clone(),
                start_date: start_date.clone(),
                due_date: due_date.clone(),
                estimate: estimate.clone(),
                cycles: cycles.clone(),
                milestones: milestones.clone(),
                clear: clear.iter().cloned().collect(),
            },
            mode,
        ),
        crate::cli::BulkAction::Link {
            selection: _,
            target,
            r#type,
        } => run_pair(store, &request, Some(target), r#type.as_deref(), true, mode),
        crate::cli::BulkAction::Unlink {
            selection: _,
            target,
            r#type,
        } => run_pair(
            store,
            &request,
            Some(target),
            r#type.as_deref(),
            false,
            mode,
        ),
        crate::cli::BulkAction::Archive { selection: _ } => run_archive(store, &request, mode),
    }
}

// `Result<ExitCode>` everywhere is a **success path carrying a status**, not an error:
// a partial batch is a completed command that reports non-zero, and
// `contracts/cli-surface.md` requires the output be retained, which means the outcome
// vector has to survive the return. So a refused item is a status, not an `Err` — and
// the only `Err`s are about the *command line* (no selection, two selections, an
// unknown `--clear`, a bad priority), which is the right place for them.

/// The issues directory a store opened for, for a caller that reports paths.
pub fn issues_dir(store: &Store) -> &Path {
    &store.issues_dir
}

/// Silence the unused-import lint for a type only used in a doc link.
const _: Option<Priority> = None;