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
//! WP01 — selection and the typed patch.
//!
//! Two properties dominate, and both are stated in the mission's contracts rather
//! than invented here:
//!
//! - **Selection resolves once and does not write.** `contracts/patch-plan.md` §3
//!   requires a plan to be cancellable with no file, relationship, archive or
//!   History change; the only way that is guaranteed is if the value that
//!   authorizes a write is built by code that cannot write. So every test here
//!   snapshots the whole fixture directory and asserts it is byte-identical after.
//! - **Absent is not empty.** `PatchValue` exists because `Option` cannot tell
//!   "not mentioned" from "empty it", and conflating them is how a bulk
//!   `--clear-dates` clears the assignee too.

use std::fs;
use std::path::{Path, PathBuf};

use indexmap::IndexMap;

use tempfile::TempDir;
use tix::bulk::{
    IssuePatch, PatchValue, RelationshipOp, Selection, SelectionScope, SelectionSource,
    scope_metadata,
};
use tix::config::{BoardConfiguration, Config, KanbanSection};
use tix::model::{Issue, Priority, Status};
use tix::storage::Store;

// ---------------------------------------------------------------------------
// Fixture
// ---------------------------------------------------------------------------

/// A store on the **mapped** board the rest of the programme uses, with one issue
/// per column. The board matters: a `status` patch has to go through the
/// transition service, and on a board with no `category_map` that service imposes
/// no policy, so a policy assertion on the default board would pass vacuously.
fn store() -> (TempDir, Store) {
    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.clone(),
        kanban: KanbanSection {
            configurations: IndexMap::from([(
                "default".to_string(),
                BoardConfiguration {
                    columns: vec!["triage".into(), "wip".into(), "shipped".into()],
                    done_column: Some("shipped".to_string()),
                    category_map: IndexMap::from([
                        ("triage".to_string(), "backlog".to_string()),
                        ("wip".to_string(), "active".to_string()),
                        ("shipped".to_string(), "completed".to_string()),
                    ]),
                    ..Default::default()
                },
            )]),
        },
        ..Config::default()
    };
    config.save(&tmp.path().join("tix.toml")).unwrap();
    let config = Config::load_with_warning(&tmp.path().join("tix.toml"), |_| {}).unwrap();
    let store = Store {
        issues_dir: config.issues_dir.clone(),
        config,
    };
    for (i, column) in ["triage", "wip", "shipped"].iter().enumerate() {
        tix::commands::create::create(
            &store.config,
            &store,
            &format!("Issue{}", i + 1),
            None,
            Some(Status::new(*column)),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        )
        .unwrap();
    }
    (tmp, store)
}

/// Every byte under `dir`, as `(relative path, contents)`, sorted.
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 {
                let rel = path
                    .strip_prefix(dir)
                    .unwrap()
                    .to_string_lossy()
                    .to_string();
                out.push((rel, fs::read(&path).unwrap()));
            }
        }
    }
    out.sort();
    out
}

/// Write an extra issue file, creating the assignee segment if it is not there yet.
///
/// The segment is derived from the git identity, so the name is not knowable here
/// — the first version hard-coded `alice` and the two tests that added an issue by
/// hand failed on a `NotFound` for a directory nothing had created.
fn write_extra_issue(store: &Store, name: &str, number: u32, title: &str) {
    // The segment a create lands in is derived from the git identity; ask the
    // store for one of the paths it already knows about rather than guessing.
    let existing = fs::read_dir(&store.issues_dir)
        .unwrap()
        .map(|e| e.unwrap().path())
        .find(|p| p.is_dir())
        .expect("the fixture created at least one issue, so a segment exists");
    let dir = existing;
    fs::write(
        dir.join(name),
        format!(
            "---\nnumber: {number}\ntitle: \"{title}\"\nstatus: triage\nlabels: []\n\
             priority: medium\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n\
             ---\n\nbody\n"
        ),
    )
    .unwrap();
}

fn titles(selection: &Selection) -> Vec<String> {
    selection.issues().iter().map(|i| i.title.clone()).collect()
}

