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
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
//! WP06 — the `tix bulk` surface, through the **real binary**.
//!
//! These are process-level cases: they run `target/debug/tix` and read its stdout,
//! stderr and **exit status**. That is the only way to check the three things the
//! CLI contract is actually about —
//!
//! - **preview is the default**, which is a claim about what a bare command line does;
//! - **a partial batch exits non-zero while retaining every outcome**, which is a
//!   claim about the status *and* the output together;
//! - **existing single-issue commands are unchanged**, which is a claim about a
//!   binary other tests call in-process.
//!
//! The binary is located through `CARGO_BIN_EXE_tix`, so a test cannot pass against a
//! stale build of `tix` on `PATH` — the mise shim is 0.3.0 and predates most of this
//! codebase.

use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};

use indexmap::IndexMap;

use tempfile::TempDir;
use tix::config::{BoardConfiguration, Config, KanbanSection};

/// The binary under test, as cargo built it for this test run.
fn tix_bin() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_tix"))
}

const MAP: [(&str, &str); 5] = [
    ("triage", "backlog"),
    ("wip", "active"),
    ("review", "active"),
    ("shipped", "completed"),
    ("abandoned", "canceled"),
];

/// A board fixture, one issue per column, so every column has exactly one issue and a
/// selection can name any of them unambiguously.
fn board() -> TempDir {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("docs").join("issues");
    fs::create_dir_all(&dir).unwrap();
    let config = Config {
        issues_dir: dir,
        kanban: KanbanSection {
            configurations: IndexMap::from([(
                "default".to_string(),
                BoardConfiguration {
                    columns: MAP.iter().map(|(c, _)| (*c).to_string()).collect(),
                    done_column: Some("shipped".to_string()),
                    category_map: MAP
                        .iter()
                        .map(|(c, k)| ((*c).to_string(), (*k).to_string()))
                        .collect(),
                    ..Default::default()
                },
            )]),
        },
        ..Config::default()
    };
    config.save(&tmp.path().join("tix.toml")).unwrap();
    let board = tmp.path().to_path_buf();
    // **All five in `triage`.**
    //
    // The first version seeded one issue per column, which reads as a tidier fixture
    // and made half these cases wrong: a test targeting `wip` then found issue 2
    // *already* there, so a batch that should have applied two issues applied one
    // and reported a no-op — and the "both apply" case asserted `2 of 2 applied`
    // against `1 of 2`. Every one of those was a fixture artefact.
    //
    // A test that needs a specific column moves the issue there itself, which is also
    // how a user would set the situation up, and it makes the intent visible in the
    // test rather than hidden in a shared helper.
    for i in 1..=5 {
        run(&board, &["create", "--title", &format!("Issue{i}")])
            .unwrap_or_else(|e| panic!("seeding issue {i}: {e}"));
    }
    tmp
}

fn run(dir: &Path, args: &[&str]) -> std::result::Result<Output, String> {
    Command::new(tix_bin())
        .current_dir(dir)
        .args(args)
        // A fixed actor, so a History line's actor field is the same in every
        // fixture and a byte comparison of two trees does not differ on identity.
        .env("GIT_AUTHOR_NAME", "Test")
        .env("GIT_AUTHOR_EMAIL", "test@example.invalid")
        .env("GIT_COMMITTER_NAME", "Test")
        .env("GIT_COMMITTER_EMAIL", "test@example.invalid")
        .output()
        .map_err(|e| e.to_string())
}

