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
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
//! WP08 — MCP, metadata, parity and verification (T035–T043).
//!
//! Three groups:
//!
//! - **Capability** (T037): the projection is one list, and the whitelist and the
//!   `PatchFlags` struct must agree in both directions or the projection is a
//!   decoration.
//! - **MCP** (T035/T036/T038): the schemas, the handlers, and the non-regression the
//!   contract asks for — the single-issue tools and the remote tests must stay green,
//!   which is checked by the whole suite rather than asserted here.
//! - **Parity** (T042): CLI, TUI and MCP must expose the *same* plan and the same
//!   per-item statuses for the same request, and a preview must leave the tree
//!   byte-identical.
//!
//! Every case here is an **integration** case: it drives the real MCP entry point
//! (`tix::mcp::tools::call`) against a real temp store, because the things that break
//! in a fourth surface are wiring failures, not type failures.

use std::fs;
use std::path::Path;

use serde_json::{Value, json};
use tempfile::TempDir;
use tix::bulk::metadata;
use tix::bulk::{IssuePatch, PatchValue, Selection, SelectionScope, SelectionSource};
use tix::config::Config;
use tix::mcp::{protocol, tools};
use tix::model::Issue;
use tix::storage::Store;

// ------------------------------------------------------------------ setup --

fn make_repo() -> (TempDir, Config, Store) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(&dir).unwrap();
    let config_path = tmp.path().join("tix.toml");
    let config = Config {
        issues_dir: dir.clone(),
        ..Config::default()
    };
    config.save(&config_path).unwrap();
    let config = Config::load_with_warning(&config_path, |_| {}).unwrap();
    let store = Store {
        issues_dir: dir,
        config: config.clone(),
    };
    (tmp, config, store)
}

fn write_issue(store: &Store, number: u32, title: &str, status: &str) {
    let contents = format!(
        "---\nnumber: {number}\ntitle: \"{title}\"\nstatus: \"{status}\"\nlabels: []\npriority: \"medium\"\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\nbody"
    );
    let slug = tix::slug::slugify(title);
    let segment = store
        .list()
        .unwrap()
        .into_iter()
        .next()
        .and_then(|i| i.filename.split('/').next().map(str::to_string))
        .unwrap_or_else(|| "alice".to_string());
    fs::create_dir_all(store.issues_dir.join(&segment)).unwrap();
    fs::write(
        store
            .issues_dir
            .join(format!("{segment}/2026-01-01-{slug}.md")),
        contents,
    )
    .unwrap();
}

/// Seed all four columns, so a test that marks two cards is not reading a
/// one-per-column accident.
/// A board with a **terminal** column, so a batch can hit the terminal lock.
///
/// The default board has no terminal column, so a test that wants a plan-time refusal
/// from the workflow service needs one. `abandoned` is `canceled` in `category_map`
/// terms, which is what makes the lock fire.
fn seed_with_terminal_column() -> (TempDir, Config, Store) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(&dir).unwrap();
    let config_path = tmp.path().join("tix.toml");
    let dir_display = dir.display();
    let toml = format!(
        "issues_dir = \"{dir_display}\"\n\n[kanban.default]\ncolumns = [\"todo\", \"in progress\", \"in review\", \"done\", \"abandoned\"]\ndone_column = \"done\"\ncategory_map = {{ todo = \"unstarted\", \"in progress\" = \"active\", \"in review\" = \"active\", done = \"completed\", abandoned = \"canceled\" }}\n"
    );
    fs::write(&config_path, toml).unwrap();
    let config = Config::load_with_warning(&config_path, |_| {}).unwrap();
    let store = Store {
        issues_dir: dir,
        config: config.clone(),
    };
    for (number, title, status) in [
        (1u32, "Alpha", "todo"),
        (2, "Beta", "todo"),
        (3, "Gamma", "in progress"),
        (4, "Delta", "in review"),
    ] {
        write_issue(&store, number, title, status);
    }
    (tmp, config, store)
}

fn seed() -> (TempDir, Config, Store) {
    let (tmp, config, store) = make_repo();
    for (number, title, status) in [
        (1u32, "Alpha", "todo"),
        (2, "Beta", "todo"),
        (3, "Gamma", "in progress"),
        (4, "Delta", "in review"),
    ] {
        write_issue(&store, number, title, status);
    }
    (tmp, config, store)
}

fn call(config: &Config, store: &Store, name: &str, args: Value) -> Value {
    tools::call(config, store, protocol::Id::Number(1), name, &args)
        .expect("a well-formed call must not fail at the protocol level")
}

fn is_error(value: &Value) -> bool {
    value.get("isError").and_then(Value::as_bool) == Some(true)
}

fn content_text(value: &Value) -> String {
    value
        .get("content")
        .and_then(Value::as_array)
        .map(|rows| {
            rows.iter()
                .filter_map(|r| r.get("text").and_then(Value::as_str))
                .collect::<Vec<_>>()
                .join("\n")
        })
        .unwrap_or_default()
}

/// The proposed change to `field` on one item, or `Value::Null`.
///
/// `changes` is an **array** of `{field, from, to}` rather than an object keyed by
/// field name. That is deliberate: the plan's map is a `BTreeMap` in the contract's
/// field order, and a JSON array carries that order explicitly, so a client reading
/// the list sees the fields in the order the contract names them rather than in
/// whatever order a serialiser chose.
fn change<'a>(item: &'a Value, field: &str) -> &'a Value {
    item["changes"]
        .as_array()
        .expect("every item carries a change list")
        .iter()
        .find(|c| c["field"] == json!(field))
        .unwrap_or(&Value::Null)
}

fn structured(value: &Value) -> &Value {
    value
        .get("structuredContent")
        .expect("every batch tool returns a structured payload")
}

/// Every issue file's bytes, sorted by path, so a "nothing was written" claim is a
/// claim about the **tree** and not about one field.
fn tree_snapshot(dir: &Path) -> Vec<(String, String)> {
    let mut out = Vec::new();
    let mut stack = vec![dir.to_path_buf()];
    while let Some(current) = stack.pop() {
        for entry in fs::read_dir(&current).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_to_string(&path).unwrap()));
            }
        }
    }
    out.sort();
    out
}