// ---------------------------------------------------------------------------
// T001 — explicit selector resolution
// ---------------------------------------------------------------------------

#[test]
fn t001_explicit_selectors_resolve_through_the_existing_grammar() {
    let (_tmp, store) = store();
    let selection = Selection::resolve(
        &store,
        &["1".to_string(), "2".to_string()],
        None,
        SelectionSource::Explicit,
        SelectionScope::Active,
    )
    .unwrap();
    assert_eq!(titles(&selection), vec!["Issue1", "Issue2"]);
    assert_eq!(selection.numbers(), vec![1, 2]);
    assert_eq!(selection.source(), SelectionSource::Explicit);
    assert_eq!(selection.scope(), SelectionScope::Active);
}

/// A number, a filename fragment and a title fragment all work, because
/// `parse_selector` already accepts all three. Asserted through the three
/// spellings so a future "bulk takes numbers only" shortcut would be caught.
#[test]
fn t001_a_number_a_fragment_and_a_title_all_resolve() {
    let (_tmp, store) = store();
    let by_number = Selection::resolve(
        &store,
        &["2".to_string()],
        None,
        SelectionSource::Explicit,
        SelectionScope::Active,
    )
    .unwrap();
    assert_eq!(titles(&by_number), vec!["Issue2"]);

    let issue = store.get(tix::storage::IssueSelector::Number(2)).unwrap();
    let by_filename = Selection::resolve(
        &store,
        std::slice::from_ref(&issue.filename),
        None,
        SelectionSource::Explicit,
        SelectionScope::Active,
    )
    .unwrap();
    assert_eq!(titles(&by_filename), vec!["Issue2"], "a filename fragment");

    let by_title = Selection::resolve(
        &store,
        &["Issue2".to_string()],
        None,
        SelectionSource::Explicit,
        SelectionScope::Active,
    )
    .unwrap();
    assert_eq!(titles(&by_title), vec!["Issue2"], "a title fragment");
}

/// The **existing** diagnostics, unwrapped. A wrapped failure reads
/// `not found: not found: issue matching …`, which is the doubled prefix a
/// relationship message already had once.
///
/// Asserted on **both** failure surfaces, because there are two and only one of
/// them was being reached: an unresolvable fragment fails inside `parse_selector`,
/// before any of this module's own error handling runs. A first version mutated
/// the `store.get` `map_err` and the case came back **green** — the mutation was on
/// a path this input never takes, so it proved nothing about the doubled prefix
/// and everything about how easy it is to write a case that looks like evidence.
#[test]
fn t001_not_found_is_the_existing_message_and_not_a_doubled_one() {
    let (_tmp, store) = store();

    // Surface 1: `parse_selector` cannot resolve the fragment at all.
    let from_parse = Selection::resolve(
        &store,
        &["no-such-issue".to_string()],
        None,
        SelectionSource::Explicit,
        SelectionScope::Active,
    )
    .unwrap_err()
    .to_string();
    assert!(
        from_parse.contains("no-such-issue"),
        "the message must name what the user typed: {from_parse}"
    );
    assert_eq!(
        from_parse.matches("not found").count(),
        1,
        "the prefix appears once, not nested: {from_parse}"
    );

    // Surface 2: a number that resolves as a selector but names no issue. This is
    // the path the `store.get` `map_err` exists for — `parse_selector` accepts any
    // number, so the failure lands in `get`.
    let from_get = Selection::resolve(
        &store,
        &["9999".to_string()],
        None,
        SelectionSource::Explicit,
        SelectionScope::Active,
    )
    .unwrap_err()
    .to_string();
    assert!(
        from_get.contains("9999"),
        "the message must name what the user typed: {from_get}"
    );
    assert_eq!(
        from_get.matches("not found").count(),
        1,
        "and the prefix still appears once: {from_get}"
    );
}