/// Run and require success, returning the stdout.
fn ok(dir: &Path, args: &[&str]) -> String {
    let out = run(dir, args).expect("the binary runs");
    assert!(
        out.status.success(),
        "tix {args:?} exited {:?}\nstdout: {}\nstderr: {}",
        out.status.code(),
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    String::from_utf8_lossy(&out.stdout).into_owned()
}

/// Run and require the given exit code, returning `(stdout, stderr)`.
fn code(dir: &Path, args: &[&str], want: i32) -> (String, String) {
    let out = run(dir, args).expect("the binary runs");
    assert_eq!(
        out.status.code(),
        Some(want),
        "tix {args:?} exited {:?}, wanted {want}\nstdout: {}\nstderr: {}",
        out.status.code(),
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    (
        String::from_utf8_lossy(&out.stdout).into_owned(),
        String::from_utf8_lossy(&out.stderr).into_owned(),
    )
}

fn snapshot(dir: &Path) -> Vec<(String, Vec<u8>)> {
    let mut out = Vec::new();
    let mut stack = vec![dir.to_path_buf()];
    while let Some(cur) = stack.pop() {
        for entry in fs::read_dir(&cur).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                stack.push(path);
            } else {
                out.push((
                    path.strip_prefix(dir)
                        .unwrap()
                        .to_string_lossy()
                        .to_string(),
                    fs::read(&path).unwrap(),
                ));
            }
        }
    }
    out.sort();
    out
}

/// The issue files, without `tix.toml` and the number-claim files.
fn issues(dir: &Path) -> Vec<(String, Vec<u8>)> {
    snapshot(&dir.join("docs").join("issues"))
}

// ---------------------------------------------------------------------------
// T026 — the tree and the selection
// ---------------------------------------------------------------------------

/// The contract's spelling works: `tix bulk edit --select <list> …` with the
/// selection **after** the action.
///
/// The first version held the selection flags on `Command::Bulk`, so clap required
/// them *before* the subcommand and `tix bulk edit --select 1,2` was
/// `error: unexpected argument '--select' found`. The contract names one surface, and
/// a surface that needs a different word order is a different surface.
#[test]
fn t026_the_contract_spelling_is_the_one_that_parses() {
    let board = board();
    let stdout = ok(
        board.path(),
        &["bulk", "edit", "--select", "1,2", "--status", "wip"],
    );
    assert!(stdout.contains("selection: 2 issues"), "{stdout}");
    assert!(stdout.contains("#1 Issue1"), "{stdout}");
    assert!(stdout.contains("#2 Issue2"), "{stdout}");
}

/// The three selection grammars are **mutually exclusive**, and both the empty and
/// the doubled cases name all three so a user is not left guessing what else to try.
#[test]
fn t026_exactly_one_selection_grammar_is_required() {
    let board = board();
    for args in [
        vec!["bulk", "edit", "--status", "wip"],
        vec![
            "bulk",
            "edit",
            "--select",
            "1",
            "--filter",
            "status:wip",
            "--status",
            "wip",
        ],
        vec![
            "bulk", "edit", "--select", "1", "--search", "wip", "--status", "wip",
        ],
    ] {
        let (_, stderr) = code(board.path(), &args, 1);
        assert!(
            stderr.contains("--select")
                && stderr.contains("--filter")
                && stderr.contains("--search"),
            "the diagnostic must name all three grammars: {stderr}"
        );
        assert!(stderr.contains("will not guess"), "and say why: {stderr}");
    }
}

/// Each grammar selects through its **own** matcher, and `--search` does not accept a
/// `key:value` criterion (WP01's finding: a search is a contiguous substring, a
/// filter's bare term is a subsequence).
#[test]
fn t026_each_grammar_selects_through_its_own_matcher() {
    let board = board();
    let by_select = ok(
        board.path(),
        &["bulk", "edit", "--select", "1", "--status", "wip"],
    );
    assert!(by_select.contains("selection: 1 issue ("), "{by_select}");
    assert!(by_select.contains("selector"), "{by_select}");

    // The fixture starts everything in `triage`, so a filter needs something in
    // another column — moved the way a user would.
    ok(board.path(), &["move", "5", "abandoned"]);
    // `abandoned` is terminal, so a preview of a move out of it is a **refusal** and
    // the preview's status says so. That is the design: a script reading the preview's
    // status knows before applying. The first version expected `0` and failed.
    let (by_filter, _) = code(
        board.path(),
        &[
            "bulk",
            "edit",
            "--filter",
            "status:abandoned",
            "--status",
            "review",
        ],
        1,
    );
    assert!(by_filter.contains("filter"), "{by_filter}");
    assert!(by_filter.contains("#5 Issue5"), "{by_filter}");

    let by_search = ok(
        board.path(),
        &["bulk", "edit", "--search", "Issue3", "--status", "wip"],
    );
    assert!(by_search.contains("search"), "{by_search}");
    assert!(by_search.contains("#3 Issue3"), "{by_search}");
    // A criterion is not literal text, so a search for one matches nothing.
    let criterion = ok(
        board.path(),
        &[
            "bulk",
            "edit",
            "--search",
            "status:abandoned",
            "--status",
            "wip",
        ],
    );
    assert!(
        criterion.contains("selection: 0 issues"),
        "a search is a substring, not a criterion: {criterion}"
    );
}