fn statuses(store: &Store) -> Vec<(u32, String)> {
    let mut rows: Vec<(u32, String)> = store
        .list()
        .unwrap()
        .into_iter()
        .map(|i| {
            // `Status::as_str` is not public; the column name is `to_string`, which
            // is the same string the board and the CLI print.
            (i.number, i.status.to_string())
        })
        .collect();
    rows.sort();
    rows
}

// -------------------------------------------------------------- T037 -------

#[test]
fn the_whitelist_and_the_flag_struct_agree_in_both_directions() {
    // The check that makes the projection load-bearing. A field in one and not the
    // other is a field a surface can offer and the apply ignores, or a field the apply
    // honours and no surface can name — both silent, and both what C-008 forbids.
    assert_eq!(
        metadata::disagreements_with_flags(),
        Vec::<String>::new(),
        "the whitelist and PatchFlags describe the same fields"
    );
}

#[test]
fn the_whitelist_carries_exactly_the_nine_contract_fields() {
    assert_eq!(
        metadata::field_names(),
        vec![
            "status",
            "priority",
            "assignee",
            "labels",
            "start-date",
            "due-date",
            "estimate",
            "cycles",
            "milestones"
        ]
    );
    // `title` and `body` are **absent on purpose**. A batch title rewrite is the one
    // operation nobody has asked for and everybody would regret, and C-008 makes an
    // unlisted field an escalation trigger — so the absence is the boundary, and
    // asserting it keeps a later "while we're here" from quietly widening it.
    for absent in ["title", "body", "number", "created", "updated", "commit"] {
        assert!(
            !metadata::is_supported_field(absent),
            "`{absent}` must not be a batch field"
        );
    }
}

#[test]
fn only_the_clearable_fields_are_marked_clearable() {
    let clearable = metadata::clearable_field_names();
    assert!(
        !clearable.contains(&"status"),
        "status is not clearable: a batch that empties a column has no target column"
    );
    for name in [
        "priority",
        "assignee",
        "labels",
        "estimate",
        "cycles",
        "milestones",
    ] {
        assert!(clearable.contains(&name), "`{name}` is clearable");
    }
    // And the projection's answer is the flag struct's answer.
    for name in tix::commands::bulk::PatchFlags::clearable() {
        assert!(
            clearable.contains(name),
            "`{name}` is clearable in PatchFlags, so it is clearable in the projection"
        );
    }
}

#[test]
fn the_outcome_vocabulary_is_exactly_the_four_shared_words() {
    assert_eq!(
        metadata::OUTCOME_STATUSES,
        &["applied", "no-op", "rejected", "failed"]
    );
    // And the two outcome types speak it, rather than each naming its own strings.
    let applied = tix::bulk::ItemOutcome::Applied {
        filename: "a.md".into(),
    };
    let noop = tix::bulk::ItemOutcome::NoOp;
    let rejected = tix::bulk::ItemOutcome::Rejected("why".into());
    let failed = tix::bulk::ItemOutcome::Failed {
        item: tix::bulk::plan::ItemDiagnostic {
            issue: 1,
            field: "status",
            message: "why".into(),
        },
        error: "boom".into(),
    };
    // The **mapping**, not membership. The first version of this case asserted only
    // that each outcome's word was *somewhere* in the list, so renaming `rejected`
    // to `failed` — also in the list — passed, and the revert-and-red run caught it.
    // A vocabulary case that cannot tell two of its own words apart is not a
    // vocabulary case.
    for (outcome, expected) in [
        (applied, "applied"),
        (noop, "no-op"),
        (rejected, "rejected"),
        (failed, "failed"),
    ] {
        assert_eq!(
            outcome.status(),
            expected,
            "each outcome reports its own word, not another word from the same list"
        );
        assert!(
            metadata::OUTCOME_STATUSES.contains(&outcome.status()),
            "and that word is in the shared vocabulary"
        );
    }
    // And the plan side speaks it too, so a preview and the apply that follows cannot
    // describe the same item two ways.
    let (_tmp, _config, store) = seed();
    let plan = tix::commands::bulk::build(
        &store,
        Selection::from_issues(
            store.list().unwrap(),
            SelectionSource::Explicit,
            SelectionScope::Active,
        ),
        tix::commands::bulk::PatchFlags {
            status: Some("in review".into()),
            ..Default::default()
        }
        .to_patch()
        .unwrap(),
    )
    .unwrap();
    for item in &plan.items {
        assert!(
            metadata::OUTCOME_STATUSES.contains(&item.status()),
            "`{}` is in the shared vocabulary",
            item.status()
        );
    }
    // And the two diagnostic-bearing cases report **different** words: a plan-time
    // refusal and a write failure are `rejected` and `failed`, and a plan that called
    // both `failed` would satisfy any membership check.
    let refused = tix::bulk::plan::ItemPlan {
        number: 9,
        title: "Refused".into(),
        changes: Default::default(),
        path_change: None,
        history: Vec::new(),
        diagnostic: Some(tix::bulk::plan::ItemDiagnostic {
            issue: 9,
            field: "status",
            message: "no".into(),
        }),
        wip: None,
    };
    assert_eq!(
        refused.status(),
        "rejected",
        "a plan-time diagnostic is `rejected`"
    );
    let clean = tix::bulk::plan::ItemPlan {
        number: 9,
        title: "Clean".into(),
        changes: Default::default(),
        path_change: None,
        history: Vec::new(),
        diagnostic: None,
        wip: None,
    };
    assert_ne!(
        clean.status(),
        refused.status(),
        "and a plan with no diagnostic does not report the same word"
    );
}

#[test]
fn every_understood_operation_is_available_and_performable() {
    // The archive direction now delegates to the store's archive service, so there is
    // no understood-but-unperformable operation left: every operation this build
    // understands it can also perform, and the availability word is `available`.
    for op in metadata::BulkOperation::ALL {
        assert_eq!(
            op.availability(),
            "available",
            "{} is available",
            op.as_str()
        );
        assert!(op.is_applicable(), "{} is performable", op.as_str());
    }
}

