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
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
//! WP05 (`triage-inbox-review-flow-01M3C600`) — T028: the `tix triage` surface,
//! and the import-policy flag, through the **real binary**.
//!
//! These are process-level cases: they run the compiled `tix` and read its
//! stdout, stderr and **exit status**. That is the only way to check what the
//! CLI contract is actually about —
//!
//! - the queue views are **read-only**, which is a claim about the tree rather
//!   than about a return value;
//! - a missing reason is refused **before** anything is written;
//! - a partial batch prints every outcome *and* exits non-zero;
//! - `--triage-policy` reaches WP07's router, which is a claim about the
//!   command, its report line and the bytes of the file it wrote.
//!
//! The binary is located through `CARGO_BIN_EXE_tix`/`cargo_bin`, so a test
//! cannot pass against a stale build of `tix` on `PATH`.
//!
//! | Test | Subtask |
//! |---|---|
//! | `triage_cli_list_*`, `triage_cli_status_*`, `triage_cli_read_only_*` | T023 queue tree/list/status |
//! | `triage_cli_each_decision_*`, `triage_cli_missing_*`, `triage_cli_an_issue_*`, `triage_cli_accept_*`, `triage_cli_repeating_*` | T024 single decisions |
//! | `triage_cli_batch_*` | T025/T026 batch preview/confirm/partial |
//! | `triage_cli_duplicate_keeps_*` | T024/T028 duplicate non-merge |
//! | `triage_cli_import_*` | T027 import policy help and routing |
//! | `triage_cli_existing_commands_*` | T028 compatibility |
//!
//! No TTY, no network, and no wall clock in any assertion: an entry's age is
//! derived from a stamp this file writes against a `today` the binary computes,
//! so every ordering claim below is about *relative* ages that hold whatever
//! the date is.

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

use assert_cmd::Command;
use tempfile::TempDir;

// ---------------------------------------------------------------------------
// Fixtures
// ---------------------------------------------------------------------------

/// A board that declares every category, so `[triage]` can name a `canceled`
/// column — the same fixture shape WP01–WP04 use, so a scope resolved here and
/// a section validated there agree about what the board is.
const BOARD: &str = r#"issues_dir = "ISSUES_DIR"

[kanban.default]
columns = ["triage", "todo", "in progress", "in review", "done", "wontfix"]
done_column = "done"
category_map = { triage = "backlog", todo = "unstarted", "in progress" = "active", "in review" = "active", done = "completed", wontfix = "canceled" }
"#;

/// The ordinary inbox: the queue is `triage`, a decline lands in `wontfix`.
const TRIAGE: &str = "\n[triage]\nentry_status = \"triage\"\ndeclined_status = \"wontfix\"\n";

/// The binary under test, as cargo built it for this run.
fn tix() -> Command {
    let mut command = Command::cargo_bin("tix").expect("the tix binary must build");
    command
        .env("NO_COLOR", "1")
        .env("TERM", "dumb")
        // A fixed identity, so a `## History` line and an `assignee:` are the
        // same bytes in every fixture and a before/after snapshot does not
        // differ on who ran it.
        .env("GIT_AUTHOR_NAME", "Test")
        .env("GIT_AUTHOR_EMAIL", "test@example.invalid")
        .env("GIT_COMMITTER_NAME", "Test")
        .env("GIT_COMMITTER_EMAIL", "test@example.invalid");
    command
}

/// A repo with an **absolute** `issues_dir` and a board that declares every
/// category, plus whatever `[triage]` section the caller asks for.
///
/// `section` may be empty: a project with no inbox is a first-class fixture,
/// not an error case, and `tix triage`'s refusal on it is a claim worth making
/// about every subcommand.
fn repo(section: &str) -> (TempDir, PathBuf) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(&dir).unwrap();
    let config = BOARD.replace("ISSUES_DIR", &dir.display().to_string());
    fs::write(
        tmp.path().join("tix.toml"),
        format!("{config}{section}\n[layout]\nmove_on_change = false\n"),
    )
    .unwrap();
    (tmp, dir)
}

/// Write one issue file. `entered_at` is written only when asked for, so a
/// legacy issue (no entry stamp) is one argument away from a stamped one.
fn write_issue(
    dir: &Path,
    file: &str,
    number: u32,
    title: &str,
    status: &str,
    entered_at: Option<&str>,
) {
    let mut text = format!(
        "---\nnumber: {number}\ntitle: \"{title}\"\nstatus: \"{status}\"\nlabels: []\n\
         priority: medium\ncreated: 2026-01-01\nupdated: 2026-01-01\n"
    );
    if let Some(at) = entered_at {
        text.push_str(&format!("entered_at: {at}\nsource: test\n"));
    }
    text.push_str("---\n\nBody text.");
    fs::write(dir.join(file), text).unwrap();
}

/// The three-issue inbox every view test reads: Alpha and Charlie are stamped
/// (Charlie entered long after Alpha), Bravo is a legacy issue with no stamp,
/// and Charlie-outside is in a column the inbox does not include.
///
/// Written rather than created through the CLI so the entry stamps — and hence
/// every age — are data this file controls instead of the wall clock's.
fn inbox_repo() -> (TempDir, PathBuf) {
    let (tmp, dir) = repo(TRIAGE);
    write_issue(
        &dir,
        "2026-01-01-alpha.md",
        1,
        "Alpha waits",
        "triage",
        Some("2020-01-01T00:00:00Z"),
    );
    write_issue(
        &dir,
        "2026-01-01-bravo.md",
        2,
        "Bravo legacy",
        "triage",
        None,
    );
    write_issue(
        &dir,
        "2026-01-01-charlie.md",
        3,
        "Charlie recent",
        "triage",
        Some("2026-09-30T00:00:00Z"),
    );
    write_issue(
        &dir,
        "2026-01-01-delta.md",
        4,
        "Delta outside",
        "in review",
        Some("2020-01-01T00:00:00Z"),
    );
    (tmp, dir)
}

fn run(dir: &Path, args: &[&str]) -> std::process::Output {
    tix()
        .current_dir(dir)
        .args(args)
        .output()
        .expect("the tix binary runs")
}

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

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

/// Every byte under a directory, for the byte-identical no-write comparisons.
fn snapshot(root: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
    let mut out = BTreeMap::new();
    let mut stack = vec![root.to_path_buf()];
    while let Some(cur) = stack.pop() {
        for entry in fs::read_dir(&cur).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                stack.push(path);
            } else {
                out.insert(path.clone(), fs::read(&path).unwrap());
            }
        }
    }
    out
}