/// A flag the action does not take is a **clap** error, not a command that accepts it
/// and ignores it. `tix bulk archive --priority high` cannot mean anything, and the
/// cheapest way to say so is to refuse to parse it.
#[test]
fn t026_a_flag_the_action_does_not_take_is_a_usage_error() {
    let board = board();
    let out = run(
        board.path(),
        &["bulk", "archive", "--select", "1", "--priority", "high"],
    )
    .expect("the binary runs");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(!out.status.success(), "must not succeed");
    assert!(
        stderr.contains("unexpected argument") && stderr.contains("--priority"),
        "clap should name the flag it does not take: {stderr}"
    );
}

// ---------------------------------------------------------------------------
// T027 — field flags, preview, report
// ---------------------------------------------------------------------------

/// **Preview is the default.** A bare `tix bulk edit` prints a table and writes
/// nothing — byte for byte, including `tix.toml`.
#[test]
fn t027_preview_is_the_default_and_writes_nothing() {
    let board = board();
    let before = snapshot(board.path());
    let stdout = ok(
        board.path(),
        &[
            "bulk",
            "edit",
            "--select",
            "1,2",
            "--status",
            "wip",
            "--estimate",
            "3d",
        ],
    );
    assert_eq!(
        snapshot(board.path()),
        before,
        "C-005: a preview is read-only — no file, no History, no tix.toml write"
    );
    // And it says "would", not "did". A preview that says it applied something is
    // the defect `Mode::verb` exists to prevent.
    assert!(stdout.contains("2 of 2 would change"), "{stdout}");
    assert!(
        !stdout.contains("applied ("),
        "a preview must not use the apply vocabulary: {stdout}"
    );
    assert!(stdout.contains("-> wip"), "{stdout}");
    assert!(stdout.contains("-> 3d"), "{stdout}");
}

/// A **refused** item shows the refusal and nothing else.
///
/// The first version printed the proposed changes and the History intent *and then*
/// the diagnostic, so the preview showed `status: "abandoned" -> review` and
/// `history: transition_accepted` above the refusal saying 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.
#[test]
fn t027_a_refused_item_shows_the_refusal_and_nothing_else() {
    let board = board();
    // #5 goes into `abandoned` — `canceled`, terminal — so the terminal lock refuses
    // it and `review` is not a complete column.
    ok(board.path(), &["move", "5", "abandoned"]);
    let (stdout, _) = code(
        board.path(),
        &["bulk", "edit", "--select", "1,5", "--status", "review"],
        1,
    );
    // Bounded to the item's own block, up to the next `#` line. An unbounded slice
    // runs to the end of the output and picks up the summary, which quotes the
    // shared diagnostic — and that message *does* contain "-> review", so the first
    // version's `!delta.contains("-> review")` was failing on the refusal's own
    // explanation rather than on a proposed change.
    let delta = stdout
        // The issue name appears **twice** -- once in the selection listing and once
        // as the item header -- so the item block is the segment after the **last**
        // occurrence. `nth(1)` gave the gap between the two, which is empty, and the
        // first version's failure said so in the least useful way: "the refusal is
        // shown: " with nothing after it.
        .rsplit_once("#5 Issue5")
        .expect("#5 is listed")
        .1
        .split("\n#")
        .next()
        .expect("the item block");
    assert!(
        delta.contains("refused [status]"),
        "the refusal is shown: {delta}"
    );
    assert!(
        !delta.contains("transition_accepted"),
        "and not a History intent that will not happen: {delta}"
    );
    assert!(
        !delta.contains("status: \""),
        "and not a proposed change that will not be made: {delta}"
    );
}

