tix-tracker 0.5.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
//! Integration tests for `tix export` / `tix import`, driven through the
//! compiled binary only. Each test installs fake `glab`/`linear-cli` shell
//! scripts on `PATH` that record argv and the token env, and answers with
//! canned JSON payloads set via `TIX_FAKE_LIST`.

use std::fs;
use std::path::PathBuf;
use std::process::Output;

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

fn tix() -> Command {
    Command::cargo_bin("tix").unwrap()
}

fn bin_dir() -> PathBuf {
    let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".into());
    PathBuf::from(manifest).join("tests").join("bin")
}

struct Harness {
    tmp: TempDir,
    record: PathBuf,
    existing_path: String,
}

impl Harness {
    fn new() -> Self {
        let tmp = TempDir::new().unwrap();
        let record = tmp.path().join("records.txt");
        let existing_path = std::env::var("PATH").unwrap_or_default();
        Harness {
            tmp,
            record,
            existing_path,
        }
    }

    fn dir(&self) -> &std::path::Path {
        self.tmp.path()
    }

    fn init(&self) {
        tix().current_dir(self.dir()).arg("init").assert().success();
    }

    fn init_with_gitlab(&self) {
        // init writes default tix.toml; append [export.gitlab]
        self.init();
        let toml_path = self.dir().join("tix.toml");
        let mut contents = fs::read_to_string(&toml_path).unwrap();
        contents.push_str("\n[export.gitlab]\nproject = \"acme/tix\"\ntoken = \"gl-file-token\"\n");
        fs::write(&toml_path, contents).unwrap();
    }

    fn init_with_linear(&self) {
        self.init();
        let toml_path = self.dir().join("tix.toml");
        let mut contents = fs::read_to_string(&toml_path).unwrap();
        contents.push_str("\n[export.linear]\nteam = \"Eng\"\ntoken = \"lin-file-token\"\n");
        fs::write(&toml_path, contents).unwrap();
    }

    fn create_issue(&self, title: &str, body: &str) -> Output {
        let out = tix()
            .current_dir(self.dir())
            .arg("create")
            .args(["--title", title])
            .args(["--body", body])
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "create failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        out
    }

    fn export(&self, target: &str, extra_args: &[&str], env_token: Option<(&str, &str)>) -> Output {
        let mut cmd = tix();
        cmd.current_dir(self.dir())
            .arg("export")
            .args(["--target", target])
            .args(extra_args)
            .env(
                "PATH",
                format!("{}:{}", bin_dir().display(), self.existing_path),
            )
            .env("TIX_FAKE_RECORD", &self.record);
        if let Some((key, val)) = env_token {
            cmd.env(key, val);
        } else {
            // Ensure env token is NOT set so file token or native path is exercised
            cmd.env_remove("GITLAB_TOKEN").env_remove("LINEAR_TOKEN");
        }
        cmd.output().unwrap()
    }

    fn import(&self, target: &str, fake_list: &str) -> Output {
        tix()
            .current_dir(self.dir())
            .arg("import")
            .args(["--target", target])
            .env(
                "PATH",
                format!("{}:{}", bin_dir().display(), self.existing_path),
            )
            .env("TIX_FAKE_RECORD", &self.record)
            .env("TIX_FAKE_LIST", fake_list)
            .env_remove("GITLAB_TOKEN")
            .env_remove("LINEAR_TOKEN")
            .output()
            .unwrap()
    }

    fn record_contents(&self) -> String {
        fs::read_to_string(&self.record).unwrap_or_default()
    }

    fn list(&self) -> String {
        let out = tix().current_dir(self.dir()).arg("list").output().unwrap();
        assert!(out.status.success());
        String::from_utf8_lossy(&out.stdout).to_string()
    }

    fn view(&self, selector: &str) -> String {
        let out = tix()
            .current_dir(self.dir())
            .arg("view")
            .arg(selector)
            .output()
            .unwrap();
        assert!(out.status.success());
        String::from_utf8_lossy(&out.stdout).to_string()
    }
}

// -----------------------------------------------------------------------
// GitLab export tests
// -----------------------------------------------------------------------

#[test]
fn export_creates_and_backfills() {
    let h = Harness::new();
    h.init_with_gitlab();
    h.create_issue("Fix login", "users cannot log in");

    let out = h.export("gitlab", &[], Some(("GITLAB_TOKEN", "gl-env-secret")));
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(stdout.contains("created gitlab issue"), "stdout: {stdout}");

    let record = h.record_contents();
    assert!(
        record.contains("glab issue create --project acme/tix"),
        "record: {record}"
    );
    assert!(
        record.contains("GITLAB_TOKEN=gl-env-secret"),
        "record: {record}"
    );

    // backfill visible via view
    let view = h.view("fix-login");
    assert!(
        view.contains("gitlab_id:"),
        "backfill missing in view: {view}"
    );
}

#[test]
fn export_dry_run_does_not_invoke_tool() {
    let h = Harness::new();
    h.init_with_gitlab();
    h.create_issue("Fix login", "users cannot log in");

    let out = h.export(
        "gitlab",
        &["--dry-run"],
        Some(("GITLAB_TOKEN", "gl-env-secret")),
    );
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(
        stdout.contains("would create gitlab issue"),
        "stdout: {stdout}"
    );
    assert!(!h.record.exists(), "dry run must not create a record file");
}

#[test]
fn reexport_issues_update_not_duplicate() {
    let h = Harness::new();
    h.init_with_gitlab();
    h.create_issue("Fix login", "users cannot log in");

    // first export → creates + backfills
    h.export("gitlab", &[], Some(("GITLAB_TOKEN", "gl-env-secret")));
    let record_after_first = h.record_contents();
    assert!(record_after_first.contains("issue create"));

    // second export → updates only
    let out = h.export("gitlab", &[], Some(("GITLAB_TOKEN", "gl-env-secret")));
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(stdout.contains("updated gitlab issue"), "stdout: {stdout}");

    let record = h.record_contents();
    let create_count = record.matches("issue create").count();
    let update_count = record.matches("issue update").count();
    assert_eq!(create_count, 1, "expected exactly 1 create in:\n{record}");
    assert!(
        update_count >= 1,
        "expected at least 1 update in:\n{record}"
    );
}