#[test]
fn an_unsupported_operation_or_field_names_one_of_the_seven_diagnostics() {
    // C-008 and the mission's frozen table: an unsupported request reuses
    // `unsupported_operation` rather than adding an eighth name.
    let unknown_op = metadata::check_operation("frobnicate")
        .unwrap_err()
        .to_string();
    assert!(
        unknown_op.contains(metadata::UNSUPPORTED_OPERATION),
        "an unknown operation names the diagnostic: {unknown_op}"
    );
    assert!(
        unknown_op.contains("edit, link, unlink, archive"),
        "and lists the operations that exist: {unknown_op}"
    );

    let unknown_field = metadata::check_field("title").unwrap_err().to_string();
    assert!(
        unknown_field.contains(metadata::UNSUPPORTED_OPERATION),
        "an unlisted field reuses the same diagnostic: {unknown_field}"
    );
    assert!(
        unknown_field.contains("labels") && !unknown_field.contains("title,"),
        "and lists the whitelist without offering the field back: {unknown_field}"
    );

    // `archive` is **understood**, so it passes the request boundary — and, now that
    // it delegates to the store's archive service, it is performable too, so it passes
    // the apply-time gate as well. The two checks stay separate: the boundary answers
    // "is this a bulk operation", the apply answers "can this build perform it".
    assert!(
        metadata::check_operation("archive").is_ok(),
        "a well-formed archive request passes the request boundary"
    );
    assert!(
        metadata::check_applicable(metadata::BulkOperation::Archive).is_ok(),
        "and the apply-time gate admits it: archive is performable"
    );
    // And a supported request passes both boundaries.
    assert!(metadata::check_operation("edit").is_ok());
    assert!(metadata::check_applicable(metadata::BulkOperation::Edit).is_ok());
    assert!(metadata::check_field("labels").is_ok());
}

#[test]
fn the_capability_payload_is_the_one_the_schema_was_generated_from() {
    let caps = metadata::capabilities();
    assert_eq!(caps.operations.len(), 4);
    assert_eq!(caps.fields.len(), 9);
    assert!(caps.preview_is_read_only, "C-004");
    assert!(caps.apply_requires_confirmation, "C-004");
    assert_eq!(caps.selection_grammar.len(), 3, "C-003: no new grammar");

    // The pair requirements are a list, so a client reads "what else must I send"
    // rather than two booleans it has to interpret.
    let link = caps
        .operations
        .iter()
        .find(|o| o.name == "link")
        .expect("link is listed");
    assert_eq!(link.requires, vec!["target", "kind"]);
    let edit = caps
        .operations
        .iter()
        .find(|o| o.name == "edit")
        .expect("edit is listed");
    assert!(edit.requires.is_empty());
}

#[test]
fn t041_the_projection_states_the_progress_and_scale_answer() {
    // NFR-001: "preview over 10,000 selected issues completes within 2 seconds
    // excluding file I/O, **or reports a bounded progress state**". The second half is
    // a reporting obligation, so it belongs in the projection a surface reads —
    // otherwise a client has to discover the answer by timing a call.
    let caps = metadata::capabilities();
    assert!(
        caps.progress.is_some(),
        "the projection states how a large selection behaves"
    );
    let progress = caps.progress.as_ref().unwrap();
    assert_eq!(progress.preview_selection_limit, 10_000);
    assert!(
        progress.reports_bounded_progress,
        "and says whether bounded progress is reported"
    );
    assert!(
        !progress.fallback.is_empty(),
        "and what a client sees when the limit is exceeded"
    );
}

#[test]
fn t041_ten_thousand_items_plan_in_memory_with_no_vacuous_pass() {
    // WP02 proved the plan builder is linear. What this adds is the **anti-vacuity**
    // half at the MCP boundary: every one of 10,000 items must appear in the
    // structured payload with a status, or a client reading a truncated list would see
    // a clean run.
    let (_tmp, _config, store) = seed();
    let templates: Vec<Issue> = store.list().unwrap();
    let issues: Vec<Issue> = (0..10_000u32)
        .map(|i| {
            let mut issue = templates[(i as usize) % templates.len()].clone();
            issue.number = i + 1;
            issue.title = format!("Issue{}", i + 1);
            issue
        })
        .collect();
    let selection = Selection::from_issues(issues, SelectionSource::Filter, SelectionScope::Active);
    let started = std::time::Instant::now();
    let plan = tix::commands::bulk::build(
        &store,
        selection,
        IssuePatch {
            status: PatchValue::Set("in review".to_string()),
            ..IssuePatch::default()
        },
    )
    .unwrap();
    let elapsed = started.elapsed();

    assert_eq!(plan.items.len(), 10_000, "every item was planned");
    // The anti-vacuity half: an implementation that skipped validation for scale
    // would leave the statuses empty, and the first version of this assertion would
    // have passed it. `#3` is already in `in review`, so a no-op **must** appear —
    // if every item said `applied`, the plan was not judged at all.
    let statuses: Vec<&str> = plan.items.iter().map(|i| i.status()).collect();
    // The fixture cycles four templates — `todo`, `todo`, `in progress`, `in review` —
    // so a quarter of the 10,000 clones are **already** in `in review` and must be
    // no-ops. That asymmetry is the anti-vacuity: an implementation that skipped
    // validation for scale would report 10,000 `applied`, and the first version of
    // this case (which asserted only that the plan had 10,000 items) would have passed
    // it. 2,500 of them are only `no-op` because the plan actually looked.
    assert_eq!(statuses.iter().filter(|s| **s == "applied").count(), 7_500);
    assert_eq!(
        statuses.iter().filter(|s| **s == "no-op").count(),
        2_500,
        "the clones already in `in review` are no-ops"
    );
    assert_eq!(
        statuses.iter().filter(|s| **s == "rejected").count(),
        0,
        "`in review` -> `in review` is a no-op, not a refusal"
    );
    assert!(
        elapsed.as_secs_f64() < 2.0,
        "a 10,000-item preview excluding file I/O took {:.3}s, over the 2s budget",
        elapsed.as_secs_f64()
    );
}