/// `--apply` writes, and reports one line per item **plus the final paths**.
#[test]
fn t027_apply_writes_and_reports_per_item_outcomes_and_final_paths() {
    let board = board();
    let stdout = ok(
        board.path(),
        &[
            "bulk", "edit", "--select", "1,2", "--status", "wip", "--apply",
        ],
    );
    assert!(stdout.contains("#1 Issue1 -> applied ("), "{stdout}");
    assert!(stdout.contains("#2 Issue2 -> applied ("), "{stdout}");
    assert!(stdout.contains("final paths:"), "{stdout}");
    // The printed final path is the real, on-disk path: parse it back and check
    // the file exists. The filename now carries the generated id between the date
    // and the slug, so it cannot be spelled out ahead of time.
    let final_path = stdout
        .lines()
        .find_map(|line| line.trim().strip_prefix("#1 -> "))
        .expect("a final path for #1");
    assert!(
        final_path.ends_with("-issue1.md"),
        "the final path keeps the human slug: {final_path}"
    );
    assert!(
        board.path().join("docs/issues").join(final_path).is_file(),
        "the printed final path is the real one: {final_path}"
    );
    assert!(stdout.contains("2 of 2 applied"), "{stdout}");
    // Every count, even the zeros.
    assert!(stdout.contains("0 already in that state"), "{stdout}");
    assert!(stdout.contains("0 refused"), "{stdout}");
}

/// A retry is a **no-op** and says so, and appends no duplicate History event. The
/// exit status is non-zero, because "not every item did what was asked" is the
/// honest status for a no-op batch.
#[test]
fn t027_a_retry_is_a_no_op_with_no_duplicate_event() {
    let board = board();
    ok(
        board.path(),
        &[
            "bulk", "edit", "--select", "1", "--status", "wip", "--apply",
        ],
    );
    let (stdout, _) = code(
        board.path(),
        &[
            "bulk", "edit", "--select", "1", "--status", "wip", "--apply",
        ],
        1,
    );
    assert!(stdout.contains("already in that state"), "{stdout}");
    assert!(stdout.contains("0 of 1 applied"), "{stdout}");
    assert!(
        !stdout.contains("final paths:"),
        "nothing was written, so there are no final paths: {stdout}"
    );
    // And the file carries exactly one decision.
    let files = issues(board.path());
    let one = files
        .iter()
        .find(|(path, _)| path.contains("issue1"))
        .expect("issue 1's file");
    let text = String::from_utf8_lossy(&one.1);
    assert_eq!(
        text.matches("transition_accepted").count(),
        1,
        "one decision, not two: {text}"
    );
}

/// `--clear` empties a named field, and a field it does not support is a **usage
/// error naming the list** — so a user is not left guessing what else to try.
#[test]
fn t027_clear_empties_a_field_and_names_the_accepted_set() {
    let board = board();
    ok(
        board.path(),
        &[
            "bulk",
            "edit",
            "--select",
            "1",
            "--estimate",
            "3d",
            "--apply",
        ],
    );
    ok(
        board.path(),
        &[
            "bulk", "edit", "--select", "1", "--clear", "estimate", "--apply",
        ],
    );
    let files = issues(board.path());
    let one = files
        .iter()
        .find(|(path, _)| path.contains("issue1"))
        .expect("issue 1's file");
    let text = String::from_utf8_lossy(&one.1);
    assert!(
        !text.contains("estimate: 3d"),
        "the estimate is gone: {text}"
    );

    // `status` is not clearable, and `body` is not a field at all. Both are refused,
    // and the message quotes the accepted set.
    for field in ["status", "body"] {
        let (_, stderr) = code(
            board.path(),
            &["bulk", "edit", "--select", "1", "--clear", field],
            1,
        );
        assert!(
            stderr.contains(&format!("cannot clear '{field}'")),
            "{stderr}"
        );
        assert!(
            stderr.contains("clearable fields:"),
            "and the accepted set is named: {stderr}"
        );
    }
}