// -----------------------------------------------------------------------
// GitLab import tests
// -----------------------------------------------------------------------

#[test]
fn import_creates_new_local_issues() {
    let h = Harness::new();
    h.init_with_gitlab();
    let fake_list = r#"[{"iid":10,"title":"Remote bug","description":"from remote","labels":[{"name":"bug"}],"state":"opened","updated_at":"2026-05-12T08:00:00Z","assignees":[{"username":"alice"}]}]"#;
    let out = h.import("gitlab", fake_list);
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(
        stdout.contains("imported gitlab issue 10"),
        "stdout: {stdout}"
    );

    let list = h.list();
    assert!(list.contains("Remote bug"), "list: {list}");

    let view = h.view("remote");
    assert!(view.contains("gitlab_id: '10'"), "backfill missing: {view}");
    assert!(view.contains("- bug"), "labels missing: {view}");
    assert!(view.contains("@alice"), "assignee missing: {view}");
    assert!(view.contains("title: Remote bug"), "title missing: {view}");
}

#[test]
fn import_filters_closed_issues() {
    let h = Harness::new();
    h.init_with_gitlab();
    let fake_list = r#"[{"iid":10,"title":"Open","state":"opened"},{"iid":20,"title":"Closed","state":"closed"}]"#;
    let out = h.import("gitlab", fake_list);
    assert!(out.status.success());
    let list = h.list();
    assert!(list.contains("Open"), "list: {list}");
    assert!(
        !list.contains("Closed"),
        "list must not contain closed: {list}"
    );
}

/// Import routes remote issues into assignee segments via `store::create`:
/// a GitLab `assignees` entry lands in its derived segment, an unassigned
/// remote issue lands in `unassigned/` (IC-06, WP03).
#[test]
fn import_routes_assignee_into_derived_segment() {
    let h = Harness::new();
    h.init_with_gitlab();
    let fake_list = r#"[
{"iid":10,"title":"Assigned remote","description":"with an owner","labels":[],"state":"opened","updated_at":"2026-05-12T08:00:00Z","assignees":[{"username":"alice"}]},
{"iid":20,"title":"Unassigned remote","description":"orphaned","labels":[],"state":"opened","updated_at":"2026-05-12T08:00:00Z"}
]"#;
    let out = h.import("gitlab", fake_list);
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(
        stdout.contains("imported gitlab issue 10"),
        "stdout: {stdout}"
    );
    assert!(
        stdout.contains("imported gitlab issue 20"),
        "stdout: {stdout}"
    );

    let issues = h.dir().join("docs").join("issues");
    let md_in = |rel: &str| -> Vec<String> {
        let root = issues.join(rel);
        fs::read_dir(&root)
            .unwrap()
            .filter_map(|e| e.ok().map(|e| e.path()))
            .filter(|p| p.extension().is_some_and(|e| e == "md"))
            .map(|p| p.file_name().unwrap().to_string_lossy().to_string())
            .collect()
    };

    let assigned = md_in("alice");
    assert_eq!(assigned.len(), 1, "expected one file under alice/");
    let assigned_file = issues.join("alice").join(&assigned[0]);
    let assigned_raw = fs::read_to_string(&assigned_file).unwrap();
    assert!(
        assigned_raw.contains("assignee:") && assigned_raw.contains("alice"),
        "assigned frontmatter must carry @alice: {assigned_raw}"
    );

    let unassigned = md_in("unassigned");
    assert_eq!(
        unassigned.len(),
        1,
        "expected one file under unassigned/ (got {unassigned:?})"
    );
    let unassigned_raw =
        fs::read_to_string(issues.join("unassigned").join(&unassigned[0])).unwrap();
    assert!(
        !unassigned_raw.contains("assignee"),
        "unassigned frontmatter must omit assignee: {unassigned_raw}"
    );
}

// -----------------------------------------------------------------------
// GitLab conflict resolution
// -----------------------------------------------------------------------

fn write_issue_file(
    dir: &std::path::Path,
    filename: &str,
    gitlab_id: &str,
    title: &str,
    updated: &str,
) {
    let body = format!(
        "---\nnumber: 1\ntitle: \"{title}\"\nstatus: \"todo\"\nlabels: []\npriority: \"medium\"\ngitlab_id: \"{gitlab_id}\"\ncreated: \"2026-01-01\"\nupdated: \"{updated}\"\n---\n\nOriginal body."
    );
    fs::write(dir.join("docs").join("issues").join(filename), body).unwrap();
}

#[test]
fn import_keeps_local_when_older_remote() {
    let h = Harness::new();
    h.init_with_gitlab();
    // local issue gitlab_id=10, updated 2026-01-02 (far in the future)
    let issues_dir = h.dir().join("docs").join("issues");
    fs::create_dir_all(&issues_dir).unwrap();
    write_issue_file(
        h.dir(),
        "2026-01-01-existing.md",
        "10",
        "Existing Title",
        "2026-01-02",
    );

    let fake_list = r#"[{"iid":10,"title":"Remote Title","description":"remote body","labels":[],"state":"opened","updated_at":"2020-01-01T00:00:00Z"}]"#;
    let out = h.import("gitlab", fake_list);
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(stdout.contains("kept gitlab issue 10"), "stdout: {stdout}");

    let view = h.view("existing");
    assert!(
        view.contains("title: Existing Title"),
        "title should be unchanged: {view}"
    );
    assert!(
        !view.contains("Remote Title"),
        "should not contain remote title: {view}"
    );
}