/// The one `.md` file in a repo — a fixture that wrote exactly one issue.
fn only_issue(dir: &Path) -> String {
    let mut found: Vec<PathBuf> = Vec::new();
    fn walk(cur: &Path, found: &mut Vec<PathBuf>) {
        for entry in fs::read_dir(cur).unwrap().flatten() {
            let path = entry.path();
            if path.is_dir() {
                walk(&path, found);
            } else if path.extension().is_some_and(|ext| ext == "md") {
                found.push(path);
            }
        }
    }
    walk(dir, &mut found);
    assert_eq!(
        found.len(),
        1,
        "expected exactly one issue, found {found:?}"
    );
    fs::read_to_string(&found[0]).unwrap()
}

/// The `## History` event lines of a file, one per applied decision.
fn history_events(text: &str) -> Vec<&str> {
    // The em-dash separators are what tell a History entry apart from the
    // `- id:` items of a `relationships:` YAML list — those are list items too,
    // and counting them would report two events for a duplicate decision.
    text.lines()
        .filter(|line| line.starts_with("- ") && line.contains(" — "))
        .collect()
}

/// The row whose first token is `num`, from a `triage list` table.
fn row<'a>(stdout: &'a str, num: &str) -> &'a str {
    stdout
        .lines()
        .find(|line| line.split_whitespace().next() == Some(num))
        .unwrap_or_else(|| panic!("no row starting with `{num}` in:\n{stdout}"))
}

// ---------------------------------------------------------------------------
// T023 — the tree, list and status
// ---------------------------------------------------------------------------

#[test]
fn triage_cli_list_prints_one_row_per_entry_and_its_age() {
    let (tmp, dir) = inbox_repo();
    let stdout = ok(tmp.path(), &["triage", "list"]);

    assert!(
        stdout.contains("inbox: 3 entries (3 awaiting, 3 deferred)"),
        "the header counts the entries, and only the inbox:\n{stdout}"
    );
    assert!(stdout.contains("NUM  AGE      TITLE"), "header:\n{stdout}");

    let alpha = row(&stdout, "1");
    assert!(alpha.contains("d "), "a stamped age is days: {alpha}");
    assert!(alpha.contains("Alpha waits"), "{alpha}");

    let bravo = row(&stdout, "2");
    assert!(
        bravo.contains("unknown"),
        "a missing stamp is `unknown`, never 0 and never `created`:\n{bravo}"
    );

    assert!(
        !stdout.contains("Delta outside"),
        "`in review` is not an inbox column, so it is not a row:\n{stdout}"
    );
    let _ = dir;
}

#[test]
fn triage_cli_list_count_prints_the_summary_and_no_rows() {
    let (tmp, _dir) = inbox_repo();
    let stdout = ok(tmp.path(), &["triage", "list", "--count"]);

    assert!(
        stdout.contains("inbox: 3 entries (3 awaiting, 3 deferred)"),
        "{stdout}"
    );
    assert!(!stdout.contains("Alpha waits"), "no rows:\n{stdout}");
    assert!(!stdout.contains("NUM"), "and no table header:\n{stdout}");
}

#[test]
fn triage_cli_list_age_orders_oldest_first_and_leaves_unknown_last() {
    let (tmp, _dir) = inbox_repo();

    // Store order: the filename sort, which is what `tix list` shows.
    let natural = ok(tmp.path(), &["triage", "list"]);
    assert!(
        natural.find("Alpha waits").unwrap() < natural.find("Bravo legacy").unwrap(),
        "snapshot order, not an age order:\n{natural}"
    );

    let by_age = ok(tmp.path(), &["triage", "list", "--age"]);
    let alpha = by_age.find("Alpha waits").expect("alpha is listed");
    let charlie = by_age.find("Charlie recent").expect("charlie is listed");
    let bravo = by_age.find("Bravo legacy").expect("bravo is listed");
    assert!(
        alpha < charlie && charlie < bravo,
        "oldest stamped first, newest stamped second, the unstamped issue last \
         rather than sorted as if it had just arrived:\n{by_age}"
    );
}

#[test]
fn triage_cli_status_names_every_decision_count_and_the_histogram() {
    // This fixture puts the declined column *inside* the inbox (`deferred_status
    // = declined_status = "wontfix"`), which is the only configuration in which
    // `declined` is ever non-zero: the figure is the staleness count — a member
    // of the `canceled` category that is still in an inbox column — and on the
    // ordinary board a decline leaves. Reporting `declined: 0` there is the
    // truth; proving the field is *wired* needs this one instead.
    let (tmp, dir) = repo(&format!("{TRIAGE}deferred_status = \"wontfix\"\n"));
    write_issue(&dir, "2026-01-01-one.md", 1, "One", "triage", None);
    write_issue(&dir, "2026-01-01-two.md", 2, "Two", "triage", None);
    write_issue(&dir, "2026-01-01-three.md", 3, "Three", "triage", None);
    write_issue(&dir, "2026-01-01-four.md", 4, "Four", "in review", None);

    // A decline (into `wontfix`, still an inbox column) and a duplicate (which
    // records an edge on #2), so two of the decision counts are real numbers.
    let out = run(
        tmp.path(),
        &["triage", "decline", "1", "--reason", "not actionable"],
    );
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let out = run(
        tmp.path(),
        &[
            "triage",
            "duplicate",
            "2",
            "--of",
            "3",
            "--reason",
            "same bug",
        ],
    );
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );

    let stdout = ok(tmp.path(), &["triage", "status"]);
    for expected in [
        // #4 is `in review`, so it is not counted anywhere.
        "inbox: 3 entries (2 awaiting, 1 deferred)",
        "  awaiting: 2",
        "  deferred: 1",
        "  accepted: 0",
        "  declined: 1",
        "  duplicated: 1",
        // Every entry here was hand-written without a stamp, so the fallback
        // stays `unknown` rather than borrowing `created`.
        "  unknown age: 3",
        "  age: today 0, 1-2 0, 3-6 0, 7-13 0, 14-29 0, 30+ 0, unknown 3",
    ] {
        assert!(
            stdout.contains(expected),
            "missing `{expected}` in:\n{stdout}"
        );
    }
}