/// A **blank** flag is `Unchanged`, not `Clear` and not `Set("")`. `--estimate ""` is a
/// flag the user did not mean, and treating it as "empty it" is the class of bug
/// `PatchValue` exists to prevent — reached through the CLI this time.
#[test]
fn t027_a_blank_flag_is_unchanged_not_clear() {
    let board = board();
    let (_, stderr) = code(
        board.path(),
        &["bulk", "edit", "--select", "1", "--estimate", "", "--apply"],
        1,
    );
    assert!(stderr.contains("no fields to change"), "{stderr}");
    // And blank beside a real field: the real one applies, the blank one does not
    // clear anything. The exit is 0 because the batch did what it was asked — which
    // is the point: a blank flag is not a refusal, it is an absence.
    let (applied, _) = code(
        board.path(),
        &[
            "bulk",
            "edit",
            "--select",
            "1",
            "--estimate",
            "3d",
            "--assignee",
            "",
            "--apply",
        ],
        0,
    );
    assert!(applied.contains("1 of 1 applied"), "{applied}");
    let files = issues(board.path());
    let one = files
        .iter()
        .find(|(path, _)| path.contains("issue1"))
        .expect("issue 1's file");
    let text = String::from_utf8_lossy(&one.1);
    assert!(text.contains("estimate: 3d"), "{text}");
    assert!(
        text.contains(&format!("assignee: {}", tix::storage::actor_identity())),
        "and the blank assignee did not clear the identity: {text}"
    );
    // The estimate landed and the assignee survived, which is the claim. A whole-board
    // comparison against a pre-test snapshot would also be wrong here: this test
    // *does* apply the estimate, so the board is expected to change by exactly that.
}

/// No patch flag at all is a refusal naming the vocabulary, not an empty apply.
#[test]
fn t027_no_patch_flag_names_the_vocabulary() {
    let board = board();
    let (_, stderr) = code(board.path(), &["bulk", "edit", "--select", "1"], 1);
    assert!(stderr.contains("no fields to change"), "{stderr}");
    for name in ["status", "priority", "assignee", "labels", "estimate"] {
        assert!(stderr.contains(name), "'{name}' missing from: {stderr}");
    }
}

/// A bad priority is refused by the **same core** a single edit uses, so a bulk
/// priority cannot be a value `tix edit --priority` would reject.
#[test]
fn t027_a_bad_priority_uses_the_single_issue_core() {
    let board = board();
    let (_, stderr) = code(
        board.path(),
        &["bulk", "edit", "--select", "1", "--priority", "bogus"],
        1,
    );
    assert!(
        stderr.contains("invalid priority 'bogus'"),
        "the shared message: {stderr}"
    );
    // The same word the single-issue command says.
    let (_, single) = code(board.path(), &["edit", "1", "--priority", "bogus"], 1);
    assert!(single.contains("invalid priority 'bogus'"), "{single}");
}

// ---------------------------------------------------------------------------
// T028 — pair and archive
// ---------------------------------------------------------------------------

/// `tix bulk link` previews, then applies, and the files match what `tix link`
/// produces.
#[test]
fn t028_link_previews_then_applies() {
    let board = board();
    let before = snapshot(board.path());
    let stdout = ok(
        board.path(),
        &[
            "bulk", "link", "--select", "1", "--target", "2", "--type", "blocks",
        ],
    );
    assert_eq!(
        snapshot(board.path()),
        before,
        "a link preview writes nothing"
    );
    assert!(stdout.contains("would link"), "{stdout}");

    let applied = ok(
        board.path(),
        &[
            "bulk", "link", "--select", "1", "--target", "2", "--type", "blocks", "--apply",
        ],
    );
    assert!(
        applied.contains("1 relationship operation applied"),
        "{applied}"
    );
    // And the relationship is really there, addressed by the same grammar.
    let listed = ok(board.path(), &["link", "list", "1"]);
    assert!(listed.contains("#2"), "the edge is listed: {listed}");
    assert!(listed.contains("blocks"), "{listed}");
}