/// An **ambiguous** fragment is an error, exactly as it is for every other
/// command. A bulk selector that silently picked one of two matches would be a
/// bulk-only selector language, which contract §7 prohibits.
#[test]
fn t001_an_ambiguous_fragment_is_refused() {
    let (_tmp, store) = store();
    // Two issues whose filenames share a fragment.
    write_extra_issue(&store, "2026-01-01-shared-alpha.md", 90, "Shared alpha");
    write_extra_issue(&store, "2026-01-01-shared-beta.md", 91, "Shared beta");
    let result = Selection::resolve(
        &store,
        &["shared".to_string()],
        None,
        SelectionSource::Explicit,
        SelectionScope::Active,
    );
    assert!(
        result.is_err(),
        "an ambiguous fragment must be refused, not resolved to one of them"
    );
}

// ---------------------------------------------------------------------------
// T002 — filter and search selection
// ---------------------------------------------------------------------------

#[test]
fn t002_a_filter_query_selects_through_the_existing_token_matcher() {
    let (_tmp, store) = store();
    let selection = Selection::resolve(
        &store,
        &[],
        Some("status:shipped"),
        SelectionSource::Filter,
        SelectionScope::Active,
    )
    .unwrap();
    assert_eq!(titles(&selection), vec!["Issue3"]);
    assert_eq!(selection.query(), Some("status:shipped"));
}

#[test]
fn t002_a_search_query_uses_the_substring_matcher() {
    let (_tmp, store) = store();
    let selection = Selection::resolve(
        &store,
        &[],
        Some("Issue2"),
        SelectionSource::Search,
        SelectionScope::Active,
    )
    .unwrap();
    assert_eq!(titles(&selection), vec!["Issue2"]);
    // The two sources agree on a bare term (tix #1498): a **search** is
    // `search_substring` and a **filter**'s bare terms go through `query_matches`,
    // whose bare-term rule is the same contiguous, case-insensitive substring. The
    // filter's former subsequence (`fuzzy_score`) rule is gone precisely because it
    // was loose — `Issue2` matched **all three** documents, since the letters
    // `I`,`s`,`s`,`u`,`e`,`2` occur in order in each. Substring matching keeps the
    // token about the word it names.
    let filtered_bare = Selection::resolve(
        &store,
        &[],
        Some("Issue2"),
        SelectionSource::Filter,
        SelectionScope::Active,
    )
    .unwrap();
    assert_eq!(
        titles(&filtered_bare),
        vec!["Issue2"],
        "a filter's bare term is a substring match, like a search's"
    );

    // And the same for a `key:value` token: a search looks for the literal text,
    // which no file contains, while a filter interprets it as a criterion.
    let search_token = Selection::resolve(
        &store,
        &[],
        Some("status:shipped"),
        SelectionSource::Search,
        SelectionScope::Active,
    )
    .unwrap();
    assert!(
        search_token.is_empty(),
        "a search looks for the literal text, not a criterion"
    );
    let filter_token = Selection::resolve(
        &store,
        &[],
        Some("status:shipped"),
        SelectionSource::Filter,
        SelectionScope::Active,
    )
    .unwrap();
    assert_eq!(titles(&filter_token), vec!["Issue3"]);
}

#[test]
fn t002_selectors_and_a_query_are_unioned_with_selectors_first() {
    let (_tmp, store) = store();
    let selection = Selection::resolve(
        &store,
        &["1".to_string()],
        Some("status:shipped"),
        SelectionSource::Filter,
        SelectionScope::Active,
    )
    .unwrap();
    assert_eq!(
        titles(&selection),
        vec!["Issue1", "Issue3"],
        "explicit selectors lead, then the query's issues"
    );
}

#[test]
fn t002_an_empty_result_is_a_selection_not_an_error() {
    let (_tmp, store) = store();
    let selection = Selection::resolve(
        &store,
        &[],
        Some("status:no-such-column"),
        SelectionSource::Filter,
        SelectionScope::Active,
    )
    .unwrap();
    assert!(selection.is_empty());
    assert_eq!(selection.len(), 0);
    // A plan over an empty selection proposes zero changes, which is the honest
    // answer. Conflating it with an error would make `--dry-run` on a filter that
    // matched nothing look like a failure.
}