#[test]
fn triage_cli_read_only_views_write_nothing() {
    let (tmp, _dir) = inbox_repo();
    let before = snapshot(tmp.path());

    for args in [
        vec!["triage", "list"],
        vec!["triage", "list", "--age"],
        vec!["triage", "list", "--count"],
        vec!["triage", "status"],
    ] {
        let out = run(tmp.path(), &args);
        assert!(
            out.status.success(),
            "tix {args:?} failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    assert_eq!(
        before,
        snapshot(tmp.path()),
        "a queue view is read-only: no file, no History, no timestamp changed"
    );
}

#[test]
fn triage_cli_without_a_triage_section_every_view_and_decision_refuses_the_same_way() {
    // A project with no inbox is not an error case, it is a different project.
    // Every subcommand answers the one question it all shares with the same
    // sentence, so a user who typed `status` instead of `list` is not told
    // about a defect they would have hit anyway.
    let (tmp, _dir) = repo("");
    let args: [&[&str]; 6] = [
        &["triage", "list"],
        &["triage", "status"],
        &["triage", "accept", "1"],
        &["triage", "decline", "1", "--reason", "x"],
        &["triage", "duplicate", "1", "--of", "2", "--reason", "x"],
        &["triage", "defer", "1", "--reason", "x"],
    ];
    for args in args {
        let (stdout, stderr) = code(tmp.path(), args, 1);
        assert!(
            stderr.contains("`tix triage` needs a `[triage]` section in tix.toml"),
            "tix {args:?} must name the missing section, not some later failure: {stderr}"
        );
        assert!(
            stdout.is_empty(),
            "and it wrote nothing to stdout: {stdout}"
        );
    }
}

// ---------------------------------------------------------------------------
// T024 — the four decisions
// ---------------------------------------------------------------------------

/// A repo with one issue per decision, all of them in the inbox.
fn decision_repo() -> (TempDir, PathBuf) {
    let (tmp, dir) = repo(TRIAGE);
    for (number, slug) in [(1, "alpha"), (2, "bravo"), (3, "charlie"), (4, "delta")] {
        write_issue(
            &dir,
            &format!("2026-01-01-{slug}.md"),
            number,
            &format!("Issue {slug}"),
            "triage",
            None,
        );
    }
    (tmp, dir)
}

#[test]
fn triage_cli_each_decision_applies_and_records_exactly_one_event() {
    let (tmp, dir) = decision_repo();

    // accept — moves out of the inbox and names where it went.
    let stdout = ok(
        tmp.path(),
        &[
            "triage",
            "accept",
            "1",
            "--to",
            "todo",
            "--reason",
            "shipped soon",
        ],
    );
    assert!(stdout.contains("#1 Issue alpha -> applied"), "{stdout}");
    assert!(stdout.contains("history: triage_accepted"), "{stdout}");
    let text = fs::read_to_string(dir.join("2026-01-01-alpha.md")).unwrap();
    assert!(text.contains("status: todo"), "accept moved it:\n{text}");
    assert_eq!(history_events(&text).len(), 1, "exactly one event:\n{text}");

    // decline — a distinct canceled column, never a delete.
    let stdout = ok(
        tmp.path(),
        &["triage", "decline", "2", "--reason", "not actionable"],
    );
    assert!(stdout.contains("history: triage_declined"), "{stdout}");
    let text = fs::read_to_string(dir.join("2026-01-01-bravo.md")).unwrap();
    assert!(text.contains("status: wontfix"), "decline:\n{text}");
    assert!(
        text.contains("reason: not actionable"),
        "the reason is in History:\n{text}"
    );
    assert_eq!(history_events(&text).len(), 1, "{text}");
    assert!(dir.join("2026-01-01-bravo.md").is_file(), "never deleted");

    // defer — stays put, restarts the wait, records its source.
    let stdout = ok(
        tmp.path(),
        &["triage", "defer", "3", "--reason", "waiting on reporter"],
    );
    assert!(stdout.contains("history: triage_deferred"), "{stdout}");
    let text = fs::read_to_string(dir.join("2026-01-01-charlie.md")).unwrap();
    assert!(
        text.contains("status: triage"),
        "defer does not move it:\n{text}"
    );
    assert!(text.contains("source: defer"), "and it re-enters:\n{text}");
    assert_eq!(history_events(&text).len(), 1, "{text}");

    // duplicate — a typed relation, and no file operation at all.
    let target_before = fs::read(dir.join("2026-01-01-alpha.md")).unwrap();
    let source_before = fs::read(dir.join("2026-01-01-delta.md")).unwrap();
    let stdout = ok(
        tmp.path(),
        &[
            "triage",
            "duplicate",
            "4",
            "--of",
            "1",
            "--reason",
            "same bug",
        ],
    );
    assert!(stdout.contains("history: triage_duplicated"), "{stdout}");
    let text = fs::read_to_string(dir.join("2026-01-01-delta.md")).unwrap();
    assert!(text.contains("kind: duplicates"), "the edge:\n{text}");
    assert!(
        text.contains("status: triage"),
        "duplicate moves nothing:\n{text}"
    );
    assert_eq!(history_events(&text).len(), 1, "{text}");
    assert_ne!(
        source_before,
        fs::read(dir.join("2026-01-01-delta.md")).unwrap(),
        "the source gained the edge and the event"
    );
    assert_eq!(
        target_before,
        fs::read(dir.join("2026-01-01-alpha.md")).unwrap(),
        "and the duplicate's *target* was only read — #190 owns merging, so a \
         duplicate decision writes exactly one file"
    );
}

#[test]
fn triage_cli_missing_reason_is_refused_before_anything_is_written() {
    let (tmp, dir) = decision_repo();

    for args in [
        vec!["triage", "decline", "1"],
        vec!["triage", "defer", "2"],
        vec!["triage", "duplicate", "3", "--of", "4"],
    ] {
        let before = snapshot(&dir);
        let (stdout, _stderr) = code(tmp.path(), &args, 1);
        assert!(
            stdout.contains("refused: missing_reason") && stdout.contains("requires a reason"),
            "tix {args:?} must name the contract's kind, in the per-item shape the \
             batch uses (tix #1488): {stdout}"
        );
        assert_eq!(
            before,
            snapshot(&dir),
            "tix {args:?} refused before any write"
        );
    }
}

#[test]
fn triage_cli_missing_actor_is_refused_and_nothing_is_written() {
    // An audit entry with no actor is worse than no entry, so `--actor ""` is
    // refused rather than falling back to a default the user did not choose.
    let (tmp, dir) = decision_repo();
    let before = snapshot(&dir);
    let (stdout, _stderr) = code(
        tmp.path(),
        &["triage", "decline", "1", "--reason", "x", "--actor", ""],
        1,
    );
    assert!(
        stdout.contains("refused: missing_actor") && stdout.contains("never recorded anonymously"),
        "{stdout}"
    );
    assert_eq!(before, snapshot(&dir), "refused before any write");
}

#[test]
fn triage_cli_an_issue_already_decided_is_refused_by_its_own_kind() {
    let (tmp, dir) = decision_repo();

    // Never queued: `not_in_triage`, because the issue is simply elsewhere.
    ok(tmp.path(), &["move", "1", "in progress"]);
    let before = snapshot(&dir);
    let (stdout, _stderr) = code(tmp.path(), &["triage", "decline", "1", "--reason", "x"], 1);
    assert!(
        stdout.contains("refused: not_in_triage"),
        "a never-queued issue is `not_in_triage`, not `already_decided`: {stdout}"
    );
    assert_eq!(before, snapshot(&dir));

    // Used its review: `already_decided`, and the answer is a normal command.
    let (tmp, dir) = decision_repo();
    ok(
        tmp.path(),
        &["triage", "decline", "1", "--reason", "not actionable"],
    );
    let before = snapshot(&dir);
    let (stdout, _stderr) = code(
        tmp.path(),
        &["triage", "defer", "1", "--reason", "one more look"],
        1,
    );
    assert!(
        stdout.contains("refused: already_decided") && stdout.contains("normal status command"),
        "{stdout}"
    );
    assert_eq!(before, snapshot(&dir));
}

#[test]
fn triage_cli_accept_target_is_validated_by_the_transition_policy() {
    let (tmp, dir) = decision_repo();

    // A column the board does not have is #183's refusal, in its vocabulary —
    // no triage-specific status rule exists (C-002).
    let before = snapshot(&dir);
    let (stdout, _stderr) = code(tmp.path(), &["triage", "accept", "1", "--to", "nope"], 1);
    assert!(
        stdout.contains("refused: unknown_column"),
        "the single-decision refusal reports the batch's per-item shape (tix #1488): {stdout}"
    );
    assert!(
        stdout.contains("is not a column on board `default`"),
        "and the board service names the real columns: {stdout}"
    );
    assert_eq!(before, snapshot(&dir), "nothing moved");

    // The legal target the flag promises.
    let stdout = ok(tmp.path(), &["triage", "accept", "1", "--to", "todo"]);
    assert!(stdout.contains("#1 Issue alpha -> applied"), "{stdout}");
    let text = fs::read_to_string(dir.join("2026-01-01-alpha.md")).unwrap();
    assert!(text.contains("status: todo"), "{text}");
}

#[test]
fn triage_cli_repeating_a_decision_is_a_noop_that_appends_nothing() {
    let (tmp, dir) = decision_repo();
    ok(
        tmp.path(),
        &["triage", "defer", "1", "--reason", "waiting on reporter"],
    );
    let after_first = snapshot(&dir);

    let stdout = ok(
        tmp.path(),
        &["triage", "defer", "1", "--reason", "waiting on reporter"],
    );
    assert!(
        stdout.contains("already in that state"),
        "an identical repeat is a no-op, not a second event:\n{stdout}"
    );
    assert!(
        !stdout.contains("history:"),
        "a no-op appended nothing, so naming an event would be a lie:\n{stdout}"
    );
    assert_eq!(
        after_first,
        snapshot(&dir),
        "the repeat wrote not one byte (NFR-002's other half)"
    );
}

// ---------------------------------------------------------------------------
// T025/T026 — batch preview, confirmation and partial outcomes
// ---------------------------------------------------------------------------

/// Five issues: four in the inbox, one outside (`5`).
fn batch_repo() -> (TempDir, PathBuf) {
    let (tmp, dir) = repo(TRIAGE);
    for number in 1..=5 {
        write_issue(
            &dir,
            &format!("2026-01-01-issue{number}.md"),
            number,
            &format!("Issue{number}"),
            if number == 5 { "in review" } else { "triage" },
            None,
        );
    }
    (tmp, dir)
}

#[test]
fn triage_cli_batch_previews_by_default_and_writes_nothing() {
    let (tmp, dir) = batch_repo();
    let before = snapshot(&dir);

    let stdout = ok(
        tmp.path(),
        &[
            "triage",
            "batch",
            "--select",
            "1,2",
            "--decision",
            "decline",
            "--reason",
            "stale",
        ],
    );

    assert!(
        stdout.contains("selection: 2 issues (selector, active scope)"),
        "{stdout}"
    );
    assert!(stdout.contains("decision: decline"), "{stdout}");
    assert!(
        stdout.contains("2 of 2 would change"),
        "a preview speaks in the conditional:\n{stdout}"
    );
    assert!(
        !stdout.contains("-> applied"),
        "and never claims it applied anything:\n{stdout}"
    );
    assert_eq!(
        before,
        snapshot(&dir),
        "a preview is read-only by construction, not by promise"
    );
}

#[test]
fn triage_cli_batch_apply_changes_every_selected_issue() {
    let (tmp, dir) = batch_repo();
    let before = snapshot(&dir);

    let stdout = ok(
        tmp.path(),
        &[
            "triage",
            "batch",
            "--select",
            "1,2,3,4",
            "--decision",
            "decline",
            "--reason",
            "stale",
            "--apply",
        ],
    );

    // The positive control: without it, the snapshot assertions above could pass
    // because `--apply` wrote nothing at all.
    assert_ne!(before, snapshot(&dir), "--apply must actually write");
    assert!(
        stdout.contains("4 of 4 applied; 0 already in that state; 0 refused"),
        "{stdout}"
    );
    for number in 1..=4 {
        let text = fs::read_to_string(dir.join(format!("2026-01-01-issue{number}.md"))).unwrap();
        assert!(text.contains("status: wontfix"), "issue {number}:\n{text}");
        assert!(
            text.contains("triage_declined"),
            "one event per applied decision (NFR-002):\n{text}"
        );
        assert_eq!(history_events(&text).len(), 1, "{text}");
    }
    // T026: the report names the state each applied item landed in — once per
    // item, not once in a header the reader has to map back themselves.
    assert_eq!(
        stdout.matches("status: \"triage\" -> wontfix").count(),
        4,
        "and the report says where each of them went:\n{stdout}"
    );
}

#[test]
fn triage_cli_batch_partial_apply_keeps_the_applied_items_and_exits_non_zero() {
    let (tmp, dir) = batch_repo();
    let refused_before = fs::read(dir.join("2026-01-01-issue5.md")).unwrap();

    let (stdout, _stderr) = code(
        tmp.path(),
        &[
            "triage",
            "batch",
            "--select",
            "1,5",
            "--decision",
            "decline",
            "--reason",
            "stale",
            "--apply",
        ],
        1,
    );

    assert!(
        stdout.contains("#1 Issue1 -> applied"),
        "the item that could be applied still was:\n{stdout}"
    );
    assert!(
        stdout.contains("#5 Issue5 -> refused: not_in_triage"),
        "the refused item is named, with its kind:\n{stdout}"
    );
    assert!(
        stdout.contains("1 of 2 applied; 0 already in that state; 1 refused"),
        "every count, including the zeros:\n{stdout}"
    );

    // No rollback, and no implied rollback: the applied item stuck, and the
    // refused one is byte-for-byte what it was before the command ran.
    let applied = fs::read_to_string(dir.join("2026-01-01-issue1.md")).unwrap();
    assert!(applied.contains("status: wontfix"), "{applied}");
    let refused = fs::read_to_string(dir.join("2026-01-01-issue5.md")).unwrap();
    assert_eq!(
        refused_before,
        fs::read(dir.join("2026-01-01-issue5.md")).unwrap(),
        "a refused item is not touched, let alone moved:\n{refused}"
    );
    assert!(
        !refused.contains("triage_declined"),
        "a refused item appends no event:\n{refused}"
    );
}

#[test]
fn triage_cli_batch_gives_every_selected_issue_exactly_one_outcome() {
    let (tmp, _dir) = batch_repo();
    // One that will apply, one already declined **with this very reason** (a
    // genuine no-op, not an `already_decided` refusal), one moved out of the
    // inbox (a refusal): three selections, three outcomes, in selection order.
    ok(tmp.path(), &["triage", "decline", "2", "--reason", "stale"]);
    ok(tmp.path(), &["move", "3", "todo"]);

    let (stdout, _stderr) = code(
        tmp.path(),
        &[
            "triage",
            "batch",
            "--select",
            "1,2,3",
            "--decision",
            "decline",
            "--reason",
            "stale",
            "--apply",
        ],
        1,
    );

    let outcomes: Vec<&str> = stdout
        .lines()
        .filter(|line| line.starts_with('#'))
        .collect();
    assert_eq!(
        outcomes.len(),
        3,
        "every selected issue receives exactly one outcome (C-005):\n{stdout}"
    );
    assert!(outcomes[0].contains("#1 Issue1 -> applied"), "{stdout}");
    assert!(
        outcomes[1].contains("#2 Issue2 -> already in that state"),
        "{stdout}"
    );
    assert!(outcomes[2].contains("#3 Issue3 -> refused"), "{stdout}");
    assert!(
        stdout.contains("1 of 3 applied; 1 already in that state; 1 refused"),
        "{stdout}"
    );
}

#[test]
fn triage_cli_batch_reapplying_is_a_noop_and_still_exits_zero() {
    let (tmp, dir) = batch_repo();
    let args = [
        "triage",
        "batch",
        "--select",
        "1,2",
        "--decision",
        "decline",
        "--reason",
        "stale",
        "--apply",
    ];
    ok(tmp.path(), &args);
    let after_first = snapshot(&dir);

    let (stdout, stderr) = code(tmp.path(), &args, 0);
    assert!(
        stdout.contains("0 of 2 applied; 2 already in that state; 0 refused"),
        "{stdout}"
    );
    assert!(stderr.is_empty(), "{stderr}");
    assert_eq!(
        after_first,
        snapshot(&dir),
        "the re-run appended no second event (spec §4 invariant)"
    );
}

#[test]
fn triage_cli_batch_needs_exactly_one_selection_grammar() {
    let (tmp, _dir) = batch_repo();

    // Two grammars: both named, and the reason given, so the fix is obvious.
    let (_, stderr) = code(
        tmp.path(),
        &[
            "triage",
            "batch",
            "--select",
            "1",
            "--filter",
            "status:triage",
            "--decision",
            "decline",
            "--reason",
            "x",
        ],
        1,
    );
    assert!(
        stderr.contains("--select") && stderr.contains("--filter"),
        "{stderr}"
    );
    assert!(stderr.contains("will not guess"), "{stderr}");

    // Zero grammars.
    let (_, stderr) = code(
        tmp.path(),
        &["triage", "batch", "--decision", "decline", "--reason", "x"],
        1,
    );
    assert!(
        stderr.contains("--select") && stderr.contains("--filter"),
        "{stderr}"
    );

    // One flag that named nothing after all.
    let (_, stderr) = code(
        tmp.path(),
        &[
            "triage",
            "batch",
            "--select",
            ",",
            "--decision",
            "decline",
            "--reason",
            "x",
        ],
        1,
    );
    assert!(stderr.contains("names no issue"), "{stderr}");
}

#[test]
fn triage_cli_batch_refuses_a_target_flag_the_decision_cannot_use() {
    let (tmp, _dir) = batch_repo();

    // `--to` on a decline: silently ignoring it would let a user believe they
    // had chosen where the issue lands.
    let (_, stderr) = code(
        tmp.path(),
        &[
            "triage",
            "batch",
            "--select",
            "1",
            "--decision",
            "decline",
            "--to",
            "todo",
            "--reason",
            "x",
        ],
        1,
    );
    assert!(
        stderr.contains("`--to` names an accept target") && stderr.contains("decline decision"),
        "{stderr}"
    );

    // `--of` on a non-duplicate: the mirror of the rule above, refused by the
    // plan builder WP04 already owns.
    let (_, stderr) = code(
        tmp.path(),
        &[
            "triage",
            "batch",
            "--select",
            "1",
            "--decision",
            "defer",
            "--of",
            "2",
            "--reason",
            "x",
        ],
        1,
    );
    assert!(
        stderr.contains("a duplicate target was named") && stderr.contains("a defer"),
        "and the shared sentence names the argument by meaning, not by a CLI flag \
         the MCP surface does not have (tix #1488): {stderr}"
    );

    // An unknown decision name is refused rather than coerced.
    let (_, stderr) = code(
        tmp.path(),
        &[
            "triage",
            "batch",
            "--select",
            "1",
            "--decision",
            "declinee",
            "--reason",
            "x",
        ],
        1,
    );
    assert!(
        stderr.contains("unknown triage decision `declinee`"),
        "{stderr}"
    );
}

#[test]
fn triage_cli_batch_duplicate_without_a_target_is_a_per_item_refusal() {
    // The decision is structurally fine; only the item is refused, and the
    // preview must show that *before* anything is written.
    let (tmp, dir) = batch_repo();
    let before = snapshot(&dir);

    let (stdout, _stderr) = code(
        tmp.path(),
        &[
            "triage",
            "batch",
            "--select",
            "1,2",
            "--decision",
            "duplicate",
            "--reason",
            "x",
        ],
        1,
    );
    assert!(
        stdout.contains("refused [decision]: invalid_duplicate_target"),
        "{stdout}"
    );
    assert!(
        stdout.contains("0 of 2 would change; 2 refused"),
        "{stdout}"
    );
    assert_eq!(before, snapshot(&dir));
}

// ---------------------------------------------------------------------------
// The duplicate decision must never merge (C-006)
// ---------------------------------------------------------------------------

#[test]
fn triage_cli_duplicate_keeps_both_files_and_creates_only_a_relation() {
    let (tmp, dir) = repo(TRIAGE);
    write_issue(&dir, "2026-01-01-alpha.md", 1, "Alpha", "triage", None);
    write_issue(&dir, "2026-01-01-bravo.md", 2, "Bravo", "triage", None);
    let target_before = fs::read(dir.join("2026-01-01-bravo.md")).unwrap();

    let stdout = ok(
        tmp.path(),
        &[
            "triage",
            "duplicate",
            "1",
            "--of",
            "2",
            "--reason",
            "same underlying bug",
        ],
    );
    assert!(stdout.contains("#1 Alpha -> applied"), "{stdout}");
    assert!(stdout.contains("history: triage_duplicated"), "{stdout}");

    // Both files still exist, and the *target* is byte-identical: a duplicate
    // decision reads the target and writes only its own file.
    assert!(
        dir.join("2026-01-01-bravo.md").is_file(),
        "the source file is never absorbed"
    );
    assert!(
        dir.join("2026-01-01-alpha.md").is_file(),
        "and the duplicate is never deleted"
    );
    assert_eq!(
        target_before,
        fs::read(dir.join("2026-01-01-bravo.md")).unwrap(),
        "the target file is untouched — no merge, no move, no re-serialisation"
    );

    let text = fs::read_to_string(dir.join("2026-01-01-alpha.md")).unwrap();
    assert!(text.contains("kind: duplicates"), "one typed edge:\n{text}");
    assert!(text.contains("from: 1"), "{text}");
    assert!(text.contains("to: 2"), "{text}");
    assert_eq!(
        history_events(&text).len(),
        1,
        "one event, one edge, and no second file write:\n{text}"
    );
    assert_eq!(
        fs::read_to_string(dir.join("2026-01-01-bravo.md"))
            .unwrap()
            .matches("## History")
            .count(),
        0,
        "the target gained no History of its own"
    );
}

// ---------------------------------------------------------------------------
// T027 — the import triage policy
// ---------------------------------------------------------------------------

/// The board WP07's routing tests use: `todo` comes first, so landing in
/// `triage` is the router's doing and not a coincidence of column order.
const ROUTING_BOARD: &str = "columns = [\"todo\", \"triage\", \"in progress\", \"done\", \"wontfix\"]\ndone_column = \"done\"\ncategory_map = { triage = \"backlog\", todo = \"unstarted\", \"in progress\" = \"active\", done = \"completed\", wontfix = \"canceled\" }\n";

const GITLAB_LIST: &str = r#"[{"iid":10,"title":"Remote bug","description":"from remote","labels":[{"name":"bug"}],"state":"opened","updated_at":"2026-05-12T08:00:00Z","assignees":[]}]"#;

#[test]
fn triage_cli_import_help_exposes_the_triage_policy_flag() {
    let (tmp, _dir) = repo(TRIAGE);
    let stdout = ok(tmp.path(), &["import", "--help"]);

    assert!(stdout.contains("--triage-policy"), "{stdout}");
    assert!(
        stdout.contains("entry|remote"),
        "the two legal values are spelled: {stdout}"
    );
    assert!(
        stdout.contains("refuses a project with\n          no `[triage]` section")
            || stdout.contains("`[triage]` section"),
        "the help says what `entry` does on a project without an inbox:\n{stdout}"
    );
    // T027's other half: the flag is *for* WP07's router, so the help names it.
    assert!(
        stdout.contains("reports the mapping") || stdout.contains("report names the mapping"),
        "{stdout}"
    );
    // The existing flag is untouched.
    assert!(stdout.contains("--target"), "{stdout}");
}

#[test]
fn triage_cli_import_refuses_an_unknown_triage_policy_before_touching_the_remote() {
    // No `[export.gitlab]` in this fixture: if the policy were parsed *after*
    // the adapter were built, the failure would be about the missing section
    // instead. Reaching the policy's own message is therefore also a check that
    // the flag is validated on the command line, where a typo is cheap to fix.
    let (tmp, _dir) = repo(TRIAGE);
    let (stdout, stderr) = code(
        tmp.path(),
        &["import", "--target", "gitlab", "--triage-policy", "nope"],
        1,
    );
    assert!(
        stderr.contains("unknown --triage-policy 'nope' — use entry or remote"),
        "{stderr}"
    );
    assert!(stdout.is_empty(), "{stdout}");
}

/// Run `tix import` against the fake `glab` on `PATH`.
fn import_with_policy(dir: &Path, policy: Option<&str>) -> (String, String, bool) {
    let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".into());
    let bin_dir = PathBuf::from(manifest).join("tests").join("bin");
    let record = dir.join("records.txt");

    let mut command = tix();
    let mut args = vec![
        "import".to_string(),
        "--target".to_string(),
        "gitlab".to_string(),
    ];
    if let Some(policy) = policy {
        args.push("--triage-policy".to_string());
        args.push(policy.to_string());
    }
    let out = command
        .current_dir(dir)
        .args(&args)
        .env(
            "PATH",
            format!(
                "{}:{}",
                bin_dir.display(),
                std::env::var("PATH").unwrap_or_default()
            ),
        )
        .env("TIX_FAKE_LIST", GITLAB_LIST)
        .env("TIX_FAKE_RECORD", &record)
        .env_remove("GITLAB_TOKEN")
        .env_remove("LINEAR_TOKEN")
        .output()
        .expect("`tix import` must run");

    (
        String::from_utf8_lossy(&out.stdout).into_owned(),
        String::from_utf8_lossy(&out.stderr).into_owned(),
        out.status.success(),
    )
}

/// A routing fixture: an inbox, and a GitLab section the fake `glab` satisfies.
fn import_repo() -> (TempDir, PathBuf) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("docs").join("issues");
    fs::create_dir_all(&dir).unwrap();
    fs::write(
        tmp.path().join("tix.toml"),
        format!(
            "issues_dir = \"docs/issues\"\n\n[kanban.default]\n{ROUTING_BOARD}\n\
             [export.gitlab]\nproject = \"acme/tix\"\ntoken = \"gl-file-token\"\n{TRIAGE}"
        ),
    )
    .unwrap();
    (tmp, dir)
}