/// A missing target is a diagnostic for the pair, and **both** endpoints are
/// untouched.
#[test]
fn t028_a_missing_target_is_a_diagnostic_and_writes_nothing() {
    let board = board();
    let before = snapshot(board.path());
    let (stdout, _) = code(
        board.path(),
        &[
            "bulk", "link", "--select", "1", "--target", "no-such", "--type", "blocks", "--apply",
        ],
        1,
    );
    assert!(stdout.contains("refused"), "{stdout}");
    assert!(stdout.contains("no-such"), "the target is named: {stdout}");
    assert_eq!(snapshot(board.path()), before, "and nothing was written");
}

/// A retry is a no-op, reported, and appends no duplicate event.
#[test]
fn t028_a_link_retry_is_a_no_op() {
    let board = board();
    let args = [
        "bulk", "link", "--select", "1", "--target", "2", "--type", "blocks", "--apply",
    ];
    ok(board.path(), &args);
    let (stdout, _) = code(board.path(), &args, 1);
    assert!(
        stdout.contains("already in that state"),
        "a retry is reported, never silent: {stdout}"
    );
    let listed = ok(board.path(), &["link", "list", "1"]);
    assert_eq!(
        listed.matches("blocks").count(),
        1,
        "one relationship, not two: {listed}"
    );
}

/// `tix bulk archive` previews, then applies: each selected file is renamed **in
/// place** to a dot-prefixed name, and a re-run reports the no-op and writes nothing.
#[test]
fn t028_archive_previews_then_applies_and_a_re_run_is_a_no_op() {
    let board = board();
    let before = snapshot(board.path());

    // Preview is read-only and exits 0: archiving is performable, so a preview of it
    // is not a failure.
    let stdout = ok(board.path(), &["bulk", "archive", "--select", "1,2"]);
    assert_eq!(snapshot(board.path()), before, "a preview archives nothing");
    assert!(
        stdout.contains("archive: would archive 2 issues"),
        "the preview names the selection size, not a literal: {stdout}"
    );
    assert!(
        stdout.contains("2 issues would be archived"),
        "and the summary agrees with the line above it: {stdout}"
    );
    assert!(
        !stdout.contains("1 issue would be archived"),
        "the count is never the old hard-coded 1: {stdout}"
    );
    assert!(
        !stdout.contains("delegation pending"),
        "the delegation is no longer pending: {stdout}"
    );

    let applied = ok(
        board.path(),
        &["bulk", "archive", "--select", "1,2", "--apply"],
    );
    assert!(
        applied.contains("selection: 2 issues"),
        "the selection is named: {applied}"
    );
    assert!(
        applied.contains("#1 Issue1 -> applied") && applied.contains("#2 Issue2 -> applied"),
        "one outcome per selected item: {applied}"
    );
    assert!(
        applied.contains("2 of 2 applied; 0 already in that state; 0 refused"),
        "the apply count line is complete: {applied}"
    );
    assert!(applied.contains("final paths:"), "{applied}");

    // The marker is the filename: exactly the two selected files gained a dot-prefix,
    // in place, and nothing else entered or left the tree.
    let after = snapshot(board.path());
    let dot: Vec<&String> = after
        .iter()
        .map(|(p, _)| p)
        .filter(|p| {
            Path::new(p)
                .file_name()
                .is_some_and(|b| b.to_string_lossy().starts_with('.'))
        })
        .collect();
    assert_eq!(dot.len(), 2, "two files gained the marker: {after:?}");
    assert_eq!(
        after.len(),
        before.len(),
        "archiving renames in place: no file added or removed"
    );

    // The archived issues are hidden from the default view and shown with the flag.
    let listed = ok(board.path(), &["list"]);
    assert!(
        !listed.contains("Issue1") && !listed.contains("Issue2"),
        "archived issues are hidden by default: {listed}"
    );
    let with_archived = ok(board.path(), &["list", "--with-archived"]);
    for n in 1..=5 {
        assert!(
            with_archived.contains(&format!("Issue{n}")),
            "issue {n} is still there: {with_archived}"
        );
    }

    // A re-run is a reported no-op that writes nothing — not a failure of the batch,
    // but a non-zero status because nothing was applied (the same rule a link retry
    // follows).
    let (again, stderr) = code(
        board.path(),
        &["bulk", "archive", "--select", "1,2", "--apply"],
        1,
    );
    assert!(
        again.contains("already in that state"),
        "a retry is reported, never silent: {again}"
    );
    assert!(
        again.contains("0 of 2 applied; 2 already in that state; 0 refused"),
        "the no-ops are counted: {again}"
    );
    assert!(
        stderr.is_empty(),
        "a reported no-op is not an error on stderr: {stderr}"
    );
    assert_eq!(
        snapshot(board.path()),
        after,
        "and a no-op writes no bytes and appends no second event"
    );
}