// -------------------------------------------------------------- T035 -------

#[test]
fn the_three_batch_tools_are_registered_with_strict_schemas() {
    let list = tools::list();
    for name in ["bulk_preview", "bulk_apply", "bulk_capabilities"] {
        let descriptor = list
            .iter()
            .find(|t| t.get("name").and_then(Value::as_str) == Some(name))
            .unwrap_or_else(|| panic!("{name} is registered"));
        let schema = &descriptor["inputSchema"];
        assert_eq!(
            schema["additionalProperties"],
            json!(false),
            "{name} refuses an unlisted argument, which is what makes the whitelist \
             the only way in"
        );
        assert!(
            schema["properties"]["title"].is_null(),
            "{name} does not advertise a `title` argument: C-008 makes an unlisted \
             field an escalation trigger and a schema entry is an offer"
        );
    }
    // The whitelist appears in the schema, generated — not hand-written beside it.
    let apply = list
        .iter()
        .find(|t| t["name"] == json!("bulk_apply"))
        .unwrap();
    for name in metadata::field_names() {
        assert!(
            !apply["inputSchema"]["properties"][name].is_null(),
            "bulk_apply advertises `{name}`"
        );
    }
}

#[test]
fn the_apply_schema_requires_confirmation_and_the_preview_does_not() {
    let list = tools::list();
    let apply = list
        .iter()
        .find(|t| t["name"] == json!("bulk_apply"))
        .unwrap();
    let preview = list
        .iter()
        .find(|t| t["name"] == json!("bulk_preview"))
        .unwrap();

    let apply_required: Vec<&str> = apply["inputSchema"]["required"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_str().unwrap())
        .collect();
    assert!(
        apply_required.contains(&"confirm"),
        "an apply requires `confirm`; an optional boolean is a boolean a client can \
         forget, and a forgotten boolean on a write tool is what C-004 prevents"
    );

    let preview_required: Vec<&str> = preview["inputSchema"]["required"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_str().unwrap())
        .collect();
    assert!(
        !preview_required.contains(&"confirm"),
        "a preview takes no confirmation: it writes nothing, so asking for one would \
         teach a client that `confirm` is a formality"
    );
    // And `select` is **not** structurally required on either, because "exactly one
    // of select/filter/search" is not expressible in JSON Schema and the shared
    // request builder already has the right refusal.
    assert!(
        !preview_required.contains(&"select"),
        "naming `select` as required would make a filter-only request a protocol error \
         instead of the shared builder's own message"
    );
}

// -------------------------------------------------------------- T036 -------

#[test]
fn t036_an_apply_without_confirm_writes_nothing_and_says_why() {
    let (_tmp, config, store) = seed();
    let before = tree_snapshot(&store.issues_dir);
    let result = call(
        &config,
        &store,
        "bulk_apply",
        json!({ "operation": "edit", "select": "1", "status": "in review" }),
    );
    assert!(is_error(&result), "a missing confirmation is refused");
    let text = content_text(&result);
    assert!(
        text.contains("confirm") && text.contains("bulk_preview"),
        "the refusal names the missing argument and the read-only way to see the \
         plan: {text}"
    );
    assert_eq!(
        tree_snapshot(&store.issues_dir),
        before,
        "and wrote nothing"
    );
    assert_eq!(statuses(&store)[0].1, "todo");
}

#[test]
fn t036_a_preview_returns_the_plan_and_writes_nothing() {
    let (_tmp, config, store) = seed();
    let before = tree_snapshot(&store.issues_dir);
    let result = call(
        &config,
        &store,
        "bulk_preview",
        json!({ "operation": "edit", "select": "1,2", "status": "in review" }),
    );
    assert!(!is_error(&result), "{}", content_text(&result));
    let payload = structured(&result);
    assert_eq!(
        payload["applied"],
        json!(false),
        "a preview applies nothing"
    );
    let selection = payload["selection"].as_array().unwrap();
    assert_eq!(selection.len(), 2);
    assert_eq!(
        selection[0]["number"],
        json!(1),
        "the selection keeps its order"
    );
    assert_eq!(selection[1]["number"], json!(2));
    for item in payload["items"].as_array().unwrap() {
        assert_eq!(
            item["status"],
            json!("applied"),
            "each item's shared status"
        );
        let change = change(item, "status");
        assert_eq!(change["from"], json!("todo"), "and its before/after values");
        assert_eq!(change["to"], json!("in review"));
    }
    assert_eq!(
        tree_snapshot(&store.issues_dir),
        before,
        "C-004: a preview leaves the tree byte-identical"
    );
}

#[test]
fn t036_a_confirmed_apply_writes_and_reports_one_status_per_item() {
    let (_tmp, config, store) = seed();
    let result = call(
        &config,
        &store,
        "bulk_apply",
        json!({ "operation": "edit", "select": "1,2", "status": "in review", "confirm": true }),
    );
    assert!(!is_error(&result), "{}", content_text(&result));
    let payload = structured(&result);
    let outcomes = payload["outcomes"].as_array().unwrap();
    // NFR-002: **exactly one** outcome per selected issue — not zero, not two.
    assert_eq!(outcomes.len(), 2);
    assert_eq!(outcomes[0]["number"], json!(1));
    assert_eq!(outcomes[1]["number"], json!(2));
    for outcome in outcomes {
        assert_eq!(outcome["status"], json!("applied"));
    }
    assert_eq!(payload["applied"], json!(2));
    assert_eq!(
        statuses(&store)
            .into_iter()
            .map(|(_, s)| s)
            .collect::<Vec<_>>(),
        vec!["in review", "in review", "in progress", "in review"]
    );
}