// ---------------------------------------------------------------------------
// T005 — deduplication, ordering, scope
// ---------------------------------------------------------------------------

#[test]
fn t005_duplicate_selectors_resolve_to_one_issue_and_are_reported() {
    let (_tmp, store) = store();
    let issue = store.get(tix::storage::IssueSelector::Number(1)).unwrap();
    let selection = Selection::resolve(
        &store,
        &[
            "1".to_string(),
            "1".to_string(),
            issue.filename.clone(),
            "Issue1".to_string(),
        ],
        None,
        SelectionSource::Explicit,
        SelectionScope::Active,
    )
    .unwrap();
    assert_eq!(selection.len(), 1, "one issue, not four");
    assert_eq!(selection.numbers(), vec![1]);
    // Three selectors named it: the repeat and the two alternate spellings. The
    // first spelling is the one that counted.
    assert_eq!(selection.duplicates().len(), 3, "each is reported");
    assert_eq!(selection.selectors(), &["1".to_string()]);
}

#[test]
fn t005_deduplication_is_by_issue_number_not_by_the_text_typed() {
    // `1` and the filename both name issue 1. De-duplicating on the text would
    // apply the patch to it twice, which is the failure the data-model calls
    // "the plan never double-writes an issue unintentionally".
    let (_tmp, store) = store();
    let issue = store.get(tix::storage::IssueSelector::Number(1)).unwrap();
    let selection = Selection::resolve(
        &store,
        &["1".to_string(), issue.filename.clone()],
        None,
        SelectionSource::Explicit,
        SelectionScope::Active,
    )
    .unwrap();
    assert_eq!(selection.len(), 1, "same issue, two spellings");
    assert_eq!(selection.duplicates(), &[issue.filename]);
}

#[test]
fn t005_order_is_the_order_the_user_typed() {
    let (_tmp, store) = store();
    let selection = Selection::resolve(
        &store,
        &["3".to_string(), "1".to_string()],
        None,
        SelectionSource::Explicit,
        SelectionScope::Active,
    )
    .unwrap();
    assert_eq!(titles(&selection), vec!["Issue3", "Issue1"]);
}

#[test]
fn t005_the_snapshot_does_not_grow_after_it_is_taken() {
    // The contract's "a selection is a stable ordered snapshot; apply does not
    // silently add issues that appeared after preview".
    let (_tmp, store) = store();
    let selection = Selection::resolve(
        &store,
        &["1".to_string()],
        None,
        SelectionSource::Explicit,
        SelectionScope::Active,
    )
    .unwrap();
    assert_eq!(selection.len(), 1);

    // A fourth issue appears. The snapshot must not see it.
    write_extra_issue(&store, "2026-01-01-late.md", 4, "Late arrival");
    assert_eq!(selection.len(), 1, "the snapshot is a value, not a query");
    assert_eq!(titles(&selection), vec!["Issue1"]);
}

#[test]
fn t005_the_fingerprint_is_membership_and_is_order_insensitive() {
    let (_tmp, store) = store();
    let a = Selection::resolve(
        &store,
        &["1".to_string(), "2".to_string()],
        None,
        SelectionSource::Explicit,
        SelectionScope::Active,
    )
    .unwrap();
    let b = Selection::resolve(
        &store,
        &["2".to_string(), "1".to_string()],
        None,
        SelectionSource::Explicit,
        SelectionScope::Active,
    )
    .unwrap();
    assert_eq!(a.fingerprint(), vec![1, 2]);
    // Same members, different order: still the same authorized set. A selection's
    // order is presentation; its membership is what an apply is authorized for.
    assert!(a.matches_fingerprint(&b.fingerprint()));
    let c = Selection::resolve(
        &store,
        &["1".to_string()],
        None,
        SelectionSource::Explicit,
        SelectionScope::Active,
    )
    .unwrap();
    assert!(
        !a.matches_fingerprint(&c.fingerprint()),
        "a subset is not the same"
    );
}