// ---------------------------------------------------------------------------
// T029 — partial exit and final paths
// ---------------------------------------------------------------------------

/// A **partial** batch exits non-zero and retains every outcome.
///
/// The status is **1**, and the choice is stated because the table is frozen: 0 is
/// "everything requested happened", 2 is a whole-command selection failure, 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.
#[test]
fn t029_a_partial_batch_exits_non_zero_and_keeps_every_outcome() {
    let board = board();
    // #5 goes into `abandoned` — `canceled`, terminal — so the terminal lock refuses
    // it and #1 goes through.
    ok(board.path(), &["move", "5", "abandoned"]);
    let (stdout, _) = code(
        board.path(),
        &[
            "bulk", "edit", "--select", "1,5", "--status", "review", "--apply",
        ],
        1,
    );
    assert!(stdout.contains("#1 Issue1 -> applied"), "{stdout}");
    assert!(stdout.contains("#5 Issue5 -> refused"), "{stdout}");
    assert!(stdout.contains("1 of 2 applied"), "every count: {stdout}");
    assert!(stdout.contains("1 refused"), "{stdout}");
    assert!(
        stdout.contains("final paths:"),
        "and the paths that did change: {stdout}"
    );
    // The refused item is **not** partly applied, and nothing implies a rollback: the
    // output says the applied item is applied, not that the batch was undone.
    assert!(
        !stdout.contains("rolled back") && !stdout.contains("reverted"),
        "the output must not imply a rollback: {stdout}"
    );
    // And the applied one really moved.
    let moved = ok(board.path(), &["view", "1"]);
    assert!(moved.contains("review"), "#1 is in review: {moved}");
}

/// A fully successful batch exits **0**, so a script can tell the two apart.
#[test]
fn t029_a_successful_batch_exits_zero() {
    let first = board();
    code(
        first.path(),
        &[
            "bulk", "edit", "--select", "1,2", "--status", "wip", "--apply",
        ],
        0,
    );
    // A **preview** of a batch that will partly fail also exits non-zero, so a script
    // reading the preview's status knows before applying — and a preview of a fully
    // valid batch exits zero. A second fixture, because the first has been moved, and
    // named `fresh` because a local named `board` shadows the fixture function.
    let fresh = board();
    ok(fresh.path(), &["move", "5", "abandoned"]);
    code(
        fresh.path(),
        &["bulk", "edit", "--select", "1,5", "--status", "review"],
        1,
    );
    code(
        fresh.path(),
        &["bulk", "edit", "--select", "1,2", "--status", "review"],
        0,
    );
}

/// An empty selection is a **report of nothing**, not a failure — a filter that
/// matched no issues is a valid request, and the exit code says so.
#[test]
fn t029_an_empty_selection_is_not_a_failure() {
    let board = board();
    let stdout = ok(
        board.path(),
        &[
            "bulk",
            "edit",
            "--search",
            "no-such-issue-anywhere",
            "--status",
            "wip",
        ],
    );
    assert!(stdout.contains("selection: 0 issues"), "{stdout}");
    assert!(stdout.contains("0 of 0 would change"), "{stdout}");
}

// ---------------------------------------------------------------------------
// T030 — the existing single-issue surface is unchanged
// ---------------------------------------------------------------------------