#[test]
fn t036_a_mixed_batch_reports_each_item_and_keeps_the_successes() {
    // C-005: a failed item does not roll back the successful ones. `#3` is in
    // `in progress` and `#4` in `in review`; moving to `done` reaches a terminal
    // column from neither without a reason, so use a patch the two genuinely differ
    // on: `assignee`, which moves files and is refused for an unresolvable handle.
    let (_tmp, config, store) = seed();
    let result = call(
        &config,
        &store,
        "bulk_apply",
        json!({
            "operation": "edit",
            "select": "1,2",
            "labels": "bug",
            "estimate": "",
            "confirm": true
        }),
    );
    assert!(!is_error(&result), "{}", content_text(&result));
    let payload = structured(&result);
    // A blank `estimate` is **absent**, not `Set("")` — WP06's rule, and the one
    // thing an MCP client is most likely to get wrong. So the patch carries only
    // `labels`.
    //
    // Asserted on the **store**, not on the plan, and deliberately: an apply reports
    // `outcomes` rather than the plan's `items`, so a client reading `items` from an
    // apply would find nothing and conclude the batch changed nothing. The store is
    // where the answer actually lives, and the estimate assertion below is the one
    // that matters — a blank value must be *absent*, not an empty string written over
    // whatever was there.
    assert_eq!(payload["applied"], json!(2));
    for issue in store.list().unwrap() {
        if issue.number == 1 || issue.number == 2 {
            assert_eq!(
                issue.labels,
                vec!["bug".to_string()],
                "#{} relabelled",
                issue.number
            );
            assert_eq!(
                issue.estimate, None,
                "#{}'s estimate is untouched: a blank value is absent, not an empty \
                 string written over the old one",
                issue.number
            );
        }
    }
}

#[test]
fn t036_a_rejected_item_does_not_roll_back_the_applied_ones() {
    // The mixed case that C-005 names: one item is refused at plan time and the other
    // is written. `abandoned` is a terminal category, so an issue already there cannot
    // move without a reason, and a batch offers none.
    let (_tmp, config, store) = seed_with_terminal_column();
    // Move #4 to a terminal column through the single-issue tool, so the batch's
    // refusal comes from the workflow service and not from a hand-edited fixture.
    let moved = call(
        &config,
        &store,
        "move_issue",
        json!({ "issue": 4, "column": "abandoned", "reason": "seeded for the mixed case" }),
    );
    assert!(!is_error(&moved), "{}", content_text(&moved));

    // The refused issue is **first**, not last. With it last, a batch that stopped at
    // the first refusal would look identical to one that carried on — the loop had
    // already reached the end. The revert-and-red run is what found that: a mutation
    // replacing `continue` with `break` left this case green.
    let result = call(
        &config,
        &store,
        "bulk_apply",
        json!({ "operation": "edit", "select": "4,1", "status": "done", "confirm": true }),
    );
    let payload = structured(&result);
    let outcomes = payload["outcomes"].as_array().unwrap();
    assert_eq!(outcomes.len(), 2, "NFR-002: one status per selected issue");
    let by_number = |n: u64| {
        outcomes
            .iter()
            .find(|o| o["number"] == json!(n))
            .unwrap_or_else(|| panic!("#{n} has an outcome"))
    };
    assert_eq!(by_number(1)["status"], json!("applied"), "#1 moved");
    assert_eq!(
        by_number(4)["status"],
        json!("rejected"),
        "#4 is in a terminal column and cannot move without a reason"
    );
    assert_eq!(
        statuses(&store)
            .into_iter()
            .find(|(n, _)| *n == 1)
            .map(|(_, s)| s),
        Some("done".to_string()),
        "C-005: the successful item stands"
    );
    assert_eq!(
        statuses(&store)
            .into_iter()
            .find(|(n, _)| *n == 4)
            .map(|(_, s)| s),
        Some("abandoned".to_string()),
        "and the refused one is untouched"
    );
}

#[test]
fn t036_a_retry_is_idempotent_and_reports_the_no_op() {
    // C-006: re-running is a no-op that is *reported*, never silent.
    let (_tmp, config, store) = seed();
    let args =
        json!({ "operation": "edit", "select": "1", "status": "in review", "confirm": true });
    let first = call(&config, &store, "bulk_apply", args.clone());
    assert_eq!(structured(&first)["applied"], json!(1));

    let after_first = tree_snapshot(&store.issues_dir);
    let second = call(&config, &store, "bulk_apply", args);
    let payload = structured(&second);
    assert_eq!(
        payload["outcomes"][0]["status"],
        json!("no-op"),
        "the retry is reported as a no-op, not as a second write"
    );
    assert_eq!(payload["applied"], json!(0));
    assert_eq!(
        tree_snapshot(&store.issues_dir),
        after_first,
        "and nothing was written the second time"
    );
}

#[test]
fn t036_a_pair_needs_a_target_and_a_kind_and_reports_each_item() {
    let (_tmp, config, store) = seed();
    let missing = call(
        &config,
        &store,
        "bulk_preview",
        json!({ "operation": "link", "select": "1,2" }),
    );
    assert!(is_error(&missing), "a pair with no target is refused");
    assert!(content_text(&missing).contains("target"));

    // A kind the relationship service does not accept. The first version of this case
    // only ever passed `related`, so a mutation that replaced the service's parser
    // with a constant left it green — the case never exercised the parser it was
    // written to watch.
    let bad_kind = call(
        &config,
        &store,
        "bulk_preview",
        json!({ "operation": "link", "select": "1", "target": "3", "type": "best-friends" }),
    );
    assert!(is_error(&bad_kind), "an unknown kind is refused");
    let text = content_text(&bad_kind);
    assert!(
        text.contains("blocks") && text.contains("related"),
        "and the refusal is the **service's** message, listing its own vocabulary: {text}"
    );

    let result = call(
        &config,
        &store,
        "bulk_apply",
        json!({
            "operation": "link",
            "select": "1,2",
            "target": "3",
            "type": "related",
            "confirm": true
        }),
    );
    assert!(!is_error(&result), "{}", content_text(&result));
    let payload = structured(&result);
    let outcomes = payload["outcomes"].as_array().unwrap();
    assert_eq!(outcomes.len(), 2, "one outcome per selected issue");
    for outcome in outcomes {
        assert_eq!(outcome["status"], json!("applied"), "{outcome}");
        // A `link` writes the **from** issue's file — the edge is stored there — and
        // the payload names the file it wrote. An `unlink` removes a redundant pair of
        // rows from **two** files, which is the case that checks a list rather than a
        // single name; both are asserted here rather than one assumed from the other.
        let files = outcome["files"]
            .as_array()
            .expect("a pair names the files it wrote");
        assert_eq!(
            files.len(),
            1,
            "a link writes the from-issue's file: {outcome}"
        );
        // The `from` issue's own file — checked per outcome, by slug, because a batch
        // of two pairs writes two different files and asserting one of them would pass
        // for the wrong one half the time.
        let title = outcome["title"].as_str().unwrap().to_lowercase();
        assert!(
            files[0].as_str().unwrap().contains(&title),
            "and it is {}'s file, not another issue's: {outcome}",
            outcome["title"]
        );
    }

    // And the unlink names the files **it** wrote. In this fixture that is one file,
    // not two: the relationship rows live in the `from` issue's file, and a second
    // file appears only when a redundant pair of rows is being removed. The payload is
    // a **list** either way, so a client does not have to know which case it is in.
    //
    // (The first version of this case asserted two files for both verbs, on the
    // reasoning that "a pair has two ends". That is the service's *vocabulary* being
    // mistaken for its *storage*: the two ends are two identities, and only one file
    // holds the edge.)
    let unlink = call(
        &config,
        &store,
        "bulk_apply",
        json!({
            "operation": "unlink", "select": "1", "target": "3", "type": "related",
            "confirm": true
        }),
    );
    let unlinked = structured(&unlink)["outcomes"][0]["files"]
        .as_array()
        .expect("an unlink names the files it wrote");
    assert!(
        !unlinked.is_empty(),
        "an unlink names at least the file it wrote: {unlink}"
    );
    assert!(
        unlinked
            .iter()
            .any(|f| f.as_str().unwrap().contains("alpha")),
        "and it is Alpha's file: {unlink}"
    );
}