#[test]
fn t005_archived_scope_is_explicit_and_read_only() {
    let (_tmp, _store) = store();
    let active = scope_metadata(SelectionScope::Active, 3);
    assert!(active.can_write);
    assert!(!active.delegation_pending);
    assert_eq!(active.to_string(), "active (3 selected)");

    // The archive service (#190) does not exist yet, so an archived scope says so
    // rather than behaving as though archived issues were active ones.
    for scope in [
        SelectionScope::ActiveAndArchived,
        SelectionScope::ArchivedOnly,
    ] {
        let meta = scope_metadata(scope, 0);
        assert!(!meta.can_write, "{scope:?} must not be writable");
        assert!(meta.delegation_pending, "{scope:?} must say it is pending");
        assert!(
            meta.to_string().contains("read-only"),
            "and the message must say why: {meta}"
        );
    }
}

#[test]
fn t005_the_scope_vocabulary_is_three_words_and_closed() {
    assert_eq!(
        SelectionScope::parse("active").unwrap(),
        SelectionScope::Active
    );
    assert_eq!(
        SelectionScope::parse("ACTIVE").unwrap(),
        SelectionScope::Active,
        "case-insensitive, because the user types it"
    );
    assert_eq!(
        SelectionScope::parse("all").unwrap(),
        SelectionScope::ActiveAndArchived
    );
    assert_eq!(
        SelectionScope::parse("archived").unwrap(),
        SelectionScope::ArchivedOnly
    );
    let err = SelectionScope::parse("everything").unwrap_err().to_string();
    assert!(err.contains("unknown scope"), "{err}");
    for word in ["active", "active+archived", "archived"] {
        assert!(err.contains(word), "'{word}' missing from: {err}");
    }
}

// ---------------------------------------------------------------------------
// T003 — typed patch values
// ---------------------------------------------------------------------------

#[test]
fn t003_absent_is_not_clear() {
    // The whole reason `PatchValue` exists. An `Option` cannot tell these apart,
    // and collapsing them is how a bulk operation ends up clearing fields the
    // user never mentioned.
    let unchanged: PatchValue<String> = PatchValue::Unchanged;
    let clear: PatchValue<String> = PatchValue::Clear;
    assert!(unchanged.is_unchanged());
    assert!(!clear.is_unchanged());
    assert!(clear.is_clear());
    assert_eq!(unchanged.as_set(), None);
    assert_eq!(clear.as_set(), None);

    // And the `From<Option<T>>` conversion must not smuggle `None` in as a
    // clear. This is the one place the distinction could be lost, so it is pinned.
    assert_eq!(
        PatchValue::from(None::<String>),
        PatchValue::Unchanged,
        "`None` is absent, not empty"
    );
    assert_eq!(
        PatchValue::from(Some("high".to_string())),
        PatchValue::Set("high".to_string())
    );
}

#[test]
fn t003_an_empty_patch_names_nothing_and_says_so() {
    let patch = IssuePatch::default();
    assert!(patch.is_empty());
    let problems = patch.structural_problems();
    assert_eq!(problems.len(), 1);
    assert_eq!(problems[0].field, "patch");
    // The message lists what *could* have been named, so a user who typed nothing
    // is told what the patch vocabulary is.
    for name in IssuePatch::field_names() {
        assert!(
            problems[0].message.contains(name),
            "'{name}' missing from: {}",
            problems[0].message
        );
    }
    assert!(patch.require_wellformed().is_err());
}

#[test]
fn t003_a_patch_is_a_whitelist_with_no_escape_hatch() {
    // There is no syntax by which a caller can name a key that is not in the
    // contract. Asserted by the *shape*: the field set is a fixed list, and the
    // only way to reach an unlisted key would be a raw map, which the type does
    // not have.
    assert_eq!(
        IssuePatch::field_names(),
        &[
            "status",
            "priority",
            "assignee",
            "labels",
            "start-date",
            "due-date",
            "estimate",
            "cycles",
            "milestones",
        ]
    );
    let patch = IssuePatch {
        priority: PatchValue::Set(Priority::High),
        ..IssuePatch::default()
    };
    assert!(!patch.is_empty(), "one field is enough");
    assert!(
        patch.structural_problems().is_empty(),
        "one field is well-formed"
    );
}