#[test]
fn triage_cli_import_policy_entry_is_routed_through_wp07() {
    let (tmp, issues_dir) = import_repo();
    let (stdout, stderr, succeeded) = import_with_policy(tmp.path(), Some("entry"));
    assert!(succeeded, "stderr: {stderr}\nstdout: {stdout}");

    assert!(
        stdout.contains("(triage entry: remote `opened` requested `todo`, landed `triage`)"),
        "the report names the mapping the flag asked for: {stdout}"
    );
    let text = only_issue(&issues_dir);
    assert!(text.contains("status: triage"), "into the inbox:\n{text}");
    assert!(
        text.contains("source: import") && text.contains("entered_at:"),
        "entry metadata travelled with it:\n{text}"
    );
}

#[test]
fn triage_cli_import_policy_remote_opts_out_and_says_so() {
    let (tmp, issues_dir) = import_repo();
    let (stdout, stderr, succeeded) = import_with_policy(tmp.path(), Some("remote"));
    assert!(succeeded, "stderr: {stderr}\nstdout: {stdout}");

    assert!(
        stdout.contains("(import policy remote:"),
        "an explicit opt-out is reported too, never silent: {stdout}"
    );
    let text = only_issue(&issues_dir);
    assert!(
        text.contains("status: todo"),
        "the column the remote mapping named:\n{text}"
    );
    assert!(
        !text.contains("source: import"),
        "nothing entered triage, so no entry stamp claims it did:\n{text}"
    );
}