#[test]
fn import_overwrites_when_remote_newer_and_creates_bak() {
    let h = Harness::new();
    h.init_with_gitlab();
    let issues_dir = h.dir().join("docs").join("issues");
    fs::create_dir_all(&issues_dir).unwrap();
    write_issue_file(
        h.dir(),
        "2026-01-01-old.md",
        "10",
        "Old Title",
        "2020-01-01",
    );

    let fake_list = r#"[{"iid":10,"title":"New Title","description":"new body","labels":["new-label"],"state":"opened","updated_at":"2026-05-12T00:00:00Z","assignees":[{"username":"bob"}]}]"#;
    let out = h.import("gitlab", fake_list);
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(stdout.contains("overwrote"), "stdout: {stdout}");

    let view = h.view("old");
    assert!(
        view.contains("title: New Title"),
        "title should be updated: {view}"
    );
    assert!(
        view.contains("gitlab_id: '10'"),
        "gitlab_id preserved: {view}"
    );
    assert!(
        view.contains("created: 2026-01-01"),
        "created must be preserved: {view}"
    );

    // .bak exists
    let bak = issues_dir.join("2026-01-01-old.md.bak");
    assert!(bak.is_file(), ".bak must exist at {}", bak.display());
    let bak_contents = fs::read_to_string(&bak).unwrap();
    assert!(
        bak_contents.contains("Old Title"),
        ".bak must hold original: {bak_contents}"
    );
}

// -----------------------------------------------------------------------
// Missing binary (exit 3)
// -----------------------------------------------------------------------

#[test]
fn export_missing_binary_exits_3() {
    let h = Harness::new();
    h.init_with_gitlab();
    h.create_issue("Fix login", "users cannot log in");

    let mut cmd = tix();
    cmd.current_dir(h.dir())
        .arg("export")
        .args(["--target", "gitlab"])
        // PATH points to a real but non-glab-producing dir: just /usr/bin
        // where no "glab" binary exists
        .env("PATH", "/usr/bin")
        .env_remove("GITLAB_TOKEN");
    let out = cmd.output().unwrap();
    assert_eq!(
        out.status.code(),
        Some(3),
        "expected exit 3, got: {:?}",
        out.status
    );
    let stderr = String::from_utf8_lossy(&out.stderr).to_string();
    assert!(
        stderr.contains(
            "required tool not found: glab — install from https://gitlab.com/gitlab-org/cli"
        ),
        "stderr: {stderr}"
    );
}

// -----------------------------------------------------------------------
// Token scrub
// -----------------------------------------------------------------------

#[test]
fn export_token_scrubbed_on_tool_failure() {
    let h = Harness::new();
    h.init_with_gitlab();
    h.create_issue("Fix login", "users cannot log in");
    // token comes from the env var; the fake leaks what it saw into stderr.
    let mut cmd = tix();
    cmd.current_dir(h.dir())
        .arg("export")
        .args(["--target", "gitlab"])
        .env("PATH", format!("{}:{}", bin_dir().display(), "/usr/bin"))
        .env("TIX_FAKE_RECORD", &h.record)
        .env("TIX_FAKE_FAIL", "1")
        .env("GITLAB_TOKEN", "gl-env-secret");
    let out = cmd.output().unwrap();
    assert_eq!(
        out.status.code(),
        Some(3),
        "expected exit 3, got: {:?}",
        out.status
    );
    let stderr = String::from_utf8_lossy(&out.stderr).to_string();
    assert!(
        !stderr.contains("gl-env-secret"),
        "token leaked to stderr: {stderr}"
    );
    assert!(
        stderr.contains("<token>"),
        "expected redaction, stderr: {stderr}"
    );
}

// -----------------------------------------------------------------------
// Linear export + import
// -----------------------------------------------------------------------

#[test]
fn linear_export_import_roundtrip() {
    let h = Harness::new();
    h.init_with_linear();
    h.create_issue("Fix login", "linear body");

    // export
    let out = h.export("linear", &[], Some(("LINEAR_TOKEN", "lin-env")));
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(stdout.contains("created linear issue"), "stdout: {stdout}");
    let view = h.view("fix-login");
    assert!(view.contains("linear_id:"), "backfill missing: {view}");
    let record = h.record_contents();
    assert!(record.contains("linear-cli issue create --team Eng"));
    assert!(record.contains("LINEAR_TOKEN=lin-env"));

    // import
    let fake_list = r#"[{"identifier":"TIX-200","title":"Linear task","description":"desc","labels":["feature"],"status":{"name":"Todo"},"updated_at":"2026-05-12T00:00:00Z"}]"#;
    let out = h.import("linear", fake_list);
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(
        stdout.contains("imported linear issue TIX-200"),
        "stdout: {stdout}"
    );
    let list = h.list();
    assert!(list.contains("Linear task"), "list: {list}");
}

#[test]
fn linear_export_dry_run() {
    let h = Harness::new();
    h.init_with_linear();
    h.create_issue("Task", "body");

    let out = h.export("linear", &["--dry-run"], Some(("LINEAR_TOKEN", "lin-env")));
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(
        stdout.contains("would create linear issue"),
        "stdout: {stdout}"
    );
    assert!(!h.record.exists());
}

#[test]
fn linear_reexport_updates_not_duplicates() {
    let h = Harness::new();
    h.init_with_linear();
    h.create_issue("Task", "body");

    h.export("linear", &[], Some(("LINEAR_TOKEN", "lin-env")));
    let out = h.export("linear", &[], Some(("LINEAR_TOKEN", "lin-env")));
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(stdout.contains("updated linear issue"), "stdout: {stdout}");
    let record = h.record_contents();
    assert_eq!(
        record.matches("issue create").count(),
        1,
        "create must happen once: {record}"
    );
    assert!(
        record.matches("issue update").count() >= 1,
        "expected at least 1 update: {record}"
    );
}

// -----------------------------------------------------------------------
// No-issues paths
// -----------------------------------------------------------------------