#[test]
fn t003_a_field_patch_and_a_pair_in_one_patch_is_refused_rather_than_ordered() {
    // "What is the order" has no answer that is right for every pair of
    // operations, and an order invented here would be a policy nobody chose.
    let both = IssuePatch {
        status: PatchValue::Set("wip".to_string()),
        relationship: Some(RelationshipOp::link(
            "1",
            "2",
            tix::relationships::RelationKind::Blocks,
        )),
        ..IssuePatch::default()
    };
    let problems = both.structural_problems();
    assert_eq!(problems.len(), 1, "one problem, not two");
    let message = &problems[0].message;
    assert!(message.contains("field changes"), "{message}");
    assert!(message.contains("a relationship operation"), "{message}");

    // Archive plus pair is the same refusal.
    let archive_and_pair = IssuePatch {
        archive: Some(tix::bulk::ArchiveRequest::archive()),
        relationship: Some(RelationshipOp::unlink(
            "1",
            "2",
            tix::relationships::RelationKind::Blocks,
        )),
        ..IssuePatch::default()
    };
    assert!(!archive_and_pair.structural_problems().is_empty());

    // And each kind on its own is fine.
    for alone in [
        IssuePatch {
            status: PatchValue::Set("wip".to_string()),
            ..IssuePatch::default()
        },
        IssuePatch {
            relationship: Some(RelationshipOp::link(
                "1",
                "2",
                tix::relationships::RelationKind::Blocks,
            )),
            ..IssuePatch::default()
        },
        IssuePatch {
            archive: Some(tix::bulk::ArchiveRequest::archive()),
            ..IssuePatch::default()
        },
    ] {
        assert!(
            alone.structural_problems().is_empty(),
            "a single kind is well-formed: {alone:?}"
        );
    }
}

// ---------------------------------------------------------------------------
// T004 — pair and archive variants
// ---------------------------------------------------------------------------

#[test]
fn t004_a_pair_carries_an_explicit_operation_and_both_endpoints() {
    let link = RelationshipOp::link("3", "1", tix::relationships::RelationKind::Blocks);
    assert!(link.link);
    assert_eq!(link.verb(), "link");
    assert_eq!((link.from.as_str(), link.to.as_str()), ("3", "1"));

    let unlink = RelationshipOp::unlink("1", "3", tix::relationships::RelationKind::Blocks);
    assert!(!unlink.link);
    assert_eq!(unlink.verb(), "unlink");
    // The same endpoints, opposite operation — the pair is the *whole* request,
    // so the two differ only in the direction and there is nothing to infer.
    assert_eq!((unlink.from.as_str(), unlink.to.as_str()), ("1", "3"));
}

#[test]
fn t004_an_archive_request_carries_a_direction_and_no_semantics_of_its_own() {
    let archive = tix::bulk::ArchiveRequest::archive();
    let restore = tix::bulk::ArchiveRequest::restore("triage", None);
    assert!(archive.archive);
    assert!(!restore.archive);
    // There is no bulk-only archive behaviour to assert, because there is none:
    // the type is a direction and WP05 delegates it. A test that invented
    // semantics here would be testing the invention.
}

// ---------------------------------------------------------------------------
// T006 — dependency metadata and the no-write guarantee
// ---------------------------------------------------------------------------