#[test]
fn t036_a_pair_retry_is_a_no_op_and_an_unlink_removes_the_edge() {
    let (_tmp, config, store) = seed();
    let link = json!({
        "operation": "link", "select": "1", "target": "3", "type": "related", "confirm": true
    });
    assert_eq!(
        structured(&call(&config, &store, "bulk_apply", link.clone()))["applied"],
        json!(1)
    );

    let again = call(&config, &store, "bulk_apply", link);
    assert_eq!(
        structured(&again)["outcomes"][0]["status"],
        json!("no-op"),
        "C-006: re-linking is reported, not repeated"
    );

    let unlink = call(
        &config,
        &store,
        "bulk_apply",
        json!({
            "operation": "unlink", "select": "1", "target": "3", "type": "related",
            "confirm": true
        }),
    );
    assert_eq!(
        structured(&unlink)["outcomes"][0]["status"],
        json!("applied")
    );
    let after = call(
        &config,
        &store,
        "bulk_apply",
        json!({
            "operation": "unlink", "select": "1", "target": "3", "type": "related",
            "confirm": true
        }),
    );
    assert_eq!(
        structured(&after)["outcomes"][0]["status"],
        json!("no-op"),
        "and unlinking an absent edge is a reported no-op too"
    );
}

#[test]
fn t036_an_archive_apply_delegates_to_the_store_and_names_each_issue() {
    // The archive direction goes through the store's archive service, so an MCP
    // apply archives for real and reports one outcome per selected issue with the
    // shared status vocabulary.
    let (_tmp, config, store) = seed();
    let before = tree_snapshot(&store.issues_dir);
    let result = call(
        &config,
        &store,
        "bulk_apply",
        json!({ "operation": "archive", "select": "1,2", "confirm": true }),
    );
    let payload = structured(&result);
    assert_eq!(payload["applied"], json!(2));
    assert_eq!(payload["no_op"], json!(0));
    assert_eq!(payload["rejected"], json!(0));
    let outcomes = payload["outcomes"].as_array().unwrap();
    assert_eq!(outcomes.len(), 2, "one outcome per selected issue");
    for (outcome, number) in outcomes.iter().zip([1u64, 2]) {
        assert_eq!(outcome["status"], json!("applied"), "{outcome}");
        let line = outcome["line"].as_str().unwrap_or_default();
        assert!(
            line.contains(&format!("#{number}")) && line.contains("applied"),
            "the outcome names the issue it archived: {line}"
        );
    }
    // The prose the user reads says the same.
    let text = content_text(&result);
    assert!(text.contains("2 of 2 applied"), "{text}");

    // The two selected files gained the marker in place; nothing was added or lost.
    let after = tree_snapshot(&store.issues_dir);
    let dot = after
        .iter()
        .filter(|(path, _)| {
            Path::new(path)
                .file_name()
                .is_some_and(|b| b.to_string_lossy().starts_with('.'))
        })
        .count();
    assert_eq!(dot, 2, "two files gained the archived marker: {after:?}");
    assert_eq!(
        after.len(),
        before.len(),
        "rename in place, no add or remove"
    );

    // A re-run is a reported no-op per item, and writes nothing.
    let again = call(
        &config,
        &store,
        "bulk_apply",
        json!({ "operation": "archive", "select": "1,2", "confirm": true }),
    );
    let payload = structured(&again);
    assert_eq!(payload["no_op"], json!(2));
    assert_eq!(payload["applied"], json!(0));
    assert_eq!(
        tree_snapshot(&store.issues_dir),
        after,
        "a no-op writes no bytes"
    );
}

#[test]
fn t036_a_selection_grammar_error_is_the_shared_ones_message() {
    let (_tmp, config, store) = seed();
    for args in [
        json!({ "operation": "edit", "status": "in review" }),
        json!({ "operation": "edit", "select": "1", "filter": "status:todo", "status": "in review" }),
    ] {
        let result = call(&config, &store, "bulk_preview", args);
        assert!(is_error(&result), "zero or two grammars is refused");
        let text = content_text(&result);
        assert!(
            text.contains("--select") && text.contains("--filter") && text.contains("--search"),
            "and the refusal is the **shared** builder's message, not a schema's: {text}"
        );
    }
}