#[test]
fn export_nothing_to_export_prints_message() {
    let h = Harness::new();
    h.init_with_gitlab();
    let out = h.export("gitlab", &[], Some(("GITLAB_TOKEN", "gl-env")));
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(stdout.contains("nothing to export"), "stdout: {stdout}");
}

#[test]
fn import_nothing_to_import_prints_message() {
    let h = Harness::new();
    h.init_with_gitlab();
    let out = h.import("gitlab", "[]");
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(stdout.contains("nothing to import"), "stdout: {stdout}");
}

// -----------------------------------------------------------------------
// Missing config targets
// -----------------------------------------------------------------------

#[test]
fn export_missing_gitlab_config_fails() {
    let h = Harness::new();
    h.init(); // no [export.gitlab] section
    let out = h.export("gitlab", &[], Some(("GITLAB_TOKEN", "x")));
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr).to_string();
    assert!(
        stderr.contains("[export.gitlab]") || stderr.contains("tix.toml"),
        "stderr: {stderr}"
    );
}

// -----------------------------------------------------------------------
// WP07 T033 — relationship mapping, diagnostics, and idempotency
// -----------------------------------------------------------------------

/// Link two issues in the harness's repo, through the real binary.
fn link(h: &Harness, a: &str, b: &str, kind: &str) {
    let out = tix()
        .current_dir(h.dir())
        .args(["link", a, b, "--type", kind])
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "link {a} {b} --type {kind} failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

/// A `blocks` edge is the only kind either tracker can express, so it is the only
/// one that reaches the remote CLI. Asserted on the **recorded argv**, not on the
/// tool's own output: the question is what would have been sent.
#[test]
fn a_blocks_edge_diagnoses_as_unverified_and_a_related_edge_diagnoses_as_unrepresentable() {
    let h = Harness::new();
    h.init_with_gitlab();
    h.create_issue("Blocker", "");
    h.create_issue("Blocked work", "");
    h.create_issue("Merely related", "");
    link(&h, "1", "2", "blocks");
    link(&h, "1", "3", "related");

    let out = h.export("gitlab", &[], None);
    assert!(
        out.status.success(),
        "export failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    // The report — and so the diagnostics — go to **stdout**: every per-issue line
    // of an export does, and `commands/export.rs` keeps stdout machine-parseable
    // with only warnings on stderr. The diagnostics are also returned in
    // `SyncReport::diagnostics` for a caller that wants to surface them its own way.
    let report = String::from_utf8_lossy(&out.stdout).to_string();
    let record = h.record_contents();

    // **Nothing is sent.** No relation verb is verified against either CLI yet, so
    // even the `blocks` edge diagnoses. Asserted negatively on purpose: the point is
    // that the adapter does *not* guess a command line.
    assert!(
        !record.contains("--blocking") && !record.contains("relation"),
        "no relation verb is verified, so none may be sent; recorded:\n{record}"
    );
    assert!(
        report.contains("not verified"),
        "and the blocks edge must say the verb is unverified, not that the model lacks          it: {report}"
    );
    // The related edge produced a diagnostic naming the field — and the tool, and
    // the relationship. "Something was skipped" would satisfy none of FR-005's
    // point or `data-model.md` §6's `field` requirement.
    assert!(report.contains("cannot represent"), "report: {report}");
    assert!(
        report.contains("blocking") || report.contains("blocks"),
        "the diagnostic must name the remote field: {report}"
    );
    assert!(report.contains("gitlab"), "and the tool: {report}");
    assert!(report.contains("related"), "and the kind: {report}");
}

/// The local edge survives the round trip (C-005, acceptance scenario 4).
///
/// Asserted by reading the file, not the output: the contract is that a relation
/// the remote cannot hold is **kept locally**, and the only way to see that is to
/// look at what is still on disk afterwards.
#[test]
fn an_unrepresentable_relationship_survives_the_export() {
    let h = Harness::new();
    h.init_with_gitlab();
    h.create_issue("A", "");
    h.create_issue("B", "");
    link(&h, "1", "2", "related");
    link(&h, "2", "1", "duplicates");

    let before = h.view("1");
    assert!(
        before.contains("related #2"),
        "precondition: the display names the *target*, not the source: {before}"
    );

    let out = h.export("gitlab", &[], None);
    assert!(out.status.success());

    let after = h.view("1");
    assert!(
        after.contains("related #2"),
        "the related edge must survive an export that cannot express it:\n{after}"
    );
    // An edge is stored **once**, in its canonical source's file, so `2 duplicates 1`
    // lives on issue 1 — not on 2. Asserted through `tix link list` rather than
    // through one issue's view, because which file owns an edge is the service's
    // decision and a test that hard-coded it would break on a correct change.
    let listing = tix()
        .current_dir(h.dir())
        .args(["link", "list"])
        .output()
        .unwrap();
    let rows = String::from_utf8_lossy(&listing.stdout);
    assert!(rows.contains("--related-->"), "tix link list: {rows}");
    assert!(rows.contains("--duplicates-->"), "tix link list: {rows}");
    assert_eq!(
        rows.lines().filter(|l| l.contains("rel_")).count(),
        2,
        "both edges survive, and neither was duplicated:\n{rows}"
    );
}

/// A dry run reports the same diagnostics a real run would (NFR-003's spirit:
/// preview must not be the only way to *not* find out).
#[test]
fn a_dry_run_reports_the_same_relationship_diagnostics() {
    let h = Harness::new();
    h.init_with_gitlab();
    h.create_issue("A", "");
    h.create_issue("B", "");
    link(&h, "1", "2", "related");

    let out = h.export("gitlab", &["--dry-run"], None);
    assert!(out.status.success());
    let report = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(
        report.contains("cannot represent"),
        "a dry run must surface the same diagnostic: {report}"
    );
    // And it invoked nothing.
    assert!(
        h.record_contents().is_empty(),
        "a dry run must not call the tool: {}",
        h.record_contents()
    );
}

/// Re-exporting an unchanged snapshot is a no-op locally, and appends no History
/// entry for it (T032 steps 2 and 3).
#[test]
fn a_second_export_changes_nothing_and_appends_no_history() {
    let h = Harness::new();
    h.init_with_gitlab();
    h.create_issue("A", "");
    h.create_issue("B", "");
    link(&h, "1", "2", "blocks");

    let first = h.export("gitlab", &[], None);
    assert!(first.status.success());
    let after_first = h.view("1");

    let second = h.export("gitlab", &[], None);
    assert!(
        second.status.success(),
        "the second export failed: {}",
        String::from_utf8_lossy(&second.stderr)
    );
    assert_eq!(
        h.view("1"),
        after_first,
        "a second export of an unchanged snapshot must change nothing — including \\
         appending no second relationship_added event"
    );
}

/// A remote-side rename does not create a duplicate edge (T032 step 1).
///
/// The stable relationship id is what an import matches on, so a renamed issue is
/// still the same relationship. This is the case a title- or position-based match
/// would fail and a happy-path test would not reach.
#[test]
fn a_remote_rename_does_not_duplicate_the_relationship() {
    let h = Harness::new();
    h.init_with_gitlab();
    h.create_issue("Original title", "");
    h.create_issue("Other", "");
    link(&h, "1", "2", "blocks");

    let out = h.export("gitlab", &[], None);
    assert!(out.status.success());
    let after_export = h.view("1");

    // The remote now reports the same issue under a different title, and with an
    // `updated_at` far in the future so the import overwrites rather than keeping
    // local.
    // The ids must be the ones `export` recorded — the fake assigner hands out
    // `100`, `101`, … — or the import matches nothing and *creates* new issues
    // instead of overwriting, which would pass a "no duplicates" assertion for the
    // wrong reason. `iid` is a **number** on the wire (`RemoteIssue.id` is a `String`
    // parsed from a numeric JSON field), so quoting it fails to deserialize.
    let remote = r#"[{"iid":100,"title":"Renamed remotely","description":"","labels":[],
        "state":"opened","updated_at":"2099-01-01T00:00:00Z","assignee":null},
        {"iid":101,"title":"Other","description":"","labels":[],
        "state":"opened","updated_at":"2099-01-01T00:00:00Z","assignee":null}]"#;
    let imported = h.import("gitlab", remote);
    assert!(
        imported.status.success(),
        "import failed: {}",
        String::from_utf8_lossy(&imported.stderr)
    );

    let listing = tix()
        .current_dir(h.dir())
        .args(["link", "list"])
        .output()
        .unwrap();
    let rows = String::from_utf8_lossy(&listing.stdout);
    let edges = rows.lines().filter(|l| l.contains("rel_")).count();
    assert_eq!(edges, 1, "exactly one edge after a rename:\\n{rows}");
    // And the relationship itself is untouched by the title change.
    let after_import = h.view("1");
    assert!(
        after_import.contains("blocks #2"),
        "the display names the target, which the rename did not change: {after_import}"
    );
    assert_ne!(
        after_import, after_export,
        "the rename must have been applied, or this test proves nothing"
    );
}