/// The single-issue commands still work and still write what they always did.
///
/// `tix bulk` is a **new** command; nothing about the old ones may have moved. This
/// is the check the bulk mission's own contract asks for, and the reason the
/// `Command::Bulk` arm in `commands::dispatch` is an explicit refusal rather than a
/// silently-removed variant: a caller that reaches dispatch with a bulk command is
/// told why.
#[test]
fn t030_the_existing_single_issue_commands_are_unchanged() {
    let board = board();
    // create / view / list / edit / move / link / unlink / search, all in one fixture.
    ok(board.path(), &["view", "1"]);
    ok(board.path(), &["list"]);
    let searched = ok(board.path(), &["search", "Issue2"]);
    assert!(searched.contains("Issue2"), "{searched}");
    ok(board.path(), &["edit", "1", "--estimate", "5d"]);
    ok(board.path(), &["move", "1", "wip"]);
    let moved = ok(board.path(), &["view", "1"]);
    assert!(moved.contains("wip"), "{moved}");
    ok(board.path(), &["link", "1", "2", "--type", "blocks"]);
    let listed = ok(board.path(), &["link", "list", "1"]);
    assert!(listed.contains("blocks"), "{listed}");
    ok(board.path(), &["unlink", "1", "2", "--type", "blocks"]);
    let after = ok(board.path(), &["link", "list", "1"]);
    assert!(!after.contains("blocks"), "the edge is gone: {after}");
    // And `tix bulk` appears in the help, so the surface is discoverable.
    let help = ok(board.path(), &["bulk", "--help"]);
    assert!(help.contains("edit"), "{help}");
    assert!(help.contains("archive"), "{help}");
}

/// A `tix bulk` run does not disturb the exit code of an unrelated command, and the
/// bulk command's own failures use the **frozen** table: a missing selection is a
/// usage error (`1`), an unresolvable selector is not-found (`2`).
#[test]
fn t030_bulk_uses_the_frozen_exit_code_table() {
    let board = board();
    // A selector that matches nothing.
    let (_, stderr) = code(
        board.path(),
        &[
            "bulk",
            "edit",
            "--select",
            "no-such-issue",
            "--status",
            "wip",
        ],
        2,
    );
    assert!(stderr.contains("not found"), "{stderr}");
    // An ambiguous selector.
    ok(board.path(), &["create", "--title", "shared-thing"]);
    ok(board.path(), &["create", "--title", "shared-thing"]);
    // Two issues titled the same is not ambiguous for a *title* selector — the
    // selector is only ambiguous when it matches more than one, and both new issues
    // share a title, so a fragment of it matches two.
    let (_, stderr) = code(
        board.path(),
        &[
            "bulk",
            "edit",
            "--select",
            "shared-thing",
            "--status",
            "wip",
        ],
        2,
    );
    assert!(stderr.contains("ambiguous"), "{stderr}");
    // A usage error stays 1.
    let (_, _) = code(board.path(), &["bulk", "edit", "--status", "wip"], 1);
}

/// The `agents.rs` block documents the batch surface, and the documentation is
/// **generated** from the same vocabulary the surface uses — so the two cannot drift.
#[test]
fn t030_the_agents_documentation_covers_the_batch_surface() {
    let doc = tix::commands::bulk::agents_doc();
    for expected in [
        "tix bulk edit",
        "tix bulk link",
        "tix bulk unlink",
        "tix bulk archive",
        "--select",
        "--filter",
        "--search",
        "--apply",
        "rolled back",
        "delegates to the store's archive service",
    ] {
        assert!(doc.contains(expected), "'{expected}' missing from:\n{doc}");
    }
    // Every clearable field and every patch field is named, from the same constants
    // the parser reads.
    for field in tix::commands::bulk::PatchFlags::clearable() {
        assert!(doc.contains(field), "'{field}' missing from:\n{doc}");
    }
    for field in tix::bulk::IssuePatch::field_names() {
        assert!(doc.contains(field), "'{field}' missing from:\n{doc}");
    }
}