// ---------------------------------------------------------------------------
// T028 — the existing commands keep their meanings
// ---------------------------------------------------------------------------

#[test]
fn triage_cli_existing_commands_keep_their_meanings() {
    let (tmp, _dir) = inbox_repo();

    // `tix list` still shows the whole board, inbox and outsider together.
    // `--all`: the default listing is scoped to your issues in the board's entry
    // column (#1711); the scope criterion below is what selects the inbox.
    let stdout = ok(tmp.path(), &["list", "--all"]);
    assert!(stdout.contains("Alpha waits"), "{stdout}");
    assert!(stdout.contains("Delta outside"), "{stdout}");

    // The `scope:` criterion WP02 added still selects the inbox — a new
    // namespace must not have taken it over.
    let stdout = ok(tmp.path(), &["list", "--filter", "scope:triage"]);
    assert!(stdout.contains("Alpha waits"), "{stdout}");
    assert!(!stdout.contains("Delta outside"), "{stdout}");

    // `tix status` is still the board summary, with its own header.
    let stdout = ok(tmp.path(), &["status"]);
    assert!(
        stdout.contains("COLUMN") && stdout.contains("COUNT"),
        "{stdout}"
    );
    assert!(stdout.contains("Total"), "{stdout}");
    assert!(
        !stdout.contains("inbox:"),
        "that is `triage status`: {stdout}"
    );

    // A bad `--target` reports what an older `tix` reported: no triage
    // diagnostic has taken over the import command's own validation.
    let (stdout, stderr) = code(tmp.path(), &["import", "--target", "foobar"], 1);
    assert!(
        stderr.contains("unknown --target 'foobar' — use gitlab or linear"),
        "{stderr}"
    );
    assert!(!stderr.contains("triage-policy"), "{stderr}");
    assert!(stdout.is_empty(), "{stdout}");
}