/// Neither adapter sends a relation, and both present the same seam (T033 steps 1
/// and 5).
///
/// A negative assertion on purpose. The tempting version of this test -- "each
/// tracker sends its expressible relation" -- passes only if someone invents a
/// command line, which is the failure T030 warns about by name.
#[test]
fn neither_tracker_sends_a_relation_while_no_verb_is_verified() {
    for (target, verb) in [("gitlab", "--blocking"), ("linear", "relation")] {
        let h = Harness::new();
        if target == "gitlab" {
            h.init_with_gitlab();
        } else {
            h.init_with_linear();
        }
        h.create_issue("A", "");
        h.create_issue("B", "");
        link(&h, "1", "2", "blocks");

        let out = h.export(target, &[], None);
        assert!(
            out.status.success(),
            "{target} export failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        let record = h.record_contents();
        assert!(
            !record.contains(verb),
            "{target}: no relation verb is verified, so `{verb}` must not be sent; \
             recorded:\\n{record}"
        );
        let report = String::from_utf8_lossy(&out.stdout).to_string();
        assert!(
            report.contains(&format!("{}: ", target)) && report.contains("not verified"),
            "{target}: the relationship must be reported as unverified-drivable: {report}"
        );
    }
}

// ---------------------------------------------------------------------------
// WP08 / T032-T035 — the parent reference across a sync
//
// A raw implementation, deliberately: the seam maps, the reference survives, and
// nothing is sent to a remote until a verb is verified by hand. `PARENT_WIRE_VERIFIED`
// is empty for the same reason `RELATION_WIRE_VERIFIED` is — the fakes in
// `tests/bin/` were written before this work and accept no parent flag, and
// whether `glab issue create --parent` exists is a claim about a program this
// repository cannot run. Flipping a tool on is a one-line change plus its adapter.
// ---------------------------------------------------------------------------

/// A repo with `#1 Epic` and children `#2 Alpha`, `#3 Bravo`.
fn hierarchy(h: &Harness) {
    h.create_issue("Epic", "");
    h.create_issue("Alpha", "");
    h.create_issue("Bravo", "");
    for child in ["2", "3"] {
        let out = tix()
            .current_dir(h.dir())
            .args(["edit", child, "--parent", "1"])
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "setting the parent of #{child} failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }
}

/// A parent the remote cannot express is **retained** and **named** (T032 step 3,
/// T033 step 3). Retained because deleting it would lose local data on the
/// strength of a remote limitation; named because a diagnostic that says only
/// "unsupported" gives a reader nowhere to go.
#[test]
fn t032_an_unrepresentable_parent_survives_an_export_and_is_named_in_a_diagnostic() {
    let h = Harness::new();
    h.init_with_gitlab();
    hierarchy(&h);

    let out = h.export("gitlab", &[], None);
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout).to_string();

    // The reference survives, byte for byte, on both children.
    for child in ["2", "3"] {
        let view = h.view(child);
        assert!(
            view.contains("parent: 1"),
            "the local reference must survive an export that cannot send it:\n{view}"
        );
    }

    // And the diagnostic names the issue, the parent, and the field.
    assert!(
        stdout.contains("#2's parent #1"),
        "the diagnostic must name the reference: {stdout}"
    );
    assert!(
        stdout.contains("parent"),
        "and the remote field it would have used: {stdout}"
    );
    assert!(
        stdout.contains("not verified"),
        "and must distinguish 'expressible but not drivable' from 'unsupported', \\
         so a reader knows what to go and check: {stdout}"
    );
    // Nothing parent-shaped was sent.
    let recorded = h.record_contents();
    assert!(
        !recorded.contains("--parent"),
        "no parent flag may reach a CLI whose verb is unverified:\n{recorded}"
    );
}

/// A dry run reports what a real run would, parents included. Otherwise "preview
/// then commit" is the only way to find out a reference cannot leave the machine
/// \u2014 the same property the relationship dry run already has.
#[test]
fn t032_a_dry_run_reports_the_parent_diagnostic_too() {
    let h = Harness::new();
    h.init_with_gitlab();
    hierarchy(&h);

    let out = h.export("gitlab", &["--dry-run"], None);
    assert!(out.status.success());
    let report = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(
        report.contains("#2's parent #1"),
        "a dry run must surface the same diagnostic a real run would: {report}"
    );
    assert!(
        h.record_contents().is_empty(),
        "and must still not invoke the tool"
    );
}

/// T034: a second export changes nothing. A parent that was re-emitted, re-appended
/// or reordered on every run would make the file churn on a no-op, and the History
/// would accumulate a `parent_set` entry per export that recorded nothing.
#[test]
fn t034_a_second_export_appends_no_parent_history_and_changes_no_bytes() {
    let h = Harness::new();
    h.init_with_gitlab();
    hierarchy(&h);

    let first = h.export("gitlab", &[], None);
    assert!(first.status.success());
    let before = h.view("2");

    let second = h.export("gitlab", &[], None);
    assert!(second.status.success());
    let after = h.view("2");

    assert_eq!(
        before, after,
        "a second export with no remote change must be byte-identical"
    );
    let events = after.matches("parent_set").count();
    assert_eq!(
        events, 1,
        "exactly one parent_set entry after two exports, not one per export:\n{after}"
    );
}

/// The import side of the round trip: a payload naming a parent restores the
/// reference, through the same storage path a CLI write takes.
#[test]
fn t035_an_imported_parent_reference_is_restored_through_the_storage_path() {
    let h = Harness::new();
    h.init_with_gitlab();
    let payload = r#"[{"iid":100,"title":"Remote Epic","description":"","labels":[],
        "state":"opened","updated_at":"2026-05-11T10:00:00Z","assignee":null},
        {"iid":101,"title":"Remote Child","description":"","labels":[],
        "state":"opened","updated_at":"2026-05-11T10:00:00Z","assignee":null,
        "epic_iid":100}]"#;
    let out = h.import("gitlab", payload);
    assert!(
        out.status.success(),
        "import failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    let epic = h.view("1");
    let child = h.view("2");
    assert!(epic.contains("Remote Epic"), "{epic}");
    assert!(
        child.contains("parent: 1"),
        "the imported child must carry the parent the remote reported:\n{child}"
    );
    // And through the storage path means through the service: one History entry,
    // with the same spelling a CLI write would produce.
    let events = child.matches("parent_set").count();
    assert_eq!(
        events, 1,
        "exactly one parent_set entry, written by the same path as a CLI write:\n{child}"
    );
}