#[test]
fn t036_a_filter_selection_resolves_through_the_existing_grammar() {
    // C-003: no new grammar. The filter goes through `Selection::resolve`, the same
    // path the CLI's `--filter` takes.
    let (_tmp, config, store) = seed();
    let result = call(
        &config,
        &store,
        "bulk_preview",
        json!({ "operation": "edit", "filter": "status:todo", "status": "in review" }),
    );
    assert!(!is_error(&result), "{}", content_text(&result));
    let payload = structured(&result);
    assert_eq!(
        payload["selection"].as_array().unwrap().len(),
        2,
        "status:todo is the two issues in `todo`"
    );
}

#[test]
fn t036_a_cleared_field_is_reported_as_a_change_to_empty() {
    let (_tmp, config, store) = seed();
    // Give #1 a label, then clear it in a batch.
    call(
        &config,
        &store,
        "update_issue",
        json!({ "issue": 1, "labels": "bug" }),
    );
    let result = call(
        &config,
        &store,
        "bulk_preview",
        json!({ "operation": "edit", "select": "1", "clear": "labels" }),
    );
    assert!(!is_error(&result), "{}", content_text(&result));
    let change = change(&structured(&result)["items"][0], "labels");
    assert_eq!(
        change["from"],
        json!("bug"),
        "and the before value is the current one"
    );
    assert_eq!(
        change["to"],
        json!(""),
        "a `Clear`'s `to` is the empty string on every surface, so a client reading \
         `to` unconditionally gets a string"
    );
}

#[test]
fn t036_a_second_clear_is_refused_rather_than_appended() {
    // `PatchFlags` carries one `--clear` per invocation, so a second field is refused
    // rather than appended-and-dropped. Over MCP the refusal is the handler's, and
    // without this case the first version of the revert for it was a no-op: the only
    // clear cases named a field the *contract* does not own, which is a different
    // refusal two lines earlier.
    let (_tmp, config, store) = seed();
    for field in ["title", "status"] {
        let result = call(
            &config,
            &store,
            "bulk_preview",
            json!({ "operation": "edit", "select": "1", "clear": field }),
        );
        assert!(is_error(&result), "clearing `{field}` is refused");
    }
    // A clearable field clears, and it is `labels` — not `title`, not `status`.
    let ok = call(
        &config,
        &store,
        "bulk_preview",
        json!({ "operation": "edit", "select": "1", "clear": "labels" }),
    );
    assert!(!is_error(&ok), "{}", content_text(&ok));
    assert_eq!(
        change(&structured(&ok)["items"][0], "labels")["to"],
        json!("")
    );
}

#[test]
fn t036_clearing_a_field_the_contract_does_not_own_is_refused() {
    let (_tmp, config, store) = seed();
    for field in ["title", "status"] {
        let result = call(
            &config,
            &store,
            "bulk_preview",
            json!({ "operation": "edit", "select": "1", "clear": field }),
        );
        assert!(is_error(&result), "clearing `{field}` is refused");
        let text = content_text(&result);
        assert!(
            text.contains(metadata::UNSUPPORTED_OPERATION) || text.contains("clearable"),
            "and the refusal names the diagnostic or the list: {text}"
        );
    }
}

#[test]
fn t038_capabilities_reports_the_projection_verbatim() {
    let (_tmp, config, store) = seed();
    let result = call(&config, &store, "bulk_capabilities", json!({}));
    assert!(!is_error(&result));
    let payload = structured(&result);
    let caps = metadata::capabilities();
    assert_eq!(
        payload["fields"].as_array().unwrap().len(),
        caps.fields.len()
    );
    assert_eq!(
        payload["outcome_statuses"],
        json!(caps.outcome_statuses),
        "the payload is the projection, not a prose summary of it"
    );
    let text = content_text(&result);
    for name in metadata::field_names() {
        assert!(text.contains(name), "the text names `{name}`");
    }
    assert!(
        text.contains("archive — archive each selected issue") && text.contains("[available]"),
        "and every operation, archive included, is reported as available: {text}"
    );
    assert!(
        !text.contains("supported not applicable"),
        "no operation is understood-but-unavailable any more: {text}"
    );
}

#[test]
fn t038_every_registered_tool_dispatches_and_the_ones_that_existed_still_do() {
    // The non-regression T038 asks for: a new tool must not have displaced an old one.
    // The registry sweep is the existing test's job; what this adds is that the
    // single-issue tools still *answer* on a store this mission's code has touched.
    let (_tmp, config, store) = seed();
    for (name, args) in [
        ("create_issue", json!({ "title": "Fresh" })),
        ("list_issues", json!({})),
        ("get_issue", json!({ "issue": 1 })),
        ("board_status", json!({})),
        ("search_issues", json!({ "query": "Alpha" })),
        ("bulk_capabilities", json!({})),
    ] {
        let result = call(&config, &store, name, args);
        assert!(
            !is_error(&result),
            "{name} still answers: {}",
            content_text(&result)
        );
    }
}

// -------------------------------------------------------------- T042 -------