#[test]
fn triage_cli_batch_accept_honours_the_named_target() {
    // Found from WP08's cross-surface matrix, not from this suite: the batch path
    // checked `--to` for the *non-accept* refusal and then never assigned it, so
    // `--to "in progress"` landed the issue in the configured `accepted_status` and
    // `--to ghost` wrote that same configured target instead of refusing the column
    // the user named. The single-decision command honoured the flag, so the two CLI
    // spellings of one decision disagreed with each other as well as with MCP.
    // The ordinary inbox plus a configured `accepted_status`, so the blank-`--to`
    // rule ("no explicit target, so the configured one applies") has one to apply.
    let (tmp, dir) = repo(
        "\n[triage]\nentry_status = \"triage\"\ndeclined_status = \"wontfix\"\naccepted_status = \"todo\"\n",
    );
    for (number, slug) in [(1, "alpha"), (2, "bravo"), (3, "charlie")] {
        write_issue(
            &dir,
            &format!("2026-01-01-{slug}.md"),
            number,
            &format!("Issue {slug}"),
            "triage",
            None,
        );
    }

    let stdout = ok(
        tmp.path(),
        &[
            "triage",
            "batch",
            "--select",
            "1",
            "--decision",
            "accept",
            "--to",
            "in progress",
            "--reason",
            "confirmed",
            "--apply",
        ],
    );
    assert!(
        stdout.contains("1 of 1 applied"),
        "the batch applied: {stdout}"
    );
    assert!(
        stdout.contains("decision: accept -> in progress"),
        "and reports the column the flag named, not the configured one: {stdout}"
    );
    assert!(
        fs::read_to_string(dir.join("2026-01-01-alpha.md"))
            .unwrap()
            .contains("status: in progress"),
        "the file landed where the flag said"
    );

    // A column the board does not have is #183's refusal, per item — not a silent
    // write to the configured target.
    let before = snapshot(&dir);
    let (stdout, stderr) = code(
        tmp.path(),
        &[
            "triage",
            "batch",
            "--select",
            "2",
            "--decision",
            "accept",
            "--to",
            "ghost",
            "--reason",
            "confirmed",
            "--apply",
        ],
        1,
    );
    assert!(
        stderr.is_empty(),
        "a refusal is a report, not an error: {stderr}"
    );
    assert!(
        stdout.contains("unknown_column"),
        "the per-item refusal names the service's kind: {stdout}"
    );
    assert_eq!(before, snapshot(&dir), "and nothing was written");

    // A blank `--to` names no column, so the configured `accepted_status` applies —
    // the rule the blank filter documents, now reachable because the flag is assigned.
    let stdout = ok(
        tmp.path(),
        &[
            "triage",
            "batch",
            "--select",
            "3",
            "--decision",
            "accept",
            "--to",
            "",
            "--reason",
            "confirmed",
            "--apply",
        ],
    );
    assert!(
        stdout.contains("decision: accept -> todo"),
        "a blank target means the configured one: {stdout}"
    );
    assert!(
        fs::read_to_string(dir.join("2026-01-01-charlie.md"))
            .unwrap()
            .contains("status: todo"),
        "and it landed there"
    );
}