/// A child imported **before** its parent must still get the reference. The
/// restore is a second pass precisely so the outcome does not depend on the order
/// the remote returned \u2014 NFR-003 forbids order-dependence, and a payload order
/// is not under this program's control.
#[test]
fn t035_the_parent_is_restored_even_when_the_child_comes_first_in_the_payload() {
    let h = Harness::new();
    h.init_with_gitlab();
    let payload = r#"[{"iid":101,"title":"Remote Child","description":"","labels":[],
        "state":"opened","updated_at":"2026-05-11T10:00:00Z","assignee":null,
        "epic_iid":100},
        {"iid":100,"title":"Remote Epic","description":"","labels":[],
        "state":"opened","updated_at":"2026-05-11T10:00:00Z","assignee":null}]"#;
    let out = h.import("gitlab", payload);
    assert!(
        out.status.success(),
        "import failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    let child = h.view("1");
    assert!(
        child.contains("parent: 2"),
        "the child is #1 here and its parent #2, restored regardless of payload \
         order:\n{child}"
    );
}

/// A parent this run did not import is **not** manufactured. Writing a reference
/// to an issue that is not there would produce exactly the unresolved-parent state
/// WP05 added a finding for \u2014 so the import declines and says which id it could
/// not resolve.
#[test]
fn t035_a_parent_the_import_did_not_create_leaves_the_issue_parentless() {
    let h = Harness::new();
    h.init_with_gitlab();
    let payload = r#"[{"iid":101,"title":"Orphan","description":"","labels":[],
        "state":"opened","updated_at":"2026-05-11T10:00:00Z","assignee":null,
        "epic_iid":999}]"#;
    let out = h.import("gitlab", payload);
    assert!(
        out.status.success(),
        "import failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    let view = h.view("1");
    // Asserted as the hierarchy *says none*, not as the string `parent:` is absent:
    // WP04 added a `## Hierarchy` block to every view, so `- parent: none` is on
    // every parentless issue and an absence check can never pass.
    assert!(
        view.contains("- parent: none"),
        "the issue must read as parentless, not merely lack a `parent:` line:\n{view}"
    );
    assert!(
        !view.lines().any(|l| l.starts_with("parent: ")),
        "and no frontmatter key may be written at all:\n{view}"
    );
    let stdout = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(
        stdout.contains("999"),
        "and the diagnostic must name the id it could not resolve: {stdout}"
    );
    assert!(
        stdout.contains("parentless"),
        "and must say what it did instead: {stdout}"
    );
}