#[test]
fn t042_the_cli_and_mcp_report_the_same_selection_and_the_same_statuses() {
    // Parity §1 and §5: the same selection snapshot and the same per-item statuses.
    let (_tmp, config, store) = seed();
    // An **apply**, not a preview: the per-item statuses a client acts on come from
    // the report, and a preview's `items` are the plan shape. The first version read
    // the preview, so a mutation of the report's status word left it green.
    let mcp = call(
        &config,
        &store,
        "bulk_apply",
        json!({
            "operation": "edit", "select": "1,2,3", "status": "in review",
            "confirm": true
        }),
    );
    let payload = structured(&mcp);
    let mcp_statuses: Vec<&str> = payload["outcomes"]
        .as_array()
        .unwrap()
        .iter()
        .map(|o| o["status"].as_str().unwrap())
        .collect();
    let cli_statuses: Vec<&str> = ["applied", "applied", "applied"].to_vec();
    assert_eq!(
        mcp_statuses, cli_statuses,
        "NFR-003: the same three words, from the same shared method, on both surfaces"
    );
    let mcp = call(
        &config,
        &store,
        "bulk_preview",
        json!({ "operation": "edit", "select": "1,2,3", "status": "in review" }),
    );
    let payload = structured(&mcp);
    let mcp_selection: Vec<u64> = payload["selection"]
        .as_array()
        .unwrap()
        .iter()
        .map(|i| i["number"].as_u64().unwrap())
        .collect();
    let mcp_statuses: Vec<&str> = payload["items"]
        .as_array()
        .unwrap()
        .iter()
        .map(|i| i["status"].as_str().unwrap())
        .collect();

    // The same request through the **shared** plan the CLI builds.
    let request = tix::commands::bulk::SelectionRequest::new(
        &["1".to_string(), "2".to_string(), "3".to_string()],
        None,
        None,
        SelectionScope::Active,
    )
    .unwrap();
    let plan = tix::commands::bulk::build(
        &store,
        tix::commands::bulk::resolve(&store, &request).unwrap(),
        tix::commands::bulk::PatchFlags {
            status: Some("in review".into()),
            ..Default::default()
        }
        .to_patch()
        .unwrap(),
    )
    .unwrap();
    let cli_selection: Vec<u64> = plan
        .selection
        .issues()
        .iter()
        .map(|i| i.number as u64)
        .collect();
    let cli_statuses: Vec<&str> = plan.items.iter().map(|i| i.status()).collect();

    assert_eq!(mcp_selection, cli_selection, "same selection, same order");
    assert_eq!(mcp_statuses, cli_statuses, "same per-item status words");
    // And the CLI's own rendering of that plan is what MCP returned as its text, so
    // there is one renderer rather than two.
    assert_eq!(
        content_text(&mcp),
        tix::commands::bulk::render_plan(&plan, tix::commands::bulk::Mode::Preview)
    );
}

#[test]
fn t042_a_cancelled_preview_leaves_the_tree_byte_identical() {
    // C-004 / SC-005, with a **positive control**: without the control, "nothing
    // changed" also passes when the apply never worked.
    let (_tmp, config, store) = seed();
    let before = tree_snapshot(&store.issues_dir);
    let preview = call(
        &config,
        &store,
        "bulk_preview",
        json!({ "operation": "edit", "select": "1,2,3", "status": "done" }),
    );
    assert!(!is_error(&preview));
    assert_eq!(
        tree_snapshot(&store.issues_dir),
        before,
        "a preview is byte-identical"
    );

    // The refusal path too — a preview that cannot be built must also write nothing.
    let refused = call(
        &config,
        &store,
        "bulk_preview",
        json!({ "operation": "edit", "select": "1" }),
    );
    assert!(is_error(&refused), "a patch with no field set is refused");
    assert_eq!(tree_snapshot(&store.issues_dir), before);

    // The positive control: the same request, confirmed, does change the tree. If this
    // failed, the two assertions above would be passing for the wrong reason.
    let applied = call(
        &config,
        &store,
        "bulk_apply",
        json!({ "operation": "edit", "select": "1", "status": "done", "confirm": true }),
    );
    assert!(!is_error(&applied), "{}", content_text(&applied));
    assert_ne!(
        tree_snapshot(&store.issues_dir),
        before,
        "the control: a confirmed apply does change the tree"
    );
}

#[test]
fn t042_the_tui_and_mcp_read_the_same_plan_value() {
    // The TUI holds `PatchFlags` and calls the same `build`; this case pins that the
    // two surfaces' *inputs* are the same value, which is what makes their outputs
    // comparable. A TUI row and an MCP argument that differ here would produce two
    // different plans and the parity claim would be untestable.
    let (_tmp, config, store) = seed();
    let mcp = call(
        &config,
        &store,
        "bulk_preview",
        json!({ "operation": "edit", "select": "1", "labels": "bug, wip" }),
    );
    let mcp_change = change(&structured(&mcp)["items"][0], "labels").clone();

    let mut modal = tix::ui::bulk::BulkModal::new(tix::ui::bulk::BatchAction::Edit);
    modal.selection.toggle(1).unwrap();
    modal
        .set_row(
            modal
                .row_names()
                .iter()
                .position(|n| *n == "labels")
                .unwrap(),
            "bug, wip".to_string(),
        )
        .unwrap();
    let tui_patch = modal.patch().unwrap();
    assert_eq!(
        tui_patch.labels,
        PatchValue::Set(vec!["bug".to_string(), "wip".to_string()]),
        "the TUI row and the MCP argument produce the same typed list"
    );
    let tui_plan = tix::commands::bulk::build(
        &store,
        tix::commands::bulk::resolve(
            &store,
            &tix::commands::bulk::SelectionRequest::new(
                &["1".to_string()],
                None,
                None,
                SelectionScope::Active,
            )
            .unwrap(),
        )
        .unwrap(),
        tui_patch,
    )
    .unwrap();
    let (from, to) = tui_plan.items[0].changes["labels"].as_from_to();
    assert_eq!(mcp_change["to"], json!(to), "and the same proposed value");
    assert_eq!(mcp_change["from"], json!(from));
    assert_eq!(
        mcp_change["field"],
        json!("labels"),
        "named by the contract's field"
    );
    let _ = config;
}

#[test]
fn t039_a_reassignment_moves_the_file_and_records_one_history_event() {
    // T039: a reassign is the one batch that changes a path, so it is the one that can
    // break C-001 (markdown files stay canonical) if the plan and the apply disagree.
    let (_tmp, config, store) = seed();
    let before = store
        .list()
        .unwrap()
        .into_iter()
        .find(|i| i.number == 1)
        .map(|i| i.filename)
        .unwrap();
    let result = call(
        &config,
        &store,
        "bulk_apply",
        json!({ "operation": "edit", "select": "1", "assignee": "bob", "confirm": true }),
    );
    assert!(!is_error(&result), "{}", content_text(&result));
    let after = store
        .list()
        .unwrap()
        .into_iter()
        .find(|i| i.number == 1)
        .map(|i| i.filename)
        .unwrap();
    assert_ne!(after, before, "the file moved into the new segment");
    assert!(
        after.contains("bob"),
        "into the assignee's segment: {after}"
    );
    assert!(
        !store.issues_dir.join(&before).exists(),
        "and the old path is gone — C-001: one canonical file per issue"
    );
}