#[test]
fn triage_cli_a_new_issue_created_into_the_inbox_records_an_entry_stamp() {
    // Found while verifying the guide's claim that "an issue entering the inbox records
    // an entry stamp": `tix create --status triage` entered the queue and recorded
    // nothing, so the most common way for work to reach the inbox was the one way to
    // end up with an unknown age. The data model names the origin (`new`), and the
    // stamp is what the age column has to have.
    let (tmp, dir) = repo(TRIAGE);

    let stdout = ok(
        tmp.path(),
        &["create", "--title", "Fresh bug", "--status", "triage"],
    );
    assert!(
        stdout.contains("fresh-bug"),
        "the create reports the file it wrote: {stdout}"
    );
    let text = snapshot(&dir)
        .into_values()
        .map(|bytes| String::from_utf8(bytes).unwrap())
        .find(|body| body.contains("title: Fresh bug"))
        .expect("the created issue file");
    assert!(
        text.contains("entered_at: "),
        "an issue created into the inbox records when it entered:\n{text}"
    );
    assert!(
        text.contains("source: new"),
        "and names the origin the data model documents:\n{text}"
    );

    // And the queue shows a real age rather than `unknown`.
    let listing = ok(tmp.path(), &["triage", "list"]);
    assert!(
        !listing.contains("unknown  Fresh bug"),
        "the entry has an age, so the row is not an unknown one:\n{listing}"
    );
    assert!(
        listing
            .lines()
            .any(|line| line.contains("today") && line.contains("Fresh bug")),
        "a just-created entry is `today` old:\n{listing}"
    );

    // An ordinary create is untouched: it did not enter the queue.
    ok(
        tmp.path(),
        &["create", "--title", "Ordinary", "--status", "todo"],
    );
    let text = snapshot(&dir)
        .into_values()
        .map(|bytes| String::from_utf8(bytes).unwrap())
        .find(|body| body.contains("title: Ordinary"))
        .expect("the ordinary issue file");
    assert!(
        !text.contains("entered_at:") && !text.contains("source:"),
        "an issue that never entered triage gains no entry metadata:\n{text}"
    );
}