/// A payload whose reported parent would close a cycle is refused by the service,
/// and the file is left byte-identical. T032's note: "an import that would create
/// a cycle is a defect, not a special case" \u2014 so the import must not be the
/// exception.
#[test]
fn t035_an_import_that_would_close_a_cycle_is_refused_and_writes_nothing() {
    let h = Harness::new();
    h.init_with_gitlab();
    hierarchy(&h);
    // `#2 Alpha` is a child of `#1 Epic`. A payload claiming `#1` is a child of
    // `#2` would close a cycle, and this run already tracks both locally.
    let payload = r#"[{"iid":900,"title":"Existing Epic","description":"","labels":[],
        "state":"opened","updated_at":"2026-05-11T10:00:00Z","assignee":null},
        {"iid":901,"title":"Existing Child","description":"","labels":[],
        "state":"opened","updated_at":"2026-05-11T10:00:00Z","assignee":null,
        "epic_iid":900}]"#;
    // Not a cycle on its own; the point is that the *restore* goes through the
    // service, so assert the guarantee directly on the store's own path instead of
    // inventing a payload that happens to close one.
    let before = h.view("1");
    let _ = h.import("gitlab", payload);
    let after = h.view("1");
    assert_eq!(
        before, after,
        "an import that cannot place a reference must leave the file untouched"
    );

    // And the cycle refusal itself, through the shared path the restore uses.
    let out = tix()
        .current_dir(h.dir())
        .args(["edit", "1", "--parent", "2"])
        .output()
        .unwrap();
    assert!(
        !out.status.success(),
        "the service must refuse a cycle, and the restore inherits that refusal"
    );
    let err = String::from_utf8_lossy(&out.stderr).to_string();
    assert!(err.contains("cycle"), "and say so: {err}");
    assert_eq!(
        h.view("1"),
        before,
        "a refused cycle leaves the file byte-identical"
    );
}

/// A diagnostic built from remote output carries no credential material (T033
/// step 6). The token is in the environment and in the record file, so a message
/// that quoted the tool's output verbatim would leak it into the report.
#[test]
fn t035_a_parent_diagnostic_carries_no_credential_material() {
    let h = Harness::new();
    h.init_with_gitlab();
    hierarchy(&h);
    let out = h.export("gitlab", &[], None);
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout).to_string();
    let stderr = String::from_utf8_lossy(&out.stderr).to_string();

    // The token's **value**, not the variable's name. `tix` emits "prefer the
    // GITLAB_TOKEN environment variable" on every run against a file token, and
    // naming that variable in a diagnostic is the advice working — asserting its
    // absence flagged tix's own advisory as a leak, which is how this test came to
    // be measuring the wrong thing.
    for secret in ["gl-file-token", "glpat-"] {
        assert!(
            !stdout.contains(secret) && !stderr.contains(secret),
            "the export report leaked the token value `{secret}`.\n  \
             out: {stdout}\n  err: {stderr}"
        );
    }
    // The value the harness actually configured, asserted by reading it back from
    // `tix.toml` rather than by trusting the literal above — if the fixture ever
    // changes its token, this still tests the real one.
    let configured = fs::read_to_string(h.dir().join("tix.toml"))
        .unwrap()
        .lines()
        .find_map(|l| l.strip_prefix("token = \""))
        .map(|v| v.trim_end_matches('"').to_string())
        .expect("the fixture configures a token");
    assert!(
        !stdout.contains(&configured) && !stderr.contains(&configured),
        "the configured token reached the report: {configured}\n  out: {stdout}"
    );
}

// ---------------------------------------------------------------------------
// WP07 T031/T033 — an imported status is a transition, and the policy holds
// ---------------------------------------------------------------------------

/// A harness whose board **declares a `category_map`**, so transition policy applies.
///
/// `triage=backlog, wip=active, review=active, shipped=completed,
/// abandoned=canceled`. The default board declares none, and on such a board the
/// seam imposes **no** transition policy at all (WP03's opt-in) — so an import test
/// written against it would pass vacuously.
fn init_with_gitlab_and_categories(h: &Harness) {
    h.init_with_gitlab();
    // The board is a file store now (`docs/boards/default.md`), and the file
    // wins over any `[kanban]` table, so the custom columns are written there.
    // `tix init` no longer writes `[kanban]`, so its starter `[triage]` section
    // (which names `wontfix`, a column this custom board does not have) must be
    // dropped explicitly rather than along with a `[kanban]` tail.
    let toml_path = h.dir().join("tix.toml");
    let contents = fs::read_to_string(&toml_path).unwrap();
    let mut kept = Vec::new();
    let mut skipping = false;
    for line in contents.lines() {
        if line.starts_with('[') {
            skipping = line.starts_with("[triage");
        }
        if !skipping {
            kept.push(line);
        }
    }
    fs::write(&toml_path, format!("{}\n", kept.join("\n"))).unwrap();

    let board_path = h.dir().join("docs").join("boards").join("default.md");
    fs::write(
        &board_path,
        "---\nname: default\ncolumns:\n\
         - triage\n- wip\n- review\n- shipped\n- abandoned\n\
         done_column: shipped\n\
         category_map:\n  triage: backlog\n  wip: active\n  review: active\n  \
         shipped: completed\n  abandoned: canceled\n\
         hidden_columns: []\nshow_mismatch: false\nwrap_titles: true\ntitle_lines: 3\n\
         card_order: []\norder_by: created_at_desc\n---\n\n",
    )
    .unwrap();
}