/// The load-bearing one. `contracts/patch-plan.md` §3: a plan must be cancellable
/// with no file, relationship, archive or History change. The only way that is
/// guaranteed is if building a selection and a patch **cannot** write, and the
/// way to show that is to build both and assert the directory is untouched.
#[test]
fn t006_building_a_selection_and_a_patch_writes_nothing() {
    let (tmp, store) = store();
    let before = snapshot(tmp.path());

    let selection = Selection::resolve(
        &store,
        &["1".to_string(), "2".to_string()],
        Some("status:triage"),
        SelectionSource::Filter,
        SelectionScope::Active,
    )
    .unwrap();
    let patch = IssuePatch {
        status: PatchValue::Set("wip".to_string()),
        priority: PatchValue::Set(Priority::High),
        labels: PatchValue::Clear,
        relationship: Some(RelationshipOp::link(
            "1",
            "2",
            tix::relationships::RelationKind::Blocks,
        )),
        ..IssuePatch::default()
    };
    // Touch every accessor a plan would, so the snapshot covers the whole surface
    // rather than whatever the first two lines happened to reach.
    let _ = (
        selection.issues(),
        selection.numbers(),
        selection.selectors(),
        selection.duplicates(),
        selection.fingerprint(),
        selection.query(),
        selection.source(),
        selection.scope(),
    );
    let _ = (
        patch.is_empty(),
        patch.fields().count(),
        patch.structural_problems(),
        IssuePatch::field_names(),
        patch.relationship.as_ref().map(|r| r.verb()),
        patch.archive.map(|a| a.archive),
    );

    assert_eq!(
        snapshot(tmp.path()),
        before,
        "C-005: selection and patch construction are read-only — no file, no \
         History entry, no tix.toml write"
    );
}

#[test]
fn t006_both_phases_agree_on_what_an_issue_is() {
    // A selection carries whole `Issue` records rather than numbers, so the plan
    // phase validates against exactly the state the apply phase will write. If it
    // carried numbers, the two phases could disagree about an issue that changed
    // in between.
    let (_tmp, store) = store();
    let selection = Selection::resolve(
        &store,
        &["1".to_string()],
        None,
        SelectionSource::Explicit,
        SelectionScope::Active,
    )
    .unwrap();
    let issue: &Issue = &selection.issues()[0];
    assert_eq!(issue.number, 1);
    assert_eq!(issue.status.display(), "triage");
    // And the record is owned: `into_issues` hands it over, so a later stage can
    // mutate its own copy without the selection changing underneath it.
    let owned = selection.into_issues();
    assert_eq!(owned.len(), 1);
}

#[test]
fn t006_the_scope_of_a_selection_is_reported_for_the_plan_header() {
    let (_tmp, store) = store();
    let _ = &store;
    let selection = Selection::resolve(
        &store,
        &["1".to_string()],
        None,
        SelectionSource::Explicit,
        SelectionScope::Active,
    )
    .unwrap();
    let meta = scope_metadata(selection.scope(), selection.len());
    assert_eq!(meta.selected, 1);
    assert!(meta.can_write);
    assert_eq!(meta.to_string(), "active (1 selected)");
}

// ---------------------------------------------------------------------------
// The dependency note: what this WP does NOT own
// ---------------------------------------------------------------------------

/// WP01's owned files are `src/bulk.rs`, `src/bulk/selection.rs` and
/// `src/bulk/patch.rs`. This asserts the **module surface** rather than the file
/// list, because a module gaining a public item is a contract change the next
/// work packages depend on and a file list cannot see.
#[test]
fn t006_the_module_surface_is_what_the_contract_declares() {
    // Selection: resolve, and read-only accessors. There is deliberately **no**
    // `apply`, no `write`, no `save` — WP03 owns those, and a selection that could
    // write would break contract §3 at the type level.
    let (_tmp, store) = store();
    let selection = Selection::resolve(
        &store,
        &["1".to_string()],
        None,
        SelectionSource::Explicit,
        SelectionScope::Active,
    )
    .unwrap();
    let path = PathBuf::from(file!());
    assert!(
        path.ends_with("tests/bulk_selection.rs"),
        "this file is the selection test target: {}",
        path.display()
    );
    assert!(!selection.issues().is_empty());
    // The value is cloneable and comparable, which is what lets a plan hold it and
    // a later stage compare two of them.
    let copy = selection.clone();
    assert_eq!(copy, selection);
}