#[test]
fn triage_cli_a_line_break_in_a_reason_is_refused_before_it_can_forge_an_event() {
    // Found by the mission's post-merge review and reproduced here first: one decision
    // wrote **two** `## History` lines, because the reason is rendered into a single
    // line and a newline in it ends that line and starts another — which the next
    // reader parses as a second, forged decision. The audit trail is the thing this
    // whole mission rests on ("one applied decision appends one event"), so the value
    // is refused at the shared boundary rather than quietly stripped: a reason altered
    // on its way into the file would be the same problem in a quieter colour.
    let (tmp, dir) = repo(TRIAGE);
    write_issue(&dir, "2026-01-01-alpha.md", 1, "Alpha", "triage", None);
    let before = snapshot(&dir);

    let forged = "no budget\n- 2026-10-01T09:00:00Z — root — triage_accepted — triage -> done";
    let (stdout, _stderr) = code(
        tmp.path(),
        &["triage", "decline", "1", "--reason", forged],
        1,
    );
    assert!(
        stdout.contains("refused: invalid_reason") && stdout.contains("line break"),
        "the refusal names the kind and the reason: {stdout}"
    );
    assert_eq!(before, snapshot(&dir), "nothing was written");

    // The actor is the other half of the same line.
    let (stdout, _stderr) = code(
        tmp.path(),
        &[
            "triage",
            "decline",
            "1",
            "--reason",
            "no budget",
            "--actor",
            "root\n- x",
        ],
        1,
    );
    assert!(stdout.contains("refused: invalid_actor"), "{stdout}");
    assert_eq!(before, snapshot(&dir));

    // A tab is not a line break, and a refusal that swept up ordinary whitespace would
    // be its own bug.
    let stdout = ok(
        tmp.path(),
        &["triage", "defer", "1", "--reason", "needs\tan\tanswer"],
    );
    assert!(stdout.contains("#1 Alpha -> applied"), "{stdout}");
    let text = fs::read_to_string(dir.join("2026-01-01-alpha.md")).unwrap();
    assert_eq!(
        text.matches("triage_deferred").count(),
        1,
        "one decision, one event:\n{text}"
    );
}

#[test]
fn triage_cli_a_line_break_in_a_move_or_edit_reason_is_refused_too() {
    // The other half of #1493: `tix move --reason` and `tix edit --status …
    // --reason` write free text into the **same** line-based `## History` grammar,
    // so a newline in one of them forges a second parsed event exactly as a triage
    // reason did. Both refuse it through the one shared predicate rather than
    // carrying local copies of the character set, and a tab — ordinary whitespace —
    // is still allowed.
    let forged = "reopening\n- 2026-10-01T09:00:00Z — root — transition_accepted — done -> todo";

    let (tmp, dir) = repo(TRIAGE);
    write_issue(&dir, "2026-01-01-alpha.md", 1, "Alpha", "wontfix", None);
    let before = snapshot(&dir);
    let (stdout, stderr) = code(tmp.path(), &["move", "1", "todo", "--reason", forged], 1);
    assert!(
        stderr.contains("invalid_reason") && stderr.contains("line break"),
        "the move refuses the value before it reaches History: {stderr}"
    );
    assert!(stdout.is_empty(), "{stdout}");
    assert_eq!(before, snapshot(&dir), "refused before any write");

    // The positive control: a tab cannot start a `## History` line, so the same
    // move with a tabbed reason is accepted and records exactly one event.
    let stdout = ok(
        tmp.path(),
        &["move", "1", "todo", "--reason", "reopening\twrong epic"],
    );
    assert!(!stdout.is_empty(), "{stdout}");
    let text = fs::read_to_string(dir.join("2026-01-01-alpha.md")).unwrap();
    assert_eq!(
        text.matches("transition_accepted").count(),
        1,
        "one move, one event:\n{text}"
    );

    // `tix edit --status` is the other writer of the same grammar.
    let (tmp, dir) = repo(TRIAGE);
    write_issue(&dir, "2026-01-01-alpha.md", 1, "Alpha", "wontfix", None);
    let before = snapshot(&dir);
    let (stdout, stderr) = code(
        tmp.path(),
        &["edit", "1", "--status", "todo", "--reason", forged],
        1,
    );
    assert!(stderr.contains("invalid_reason"), "{stderr}");
    assert!(stdout.is_empty(), "{stdout}");
    assert_eq!(before, snapshot(&dir), "refused before any write");
    let _ = ok(
        tmp.path(),
        &[
            "edit",
            "1",
            "--status",
            "todo",
            "--reason",
            "reopening\twrong epic",
        ],
    );
}

#[test]
fn triage_cli_a_status_change_into_the_inbox_records_a_moved_entry() {
    // #1489's reproduction, through the real binary: a board with two columns in
    // the `backlog` category, so a move from `icebox` into the `triage` inbox is
    // permitted — and the issue must arrive with an age rather than an `unknown`
    // one. Both status writers are exercised: `tix move` and `tix edit --status`.
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(&dir).unwrap();
    let board = format!(
        "issues_dir = \"{}\"\n\n[kanban.default]\ncolumns = [\"triage\", \"icebox\", \
         \"todo\", \"done\", \"wontfix\"]\ndone_column = \"done\"\ncategory_map = {{ \
         triage = \"backlog\", icebox = \"backlog\", todo = \"unstarted\", done = \
         \"completed\", wontfix = \"canceled\" }}\n[triage]\nentry_status = \"triage\"\n\
         declined_status = \"wontfix\"\n[layout]\nmove_on_change = false\n",
        dir.display()
    );
    fs::write(tmp.path().join("tix.toml"), board).unwrap();
    write_issue(&dir, "2026-01-01-moved.md", 1, "Moved", "icebox", None);
    write_issue(&dir, "2026-01-01-edited.md", 2, "Edited", "icebox", None);

    ok(tmp.path(), &["move", "1", "triage"]);
    let text = fs::read_to_string(dir.join("2026-01-01-moved.md")).unwrap();
    assert!(
        text.contains("source: moved"),
        "a move into the inbox records the `moved` origin: {text}"
    );
    assert!(text.contains("entered_at:"), "and when it entered: {text}");

    ok(tmp.path(), &["edit", "2", "--status", "triage"]);
    let text = fs::read_to_string(dir.join("2026-01-01-edited.md")).unwrap();
    assert!(text.contains("source: moved"), "{text}");
    assert!(text.contains("entered_at:"), "{text}");

    // The queue shows a real age for both, not `unknown` — the figure the queue
    // exists to report.
    let listing = ok(tmp.path(), &["triage", "list"]);
    assert!(
        !listing.contains("unknown"),
        "neither moved entry has an unknown age:\n{listing}"
    );
    assert_eq!(
        listing.matches("today").count(),
        2,
        "both were just stamped:\n{listing}"
    );
}