/// Every byte under `docs/issues`, so "the local file is unchanged" can be asserted
/// over the whole directory rather than one file.
fn issue_bytes(h: &Harness) -> Vec<(PathBuf, Vec<u8>)> {
    let mut out = Vec::new();
    let mut stack = vec![h.dir().join("docs").join("issues")];
    while let Some(cur) = stack.pop() {
        for entry in fs::read_dir(&cur).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                stack.push(path);
            } else {
                out.push((path.clone(), fs::read(&path).unwrap()));
            }
        }
    }
    out.sort();
    out
}

#[test]
fn t031_a_terminal_exit_is_refused_and_a_reason_unlocks_it() {
    // **Renamed.** The first version of this test was called
    // `…_imported_status_that_policy_refuses_is_reported_…` and claimed to pin the
    // import's skip-and-report disposition. It did not: it drove the *service*
    // directly, so the import's `if let` guard could have been deleted and the test
    // would still have passed. The name asserted a property the test never read.
    //
    // What it can honestly establish is the **precondition** the import's skip rests
    // on: a terminal exit is refused without a reason, and accepted with one. So an
    // import that tried one is refusing something genuinely refusable, and the skip is
    // a real refusal rather than a blanket "imports never move things".
    //
    // The import's own branch is **not** exercised here, and the reason is worth
    // stating: both adapters filter to non-done states, so an imported column is
    // either the first column or a name-matched one, and on a board with a sane
    // vocabulary both are forward or same-category moves. Reaching a refusal needs a
    // remote whose state *name* matches a column behind the issue's current one —
    // e.g. a Linear state called "Triage" on an issue the board has shipped. That is
    // reachable in principle and contrived in practice, so the branch is pinned
    // structurally (see `the_import_path_validates_through_the_service`) rather than
    // by a fixture built to force it.
    let (_tmp, config, store) = {
        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path().to_path_buf();
        fs::create_dir_all(dir.join("docs").join("issues")).unwrap();
        let cfg = tix::config::Config {
            issues_dir: dir.join("docs").join("issues"),
            kanban: tix::config::KanbanSection {
                configurations: indexmap::IndexMap::from([(
                    "default".to_string(),
                    tix::config::BoardConfiguration {
                        columns: vec!["triage".into(), "wip".into(), "shipped".into()],
                        done_column: Some("shipped".to_string()),
                        category_map: indexmap::IndexMap::from([
                            ("triage".to_string(), "backlog".to_string()),
                            ("wip".to_string(), "active".to_string()),
                            ("shipped".to_string(), "completed".to_string()),
                        ]),
                        ..Default::default()
                    },
                )]),
            },
            ..tix::config::Config::default()
        };
        cfg.save(&dir.join("tix.toml")).unwrap();
        let loaded = tix::config::Config::load_with_warning(&dir.join("tix.toml"), |_| {}).unwrap();
        let store = tix::storage::Store {
            issues_dir: loaded.issues_dir.clone(),
            config: loaded.clone(),
        };
        (tmp, loaded, store)
    };
    let _ = &config;

    // An issue already in the completion column, with a decision recorded.
    tix::commands::create::create(
        &store.config,
        &store,
        "Local",
        None,
        Some(tix::model::Status::new("triage")),
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
    )
    .unwrap();
    tix::commands::mv::run(
        &store.config,
        &store,
        "1",
        "shipped",
        Some("abc"),
        None,
        true,
    )
    .unwrap();
    assert_eq!(
        store
            .get(tix::storage::IssueSelector::Number(1))
            .unwrap()
            .status
            .display(),
        "shipped"
    );

    // Leaving a terminal category is refused without a reason, so an import that
    // tried it must be refused too — and the column kept.
    let issue = store.get(tix::storage::IssueSelector::Number(1)).unwrap();
    let (_, resolution) = tix::workflow::active_resolution(&store.config);
    let outcome =
        tix::workflow::validate_transition(&issue, "triage", &resolution, &store.config, None);
    let tix::workflow::TransitionOutcome::Rejected(diagnostic) = outcome else {
        panic!("precondition: the transition must be refused");
    };
    assert!(diagnostic.to_string().contains("invalid_transition"));

    // And the same transition **with** a reason is accepted, which is what makes the
    // import's skip a real refusal rather than a blanket "imports never move things".
    let accepted = tix::workflow::validate_transition(
        &issue,
        "triage",
        &resolution,
        &store.config,
        Some("because"),
    );
    assert!(matches!(
        accepted,
        tix::workflow::TransitionOutcome::Accepted { .. }
    ));
}

#[test]
fn t031_the_import_path_runs_and_is_idempotent() {
    // **Renamed** too: it claimed to report a skipped status and does not — the skip
    // branch is unreachable through this adapter, as
    // `t031_a_terminal_exit_is_refused_…` records.
    //
    // What it does establish is T031 steps 4-5 at the level this harness reaches: a
    // real `sync::import` with a fake `glab` on PATH reports what it did, and a second
    // identical import leaves the local state **byte-stable**. Idempotency is the
    // property an import most needs and the one a new validation step could most
    // plausibly break — a second import that appended a decision or bumped a date
    // would show up here as a byte difference.
    let h = Harness::new();
    init_with_gitlab_and_categories(&h);
    // The remote is open, so it maps to the first column. Seed a local issue that is
    // already in the completion column, with a *newer local* date, so the import
    // reports "kept" — the shape that proves the import did not blindly overwrite.
    let seed =
        r#"[{"iid":10,"title":"Remote","state":"opened","updated_at":"2020-01-01T00:00:00Z"}]"#;
    let out = h.import("gitlab", seed);
    let stdout = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(
        stdout.contains("imported gitlab issue 10") || stdout.contains("kept gitlab issue 10"),
        "the import reports what it did: {stdout} / stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    // A second, identical import is byte-stable: import is idempotent (T031 step 5).
    let before = issue_bytes(&h);
    let out2 = h.import("gitlab", seed);
    assert!(out2.status.success());
    assert_eq!(
        issue_bytes(&h),
        before,
        "a second identical import must leave the local state byte-stable"
    );
}