tix-tracker 0.6.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
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
//! External tracker sync: orchestration for `tix export` / `tix import`,
//! the [`Tool`] selector, the [`CommandRunner`] spawn seam, and the pure
//! mapping / conflict-resolution rules.
//!
//! WP05 wires the CLI to `glab` (GitLab) and `linear-cli` (Linear) under
//! `contracts/external-tools.md`. Tokens are resolved through
//! [`token::resolve`] with env precedence, injected only as an env pair (never
//! argv), and every error/report surface scrubs the secret as `<token>`.
//!
//! The orchestration lives here so it is testable at module granularity by
//! pointing PATH at fake tool scripts; [`export`] / [`import`] are pure in the
//! sense that they take the store, tool, config and an output sink, and the
//! only externally visible side effects are local issue files, `tix.toml`,
//! the tool subprocesses, and what is written to `out`.
//!
//! ## One definition of "complete", and what this module's job actually is
//!
//! **A second local completion definition in this module is a C-004 defect.** There
//! used to be one: `remote_status_is_done(status) == (status == "closed" ||
//! status == "Done")`, a helper that looked like it decided whether an issue was
//! complete and in fact decided whether a *remote* state word was one of the two
//! this module happens to send. It had **no production callers** — WP02 removed the
//! last one — and its only remaining referrer was its own unit test, which is the
//! shape dead code takes when a test keeps it alive. Removed in WP07.
//!
//! What this module legitimately owns is the **translation**: the remote trackers
//! have a closed set of states (`opened`/`closed` for GitLab, a workflow-state label
//! for Linear), so something here has to say which remote word means closed and which
//! local column to send it as. That is a protocol concern and it is this module's
//! job.
//!
//! What it does **not** own is the meaning of *complete*. That is
//! [`crate::workflow::is_completed`] and nothing else — so [`local_to_remote_status`]
//! asks the service whether a local column is complete, and
//! [`remote_to_local_status`] picks the column the service calls complete via
//! [`completion_column`].
//!
//! The distinction matters because the two can disagree. A board whose `category_map`
//! puts `completed` on `shipped` while `done_column` is `done` has a completion
//! column that is *not* the one `done_column` names: comparing names exports
//! `shipped` as open and closes `done` instead, so the tracker and the board
//! disagree about the same issue in both directions.

use std::io::Write;

use crate::config::{BoardConfiguration, Config};
use crate::error::{Result, TixError};
use crate::model::{Issue, Status};
use crate::storage::Store;

pub mod glab;
pub mod linear;
pub mod token;

/// The supported external tracker, selected via `--target gitlab|linear`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tool {
    GitLab,
    Linear,
}

impl Tool {
    #[must_use]
    pub fn from_target(target: &str) -> Result<Tool> {
        match target {
            "gitlab" => Ok(Tool::GitLab),
            "linear" => Ok(Tool::Linear),
            other => Err(TixError::InvalidInput(format!(
                "unknown --target '{other}' — use gitlab or linear"
            ))),
        }
    }

    /// The token env var that wins over any `tix.toml` token.
    #[must_use]
    pub fn token_var(self) -> &'static str {
        match self {
            Tool::GitLab => "GITLAB_TOKEN",
            Tool::Linear => "LINEAR_TOKEN",
        }
    }

    /// The binary shelled out to.
    #[must_use]
    pub fn binary(self) -> &'static str {
        match self {
            Tool::GitLab => "glab",
            Tool::Linear => "linear-cli",
        }
    }

    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Tool::GitLab => "gitlab",
            Tool::Linear => "linear",
        }
    }
}

impl std::fmt::Display for Tool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The captured result of a spawned external tool.
///
/// `ProcessRunner` waits synchronously on the child (never kills it), so a
/// blocking tool blocks the sync — the contract's supported "wait" model for
/// `glab`/`linear-cli`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandOutcome {
    pub success: bool,
    pub status: Option<i32>,
    pub stdout: String,
    pub stderr: String,
}

impl CommandOutcome {
    /// The human-readable output chosen for error reporting: stderr when the
    /// tool failed and produced any, otherwise stdout.
    #[must_use]
    pub fn text(&self) -> &str {
        if self.success {
            &self.stdout
        } else if !self.stderr.trim().is_empty() {
            &self.stderr
        } else {
            &self.stdout
        }
    }
}

/// Spawn seam: production uses [`ProcessRunner`]; tests inject a
/// `FakeRunner` that records argv/env without spawning anything.
pub trait CommandRunner: Send {
    fn run(
        &self,
        program: &str,
        args: &[String],
        env: &[(String, String)],
    ) -> Result<CommandOutcome>;

    /// Downcasting hook so tests can inspect recorded calls on a fake.
    fn as_any(&self) -> &dyn std::any::Any;
}

/// Production runner: `std::process::Command` with a synchronous output wait.
///
/// A missing binary surfaces as [`TixError::External`] with the contract's
/// exit-3 wording (`contracts/external-tools.md`: "missing binary ... exit 3").
pub struct ProcessRunner;

impl CommandRunner for ProcessRunner {
    fn run(
        &self,
        program: &str,
        args: &[String],
        env: &[(String, String)],
    ) -> Result<CommandOutcome> {
        use std::process::Command;
        let mut cmd = Command::new(program);
        cmd.args(args);
        for (key, value) in env {
            cmd.env(key, value);
        }
        let output = cmd.output().map_err(|e| {
            if e.kind() == std::io::ErrorKind::NotFound {
                TixError::External(not_found_message(program))
            } else {
                TixError::External(format!("`{program}` failed to start: {e}"))
            }
        })?;
        Ok(CommandOutcome {
            success: output.status.success(),
            status: output.status.code(),
            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// Common surface both tracker adapters implement so the orchestration is
/// tool-agnostic.
///
/// `status` is the *remote* state/label already computed by the pure mapping
/// helpers (e.g. `closed`, `Done`, or the first work column). GitLab conveys
/// "done" via a separate close call ([`TrackerAdapter::mark_done`]); Linear
/// sends `--status Done` directly ([`TrackerAdapter::done_via_status`]).
pub trait TrackerAdapter {
    fn tool(&self) -> Tool;

    /// Create a remote issue and return its remote id (GitLab `iid`, Linear
    /// `identifier`).
    fn create_issue(
        &mut self,
        title: &str,
        body: &str,
        labels: &[String],
        assignee: Option<&str>,
        priority: Option<&str>,
        status: &str,
    ) -> Result<String>;

    /// Update an existing remote issue in place.
    #[allow(clippy::too_many_arguments)]
    fn update_issue(
        &mut self,
        remote_ref: &str,
        title: &str,
        body: &str,
        labels: &[String],
        assignee: Option<&str>,
        priority: Option<&str>,
        status: &str,
    ) -> Result<()>;

    /// Convey "done" (GitLab: `issue close <id>`). Only invoked when
    /// `done_via_status` is false.
    fn mark_done(&mut self, remote_ref: &str) -> Result<()>;

    /// List open remote issues (the import source). Closed/done issues are
    /// excluded.
    fn list_open(&mut self) -> Result<Vec<RemoteIssue>>;

    /// Linear sets done through the status flag; GitLab needs a separate
    /// close call.
    fn done_via_status(&self) -> bool;

    /// Send the relationships this tracker can express, after the issue itself
    /// exists (WP07 T030/T031).
    ///
    /// **Required, not defaulted.** A default no-op would let a tracker be added
    /// that silently never syncs relationships — the failure mode is a local
    /// relation that appears to sync and does not, which is the same silent-loss
    /// shape as a dropped edge. Two implementors is a small price for making the
    /// omission a compile error.
    ///
    /// The relationships arrive already filtered by
    /// [`map_relation_to_remote`], so an adapter never decides representability:
    /// it sends what the shared seam says it can send, and reports the rest. A
    /// `blocks` edge reaches here; a `related` edge never does.
    fn set_relations(&mut self, remote_ref: &str, relations: &[MappedRelation]) -> Result<()>;
}

/// A remote issue parsed from the tracker's JSON list output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteIssue {
    /// Remote id (GitLab `iid`, Linear `identifier`).
    pub id: String,
    pub title: String,
    pub description: String,
    pub labels: Vec<String>,
    /// Remote state (`closed` / `Done` / a column label, ...).
    pub state: String,
    /// ISO-8601 `updated_at`; `None` when the tool omitted it.
    pub updated_at: Option<String>,
    /// Best-effort single assignee (bare name, no `@`).
    pub assignee: Option<String>,
    /// The remote id of this issue's parent, when the remote reported one.
    ///
    /// A **remote** id, not a local number, because it is read from a remote
    /// payload and the two id spaces are not interchangeable. It is resolved to a
    /// local number by `local_parent_number` before anything is written, and
    /// `None` — rather than a guess — when it cannot be resolved.
    pub parent: Option<String>,
}

/// What one export or import run did, and what it could not do.
///
/// Returned rather than only written to the caller's `Write`, so a caller can
/// surface the diagnostics without scraping its own output — and so the count and
/// the diagnostics cannot disagree. Both entry points had `Result<usize>`; a count
/// alone cannot express "three issues synced, one relationship could not be".
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SyncReport {
    /// Issues created, updated, or overwritten.
    pub handled: usize,
    /// Relationships the remote could not represent, in encounter order.
    pub diagnostics: Vec<RemoteMappingDiagnostic>,
    /// Items whose **status** the transition policy refused (WP07 T031).
    ///
    /// Counted separately from `handled` because an import can do both: an issue
    /// whose title and body imported fine while its status was refused still counts
    /// as handled — the file was written — and also as skipped, because a column did
    /// not move. A single number cannot express that, and the report line it backs
    /// (`overwrote … without its status`) is the one a user has to be able to find.
    pub skipped: usize,
}

impl SyncReport {
    /// Record one unrepresentable relationship: keep the diagnostic for the
    /// caller, and say so on the human-facing stream too.
    fn note(&mut self, mapped: MappedRelation, out: &mut dyn Write) -> std::io::Result<()> {
        if let MappedRelation::Unsupported(diagnostic) = mapped {
            writeln!(out, "{diagnostic}")?;
            self.diagnostics.push(diagnostic);
        }
        Ok(())
    }

    /// The same, for a **parent** reference.
    ///
    /// Its own method rather than coercing a `MappedParent` into a
    /// `MappedRelation`: a parent is not a relationship, and the first cut did
    /// exactly that with an empty `field` and an empty `value` on the remote arm
    /// — which reads as though something were being sent when nothing is. The
    /// coercion compiled, produced the right output, and was wrong in a way only
    /// reading the type would have caught.
    fn note_parent(&mut self, mapped: MappedParent, out: &mut dyn Write) -> std::io::Result<()> {
        if let MappedParent::Unsupported(diagnostic) = mapped {
            writeln!(out, "{diagnostic}")?;
            self.diagnostics.push(diagnostic);
        }
        Ok(())
    }
}

/// The record emitted when a remote tracker cannot represent a local relation
/// (FR-005, C-005, `data-model.md` §6).
///
/// The four fields are fixed by the data model. `field` is the important one: it
/// is what makes the diagnostic actionable rather than a shrug, and
/// `data-model.md` §6 requires it for exactly that reason — "so the message can
/// name it".
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteMappingDiagnostic {
    /// The local relationship the diagnostic is about.
    pub relation_id: String,
    /// The specific unsupported remote field or relation name.
    pub field: String,
    /// Which adapter produced the diagnostic.
    pub tool: Tool,
    /// Human-readable text, safe for CLI output, the TUI, and lint.
    pub message: String,
}

impl std::fmt::Display for RemoteMappingDiagnostic {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}: {} cannot represent this relationship ({}) — {}",
            self.tool.as_str(),
            self.field,
            self.relation_id,
            self.message
        )
    }
}

/// The outcome of mapping one local relationship for one tracker: either a
/// remote representation, or a diagnostic naming why there is none.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MappedRelation {
    /// The remote field/value pair to send.
    Remote { field: String, value: String },
    /// The tracker cannot express this relation. The **local** relation is
    /// untouched — C-005 is that a relation the remote cannot hold still survives.
    Unsupported(RemoteMappingDiagnostic),
}

/// The remote fields each tracker can express for a typed relation, and the one it
/// maps every blocking edge onto.
///
/// This is the whole of the representability decision, and it is deliberately a
/// table keyed on `(Tool, RelationKind)` rather than logic spread across the two
/// adapters. Two consequences worth stating:
///
/// - **It is derived from what the adapters can actually send**, not from a guess
///   about their APIs. `glab issue update --blocking` and Linear's
///   `relations.create` are the only blocking affordances either CLI exposes here,
///   so `blocks` maps and nothing else does.
/// - **`blocks` maps; `related`, `duplicates`, and `blocked_by` do not.** Both
///   trackers' issue-update CLIs carry a title, body, labels, assignee, and state —
///   and no field for "this issue is related to that one". Guessing otherwise
///   would mean writing a title into a field, which is not a mapping.
///
/// `blocked_by` is the inverse of `blocks`, not a third thing, so it is reported
/// against the same remote field: naming `blocking` for it would be true but would
/// send the reader looking for a relation the tracker does not have.
///
/// ## Nothing is on the verified list yet
///
/// The mapping above knows what each tracker's *model* can express — GitLab and
/// Linear both have blocking relations in their APIs — but the adapters drive a
/// **CLI**, and whether `glab issue update --blocking` or a `linear-cli` relation
/// subcommand exists is a claim about a program this repository cannot run. The
/// fake `linear-cli` in `tests/bin/` models the tool as issue-only, and a fake
/// written before this work is better evidence of the surface than an assumption
/// made after it.
///
/// Sending an unverified command line is not a conservative default; it is a
/// production failure with a confusing message. So the seam maps, and the adapters
/// send nothing until a verb is verified. T030's instruction is explicit: "do
/// **not** invent remote capabilities: the mapping must reflect what the adapter
/// can actually express."
///
/// **So `tix export` currently exports no relationships at all**, and every
/// relationship produces a `RemoteMappingDiagnostic` — the contract's answer for
/// exactly this case (C-005: emitted, never resolved by deletion; the local
/// relation survives). The follow-up is narrow: verify both verbs against the real
/// CLIs, add the tool to this list, and implement its `set_relations`.
const RELATION_WIRE_VERIFIED: &[Tool] = &[];

// ---------------------------------------------------------------------------
// WP08 — the parent reference across a sync round trip
// ---------------------------------------------------------------------------

/// The CLI verbs that would carry a parent reference, per adapter.
///
/// **Empty, and for the same reason `RELATION_WIRE_VERIFIED` is.** Both trackers'
/// *models* have a hierarchy — GitLab has epics and child issues, Linear has
/// parent issues — but the adapters drive a CLI, and whether `glab issue create
/// --parent` or `linear-cli issue create --parent` exists is a claim about a
/// program this repository cannot run. The fakes in `tests/bin/` were written
/// before this work and accept no parent flag at all, which is better evidence of
/// the surface than an assumption made after it.
///
/// So the seam maps, and nothing is sent until a verb is verified. What *does*
/// work today — and is what the round trip covers — is that the reference
/// survives: the local parent is retained, the mapping is reported, and an import
/// restores a parent that came from the remote. Flipping a tool on here is a
/// one-line change plus its adapter implementation, once the verb is confirmed by
/// hand.
const PARENT_WIRE_VERIFIED: &[Tool] = &[];

/// The remote field each adapter would carry a parent in, if its verb existed.
///
/// Present so the diagnostic can *name* the thing that is missing, rather than
/// saying only that something is. A reader told "GitLab cannot express this" will
/// not go looking for the flag.
const GITLAB_PARENT_FIELD: &str = "parent";
const LINEAR_PARENT_FIELD: &str = "parent";

/// What one parent reference maps to on the wire.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MappedParent {
    /// The remote value to send, as a field/value pair like a relation.
    Remote { field: String, value: String },
    /// The adapter cannot carry it. The **local** reference is untouched, which is
    /// the same contract the relationship mapper follows (C-005): a reference the
    /// remote cannot hold still survives here.
    Unsupported(RemoteMappingDiagnostic),
}

/// Map one local parent reference to its remote representation, or say why not.
///
/// Pure: no adapter, no I/O, no configuration, and shared by both trackers so a
/// future one cannot be added with a divergent contract (T033).
#[must_use]
pub fn map_parent_to_remote(tool: Tool, issue_number: u32, parent: Option<u32>) -> MappedParent {
    let Some(parent) = parent else {
        // No reference is not a mapping problem. Reporting it would put a
        // diagnostic on every parentless issue in the repository, which is every
        // diagnostic being ignored.
        return MappedParent::Remote {
            field: parent_field(tool).to_string(),
            value: String::new(),
        };
    };
    let field = parent_field(tool);
    if PARENT_WIRE_VERIFIED.contains(&tool) {
        return MappedParent::Remote {
            field: field.to_string(),
            value: format!("#{parent}"),
        };
    }
    MappedParent::Unsupported(RemoteMappingDiagnostic {
        relation_id: format!("{issue_number}->{parent}"),
        field: field.to_string(),
        tool,
        message: format!(
            "#{issue_number}'s parent #{parent} is expressible in {}'s model as \
             `{field}`, but the CLI verb that would carry it is not verified, so \
             nothing is sent; the local reference is kept",
            tool.as_str()
        ),
    })
}

/// The field an adapter would carry a parent in.
fn parent_field(tool: Tool) -> &'static str {
    match tool {
        Tool::GitLab => GITLAB_PARENT_FIELD,
        Tool::Linear => LINEAR_PARENT_FIELD,
    }
}

const GITLAB_BLOCKING_FIELD: &str = "blocking";
const GITLAB_BLOCKING_VALUE: &str = "blocks";
const LINEAR_BLOCKING_FIELD: &str = "blocks";
const LINEAR_BLOCKING_VALUE: &str = "blocks";

/// Map one local relationship to its remote representation, or say why not.
///
/// Pure: no adapter, no I/O, no configuration. Both trackers share it, so a future
/// one cannot be added with a divergent contract (T033) — and the representability
/// table lives in exactly one place instead of once per adapter.
#[must_use]
pub fn map_relation_to_remote(
    tool: Tool,
    relation: &crate::relationships::Relationship,
) -> MappedRelation {
    use crate::relationships::RelationKind;
    let (field, value) = match tool {
        Tool::GitLab => (GITLAB_BLOCKING_FIELD, GITLAB_BLOCKING_VALUE),
        Tool::Linear => (LINEAR_BLOCKING_FIELD, LINEAR_BLOCKING_VALUE),
    };
    // The tracker's *model* can express a blocking edge — but the adapter drives a
    // CLI, and no relation verb is verified against either one yet. See
    // `RELATION_WIRE_VERIFIED`.
    let model_supports = matches!(
        relation.kind,
        RelationKind::Blocks | RelationKind::BlockedBy
    );
    if model_supports && RELATION_WIRE_VERIFIED.contains(&tool) {
        return MappedRelation::Remote {
            field: field.to_string(),
            value: format!("{value} #{}", relation.to),
        };
    }
    if model_supports {
        // Expressible in the model, not drivable from the CLI. A *different* claim
        // from "unsupported", and the message says which — a reader who is told
        // "GitLab cannot express this" will not go looking for the verb.
        return MappedRelation::Unsupported(RemoteMappingDiagnostic {
            relation_id: relation.id.clone(),
            field: field.to_string(),
            tool,
            message: format!(
                "`{}` is expressible in {}'s model as `{field}`, but the CLI verb \\
                 that would carry it is not verified, so nothing is sent; the local \\
                 edge is kept",
                relation.kind.as_str(),
                tool.as_str()
            ),
        });
    }
    MappedRelation::Unsupported(RemoteMappingDiagnostic {
        relation_id: relation.id.clone(),
        field: field.to_string(),
        tool,
        message: format!(
            "`{}` is a local-only relation; {} has no field for it, so the local \
             edge is kept and the remote one is not created",
            relation.kind.as_str(),
            tool.as_str()
        ),
    })
}

/// The inverse: read a remote relation back to a local kind and target.
///
/// Symmetric with [`map_relation_to_remote`] by construction — the blocking field
/// maps back to `blocks`, and nothing else maps back at all. A remote payload
/// carrying a field this function does not recognise yields a diagnostic rather
/// than a default, so an import cannot invent a relation the export never made.
#[must_use]
pub fn map_relation_from_remote(
    tool: Tool,
    field: &str,
    value: &str,
    relation_id: &str,
) -> MappedRelation {
    let expected = match tool {
        Tool::GitLab => GITLAB_BLOCKING_FIELD,
        Tool::Linear => LINEAR_BLOCKING_FIELD,
    };
    // Gated the same way as the forward direction: without a verified verb there is
    // no payload this could have received, and coercing one would invent a
    // relationship the export never made.
    if field == expected && RELATION_WIRE_VERIFIED.contains(&tool) {
        // The value this module writes is `"{kind} #{n}"`, so the target is the
        // **last** whitespace-separated token. Taking the first reads the kind word
        // and fails — which is what an earlier version did, and it made the round
        // trip look asymmetric when only the parser was.
        if let Some(target) = value
            .split_whitespace()
            .last()
            .and_then(|t| t.strip_prefix('#'))
            .and_then(|t| t.parse::<u32>().ok())
        {
            // The reverse value is **local**-shaped — the canonical kind spelling
            // and a `#`-prefixed number — not a copy of the remote field name.
            // GitLab's field is `blocking` and Linear's is `blocks`; echoing the
            // field back would make the round trip return different text per
            // tracker for the same relationship, which is the opposite of
            // symmetric.
            return MappedRelation::Remote {
                field: "kind".to_string(),
                value: format!("blocks #{target}"),
            };
        }
        return MappedRelation::Unsupported(RemoteMappingDiagnostic {
            relation_id: relation_id.to_string(),
            field: field.to_string(),
            tool,
            message: format!(
                "`{value}` is not a target issue number, so the remote relation \
                 cannot be read back; no local edge was created"
            ),
        });
    }
    MappedRelation::Unsupported(RemoteMappingDiagnostic {
        relation_id: relation_id.to_string(),
        field: field.to_string(),
        tool,
        message: format!(
            "`{field}` is not a relation field {} writes, so it is ignored; the \
             local relationship set is unchanged",
            tool.as_str()
        ),
    })
}

/// Map a local column to the remote state/label sent to the tracker
/// (`contracts/external-tools.md` mapping table).
///
/// - GitLab: done → `closed`, anything else → `opened`.
/// - Linear: done → `Done`, otherwise the first non-done column label.
#[must_use]
pub fn local_to_remote_status(tool: Tool, local_status: &str, config: &Config) -> String {
    let board = config.default_config();
    match tool {
        Tool::GitLab => {
            if is_done_column(board, local_status, config) {
                "closed".into()
            } else {
                "opened".into()
            }
        }
        Tool::Linear => {
            if is_done_column(board, local_status, config) {
                "Done".into()
            } else {
                first_work_column(board, config).to_string()
            }
        }
    }
}

/// Map a remote state/label back onto a local column. Closed/Done maps to
/// the effective done column; anything else lands in the column whose name
/// matches (case-insensitive), else the first column — per the contract's
/// "whose name matches, else into the first column".
#[must_use]
pub fn remote_to_local_status(tool: Tool, remote_status: &str, config: &Config) -> String {
    let board = config.default_config();
    // WP07 T032: the *service's* completion column, not `done_column`. See
    // `completion_column` for why choosing one local column is this module's business
    // while the meaning of "complete" is not.
    let done = completion_column(board, config);
    match tool {
        Tool::GitLab => {
            if remote_status == "closed" {
                done
            } else {
                board
                    .columns
                    .first()
                    .cloned()
                    .unwrap_or_else(|| "todo".into())
            }
        }
        Tool::Linear => {
            if remote_status == "Done" {
                done
            } else {
                board
                    .columns
                    .iter()
                    .find(|c| c.eq_ignore_ascii_case(remote_status))
                    .cloned()
                    .unwrap_or_else(|| {
                        board
                            .columns
                            .first()
                            .cloned()
                            .unwrap_or_else(|| "todo".into())
                    })
            }
        }
    }
}

/// Whether `local_status` is the board's **completion** column, by the service.
///
/// WP07 T032. This was `board.effective_done_column() == Some(local_status)` — a
/// column-*name* comparison, which is a second local definition of "done" and exactly
/// what C-004 forbids. It agreed with the service on a board with no
/// `category_map` — every existing configuration — and disagreed on precisely the
/// boards this mission exists to support: a board mapping `shipped` to `completed`
/// exports `shipped` as *open* and leaves `done_column` (mapped to `active`) as
/// *closed*.
///
/// `sync/mod.rs` is out of this mission's map; the edit is the completion
/// reconciliation T032 names, and the rationale is recorded here and in
/// `decisions/WP07-verification.md`.
fn is_done_column(board: &BoardConfiguration, local_status: &str, config: &Config) -> bool {
    let resolution =
        crate::workflow::resolution(config, board, crate::workflow::active_board_name(config));
    resolution
        .resolve(local_status)
        .is_some_and(crate::workflow::WorkflowCategory::is_complete)
}

/// The board's completion **column**, chosen by the service rather than by
/// `done_column`.
///
/// The remote trackers have a two-state notion of "closed", so the export path has to
/// pick one local column to send as closed. That is a **remote-translation** concern
/// and belongs here; deciding what "complete" *means* is not, and is the service's.
///
/// Preferring the column the service calls complete means a board whose completion
/// category sits on a column other than `done_column` still round-trips: export
/// closes the column that is genuinely complete, and import brings it back to that
/// same column rather than to `done_column`.
fn completion_column(board: &BoardConfiguration, config: &Config) -> String {
    // WP09: this was a private re-implementation — the same "first complete column,
    // else `done_column`, else `done`" rule the service now owns, duplicated here so
    // that `first_work_column` and `remote_to_local_status` could each have a total
    // `String`. It is the module's own doc comment, written in WP07, that says a
    // second local definition is a C-004 defect, so the duplicate had to go.
    crate::workflow::completion_column_or_default(board, config)
}

/// The first column that is **not** the board's completion column, or the
/// completion column when every column is complete.
///
/// WP09: "not the done column" is a question about **completion**, so it is asked of
/// the service rather than of `done_column`. On a board whose `category_map` puts
/// `completed` on `shipped` while `done_column` is `done`, the old version returned
/// `todo` as the first *work* column when `shipped` is the first column that is
/// genuinely finished — so an export labelled a shipped issue as work in progress.
fn first_work_column<'a>(board: &'a BoardConfiguration, config: &Config) -> &'a str {
    // The lifetime is `board`'s, and the `done` fallback cannot borrow from `config`
    // — so the completion column is compared as a `String` and the fallback is a
    // literal. The alternative, returning `&'a str` from a local, is what forces the
    // old `unwrap_or("done")` to exist at all.
    let done = crate::workflow::completion_column_or_default(board, config);
    board
        .columns
        .iter()
        .find(|c| c.as_str() != done)
        .map_or("done", String::as_str)
}

/// The inverse of `model::civil_from_days` (Howard Hinnant's
/// `days_from_civil`): calendar date → days since the Unix epoch.
#[must_use]
pub fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
    let y = if m <= 2 { y - 1 } else { y };
    let era = if y >= 0 { y } else { y - 399 } / 400;
    let yoe = y - era * 400; // [0, 399]
    let mp = (m + 9) % 12; // [0, 11]
    let doy = i64::from((153 * mp + 2) / 5 + d - 1); // [0, 365]
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096]
    era * 146_097 + doe - 719_468
}

/// Parse `YYYY-MM-DD` into days since the Unix epoch.
#[must_use]
pub fn date_to_epoch_days(ymd: &str) -> Option<i64> {
    let mut parts = ymd.trim().split('-');
    let y: i64 = parts.next()?.parse().ok()?;
    let m: u32 = parts.next()?.parse().ok()?;
    let d: u32 = parts.next()?.parse().ok()?;
    if parts.next().is_some() {
        return None;
    }
    if !(1..=12).contains(&m) || !(1..=31).contains(&d) {
        return None;
    }
    Some(days_from_civil(y, m, d))
}

/// Parse an ISO-8601 remote timestamp into epoch seconds. Accepts
/// `YYYY-MM-DDTHH:MM:SS` (the `T` may be a space) with optional fractional
/// seconds and a `Z` or `±HH:MM` zone.
#[must_use]
pub fn iso_to_epoch_secs(input: &str) -> Option<i64> {
    let (date, time) = input.trim().split_once(['T', ' '])?;
    let days = date_to_epoch_days(date)?;
    let (time, zone) = split_zone(time);
    let mut hms = time.split(':');
    let hh: i64 = hms.next()?.parse().ok()?;
    let mm: i64 = hms.next()?.parse().ok()?;
    let ss_part = hms.next()?;
    let whole: i64 = ss_part.split('.').next()?.parse().ok()?;
    if !(0..=23).contains(&hh) || !(0..=59).contains(&mm) || !(0..=59).contains(&whole) {
        return None;
    }
    let mut secs = days * 86_400 + hh * 3600 + mm * 60 + whole;
    if let Some((zh, zm)) = zone {
        secs -= zh * 3600 + zm * 60;
    }
    Some(secs)
}

/// Split `HH:MM:SS[.frac][zone]` into the bare time and an optional
/// `(hours, minutes)` zone offset (already sign-adjusted).
fn split_zone(time: &str) -> (&str, Option<(i64, i64)>) {
    if time.ends_with('Z') || time.ends_with('z') {
        return (&time[..time.len() - 1], Some((0, 0)));
    }
    match time.rfind(['+', '-']) {
        Some(i) if i > 0 => {
            let (bare, zone) = time.split_at(i);
            let sign = if zone.starts_with('-') { -1i64 } else { 1i64 };
            let digits = &zone[1..];
            let (zh, zm) = if let Some((h, m)) = digits.split_once(':') {
                (h.parse::<i64>().ok(), m.parse::<i64>().ok())
            } else if digits.len() == 2 {
                (digits.parse::<i64>().ok(), Some(0))
            } else if digits.len() >= 3 {
                let (h, m) = digits.split_at(digits.len() - 2);
                (h.parse::<i64>().ok(), m.parse::<i64>().ok())
            } else {
                (None, None)
            };
            match (zh, zm) {
                (Some(zh), Some(zm)) => (bare, Some((sign * zh, sign * zm))),
                _ => (bare, None),
            }
        }
        Some(_) | None => (time, None),
    }
}

/// The conflict rule: the remote wins when its `updated_at` is strictly later
/// than the local issue's `updated` (a `YYYY-MM-DD` interpreted as end of
/// day). A remote timestamp that cannot be parsed counts as *not newer*, so
/// the local issue is kept.
#[must_use]
pub fn is_remote_newer(remote_updated_at: &str, local_updated: &str) -> bool {
    let Some(remote) = iso_to_epoch_secs(remote_updated_at) else {
        return false;
    };
    let local_end_of_day = date_to_epoch_days(local_updated).map_or(0, |d| d * 86_400 + 86_399);
    remote > local_end_of_day
}

/// Redact a resolved secret from text flowing through error/report surfaces.
#[must_use]
pub fn scrub_secret(text: &str, secret: &str) -> String {
    if secret.is_empty() {
        return text.to_string();
    }
    text.replace(secret, "<token>")
}

/// The contract's missing-binary wording (`contracts/external-tools.md`):
/// exit code 3 with `required tool not found: <tool> — install from <source>`.
fn not_found_message(program: &str) -> String {
    match program {
        "glab" => "required tool not found: glab — install from https://gitlab.com/gitlab-org/cli"
            .to_string(),
        _ => format!("required tool not found: {program} — install it and retry"),
    }
}

/// `tix export`: mirror local issues to the remote tracker, recording the
/// remote id back into the local `gitlab_id`/`linear_id` so a re-run updates
/// instead of creating duplicates (idempotency, FR-Remote-sync).
///
/// Returns the number of issues handled (created or updated — `close` on an
/// updated GitLab done issue is not counted separately).
pub fn export(
    store: &Store,
    tool: Tool,
    config: &Config,
    dry_run: bool,
    out: &mut dyn Write,
) -> Result<SyncReport> {
    let mut adapter = adapter_for(tool, config)?;
    let mut report = SyncReport::default();
    // Built **once** for the whole run, which is the service's rule: resolution is
    // not rebuilt per issue. See `workflow::resolution`.
    let resolution = crate::workflow::resolution(config, config.default_config(), "default");

    if dry_run {
        for issue in store.list()? {
            match remote_ref(tool, &issue) {
                Some(r) => {
                    writeln!(out, "would update {tool} issue {r} \"{}\"", issue.title)?;
                }
                None => {
                    writeln!(out, "would create {tool} issue \"{}\"", issue.title)?;
                }
            }
        }
        writeln!(out, "dry run — {tool} CLI was not invoked")?;
        report.handled = store.list()?.len();
        // The dry run reports the same diagnostics a real run would, so
        // "preview then commit" is not the only way to find out that a
        // relationship cannot leave the machine.
        for issue in store.list()? {
            for rel in store.relationships_for(issue.number)? {
                report.note(map_relation_to_remote(tool, &rel), out)?;
            }
            // And the parent, so a dry run surfaces exactly what a real run would.
            if issue.parent.is_some() {
                report.note_parent(map_parent_to_remote(tool, issue.number, issue.parent), out)?;
            }
        }
        return Ok(report);
    }

    let mut handled = 0;
    for mut issue in store.list()? {
        let remote_status = local_to_remote_status(tool, issue.status.display(), config);
        let labels: Vec<String> = issue.labels.clone();
        let assignee = issue.assignee.as_deref();
        let priority = issue.priority.to_string();
        match remote_ref(tool, &issue) {
            Some(r) => {
                let r = r.to_string();
                adapter.update_issue(
                    &r,
                    &issue.title,
                    &issue.body,
                    &labels,
                    assignee,
                    Some(&priority),
                    &remote_status,
                )?;
                if !adapter.done_via_status() && crate::workflow::is_completed(&issue, &resolution)
                {
                    adapter.mark_done(&r)?;
                }
                writeln!(out, "updated {tool} issue {r} \"{}\"", issue.title)?;
            }
            None => {
                let id = adapter.create_issue(
                    &issue.title,
                    &issue.body,
                    &labels,
                    assignee,
                    Some(&priority),
                    &remote_status,
                )?;
                if !adapter.done_via_status() && crate::workflow::is_completed(&issue, &resolution)
                {
                    adapter.mark_done(&id)?;
                }
                match tool {
                    Tool::GitLab => issue.gitlab_id = Some(id.clone()),
                    Tool::Linear => issue.linear_id = Some(id.clone()),
                }
                store.update(&issue.filename, &issue)?;
                writeln!(
                    out,
                    "created {tool} issue {id} \"{}\" (remote id recorded)",
                    issue.title
                )?;
            }
        }
        // The parent reference is offered to the same shared mapper, on the same
        // "after the issue" footing as a relationship: a parent only means
        // something once the parent itself exists remotely. Nothing is sent while
        // `PARENT_WIRE_VERIFIED` is empty, so this reports rather than acts — and
        // the local reference is untouched either way.
        report.note_parent(map_parent_to_remote(tool, issue.number, issue.parent), out)?;

        // Relationships go **after** the issue, because an edge is only meaningful
        // once both endpoints exist remotely. Each is offered to the shared mapper
        // first: what it accepts is sent to the adapter, what it does not becomes a
        // diagnostic naming the field. The adapter never decides representability.
        let remote = match remote_ref(tool, &issue) {
            Some(r) => r.to_string(),
            None => match tool {
                Tool::GitLab => issue.gitlab_id.clone(),
                Tool::Linear => issue.linear_id.clone(),
            }
            .unwrap_or_default(),
        };
        if !remote.is_empty() {
            let mut sendable = Vec::new();
            for rel in store.relationships_for(issue.number)? {
                match map_relation_to_remote(tool, &rel) {
                    MappedRelation::Remote { field, value } => {
                        writeln!(out, "exported {tool} {field} {value} ({})", rel.id)?;
                        sendable.push(MappedRelation::Remote { field, value });
                    }
                    unsupported @ MappedRelation::Unsupported(_) => {
                        report.note(unsupported, out)?
                    }
                }
            }
            adapter.set_relations(&remote, &sendable)?;
        }
        handled += 1;
    }
    report.handled = handled;
    writeln!(
        out,
        "exported {handled} issue(s) to {tool} ({} relationship(s) not representable)",
        report.diagnostics.len()
    )?;
    Ok(report)
}

/// `tix import`: pull open remote issues into local files.
///
/// Conflict resolution: a remote issue that already tracks a local one skips
/// the local file when the local `updated` is later or equal; when the remote
/// `updated_at` is newer the local file is overwritten (fields + body, keeping
/// `created`), with the previous file first copied to `<filename>.bak`.
///
/// `policy` is the explicit triage-entry policy (WP07 T034). It decides **only
/// where a newly created file lands and what the report says about it**: the
/// conflict rules above, remote ids, and adapter behaviour are untouched, and
/// the overwrite path never consults it (T036).
///
/// Returns the number of local files created or overwritten.
pub fn import(
    store: &Store,
    tool: Tool,
    config: &Config,
    out: &mut dyn Write,
    policy: crate::triage::import_policy::ImportPolicy,
) -> Result<SyncReport> {
    let mut adapter = adapter_for(tool, config)?;
    import_with_adapter(store, tool, config, out, policy, adapter.as_mut())
}

/// [`import`] with the adapter injected — the [`CommandRunner`] pattern, so the
/// orchestration under test is the real one and the remote side is a fake that
/// returns canned [`RemoteIssue`]s without spawning a process (WP07 T037).
///
/// `command`s like `tix import` still go through [`import`]; this entry point
/// exists so a test can hold every input of the triage policy in one place —
/// config, policy, and the remote payloads — instead of installing a fake
/// binary on `PATH` and running the compiled CLI to reach it.
pub fn import_with_adapter(
    store: &Store,
    tool: Tool,
    config: &Config,
    out: &mut dyn Write,
    policy: crate::triage::import_policy::ImportPolicy,
    adapter: &mut dyn TrackerAdapter,
) -> Result<SyncReport> {
    // Resolved **before** the loop: a policy this project cannot represent
    // refuses the whole import, not the third item of it.
    let router = crate::triage::import_policy::resolve(config, policy)?;
    let remote_issues = adapter.list_open()?;
    let mut report = SyncReport::default();
    let mut handled = 0;
    // Remote ids imported this run, paired with the local number each one landed
    // on. A parent is named by a **remote** id in the payload, so the reference can
    // only be restored after the parent itself has been created — which is why
    // this is a second pass rather than something set while building each issue.
    let mut imported: Vec<(String, u32)> = Vec::new();
    // `(child remote id, parent remote id)` for every payload that named one.
    let mut claims: Vec<(String, String)> = Vec::new();
    for remote in remote_issues.clone() {
        if let Some(parent) = remote.parent.clone() {
            claims.push((remote.id.clone(), parent));
        }
        let tracked = store
            .list()?
            .into_iter()
            .find(|i| remote_ref(tool, i) == Some(remote.id.as_str()));
        match tracked {
            None => {
                // WP07 T034/T035: the placement decision is made here, once, from
                // the remote state and the configured entry column — before any
                // byte of the file exists. `requested` comes from this module's
                // own mapper rather than being re-derived by the policy, so the
                // two answers can be compared in the report instead of guessed at.
                let requested = remote_to_local_status(tool, &remote.state, config);
                let mapping = router.place(&remote.state, &requested);
                let mut issue = Issue {
                    number: 0,
                    title: remote.title.clone(),
                    status: Status::new(mapping.landed.clone()),
                    labels: remote.labels.clone(),
                    priority: crate::model::Priority::Medium,
                    assignee: remote.assignee.clone(),
                    estimate: None,
                    commit: None,
                    gitlab_id: None,
                    linear_id: None,
                    mission: None,
                    task: None,
                    relationships: vec![],
                    related_issues: vec![],
                    files: vec![],
                    cycles: None,
                    milestones: None,
                    reviewer: None,
                    start_date: None,
                    due_date: None,
                    created: crate::model::today(),
                    type_: None,
                    updated: crate::model::today(),
                    filename: String::new(),
                    body: String::new(),
                    history: crate::model::History::new(),
                    has_retired_links_key: false,
                    parent: None,
                    extra_frontmatter: std::collections::BTreeMap::new(),
                    archived: false,
                    entered_at: None,
                    source: None,
                };
                // T035: entry metadata through the same seam every other entry
                // uses. The queue's age is measured from `entered_at`, so an issue
                // that entered the board through an import has to record that it
                // did — and `import` is the origin data-model §2 documents for it.
                //
                // The **landing column** decides, not `mapping.routed`: `routed` is a
                // policy notion, so under `--triage-policy remote` (or a default whose
                // remote-mapped column happens to be the entry column) an imported
                // issue landed in the inbox with no stamp and the queue reported
                // `unknown` for an issue it was listing. On a project with no
                // `[triage]` section the shared rule stamps nothing, which is the
                // outcome the old guard was reaching for.
                crate::triage::record_entry_if_inbox(config, &mut issue, "import")?;
                match tool {
                    Tool::GitLab => issue.gitlab_id = Some(remote.id.clone()),
                    Tool::Linear => issue.linear_id = Some(remote.id.clone()),
                }
                // WP07 T031: a **column check** on the incoming status, and only
                // that. `remote_to_local_status` already lands on a column the board
                // configures — the service's completion column, or a name match, or
                // the first — so this is the belt to that braces, and it means an
                // import can never create a file in a column the board lacks. The
                // create path performs the same check (WP05), so this is belt *and*
                // braces for the remote-sourced case.
                //
                // Not a transition evaluation: a new issue is not leaving anywhere, so
                // the terminal lock has nothing to say. Importing an issue directly
                // into a terminal column is legitimate.
                let (_, resolution) = crate::workflow::active_resolution(config);
                if resolution.resolve(issue.status.display()).is_none() {
                    // Reported, not written. A skipped item is visible and the rest of
                    // the batch still lands.
                    writeln!(
                        out,
                        "skipped {tool} issue {} \"{}\": `{}` is not a column on board `{}`",
                        remote.id, remote.title, issue.status, resolution.board
                    )?;
                    report.skipped += 1;
                    continue;
                }
                let path = store.create(&mut issue, &remote.description, None)?;
                imported.push((remote.id.clone(), issue.number));
                let name = path
                    .file_name()
                    .map(|n| n.to_string_lossy().to_string())
                    .unwrap_or_default();
                // T035: the mapping is named in the same line that names the file,
                // and `report_clause` is empty exactly when the default policy
                // decided nothing — so a legacy project's report is byte-identical
                // to what it was, and a project that routed says where the remote
                // state asked for and where the issue landed.
                let clause = mapping.report_clause();
                writeln!(
                    out,
                    "imported {tool} issue {} \"{}\" as #{} ({}) [{name}]{clause}",
                    remote.id, remote.title, issue.number, issue.status
                )?;
                handled += 1;
            }
            Some(local) => {
                if is_remote_newer(remote.updated_at.as_deref().unwrap_or(""), &local.updated) {
                    let backup = format!("{}.bak", local.filename);
                    std::fs::copy(
                        store.issues_dir.join(&local.filename),
                        store.issues_dir.join(&backup),
                    )?;
                    // Captured before `local` is moved into `overwritten`: the
                    // skip path restores the local status, and reading it back off
                    // `overwritten` after the assignment would restore the status the
                    // *incoming* value was about to overwrite.
                    let local_status = local.status.clone();
                    let mut overwritten = local;
                    let keep_created = overwritten.created.clone();
                    overwritten.title = remote.title.clone();
                    overwritten.body = remote.description.clone();
                    overwritten.labels = remote.labels.clone();
                    let incoming = Status::new(remote_to_local_status(tool, &remote.state, config));
                    // WP07 T031: validate the incoming status as a **transition**,
                    // because this *is* one — an existing issue moving columns.
                    //
                    // **Skip-and-report**, which is the disposition the design settles
                    // (T031 step 3). The alternative, apply-and-report, would make a
                    // board's policy non-binding for the one path nobody watches, and
                    // a remote whose states the board forbids would quietly win.
                    // Skipping keeps the local file truthful and puts the conflict in
                    // the report where a human will see it. Recorded here rather than
                    // in `data-model.md` §8, which is a protected path for this lane.
                    let (_, resolution) = crate::workflow::active_resolution(config);
                    let transition = crate::workflow::validate_transition(
                        &overwritten,
                        incoming.display(),
                        &resolution,
                        config,
                        None,
                    );
                    if let crate::workflow::TransitionOutcome::Rejected(diagnostic) = transition {
                        // The status is left alone; the other fields still import,
                        // because they are not what the policy governs. The file is
                        // rewritten, so this is a **partial** import — reported as such
                        // rather than as a plain overwrite.
                        overwritten.status = local_status.clone();
                        overwritten.title = remote.title.clone();
                        overwritten.body = remote.description.clone();
                        overwritten.labels = remote.labels.clone();
                        if let Some(a) = &remote.assignee {
                            overwritten.assignee = Some(a.clone());
                        }
                        overwritten.created = keep_created;
                        overwritten.bump_updated();
                        let filename = overwritten.filename.clone();
                        store.update(&filename, &overwritten)?;
                        writeln!(
                            out,
                            "overwrote {tool} issue {} \"{}\" without its status: {diagnostic} \
                             (kept {})",
                            remote.id, overwritten.title, overwritten.status
                        )?;
                        report.skipped += 1;
                        handled += 1;
                        continue;
                    }
                    overwritten.status = incoming;
                    if let Some(a) = &remote.assignee {
                        overwritten.assignee = Some(a.clone());
                    }
                    overwritten.created = keep_created;
                    overwritten.bump_updated();
                    let filename = overwritten.filename.clone();

                    // An import that moves a locally-blocked issue into the
                    // board's completion column goes through the same blocked-move
                    // policy as every other surface -- WP04 T016 step 6 names
                    // "any bulk or import path" explicitly, and an import that
                    // can end an issue in the completion column with open
                    // blockers is the sharpest form of that.
                    //
                    // It **records** the acknowledgement rather than refusing, and
                    // the asymmetry is deliberate. There is no interactive
                    // confirmation available mid-import, and refusing would make
                    // `tix import` unusable whenever one issue in a batch carries
                    // a stale blocker -- turning a stale local edge into a
                    // permanently un-syncable board. The user ran the import;
                    // that is the decision, and the event exists to preserve it.
                    // Where a human is present to answer, refusing is right
                    // (`tix move`, `tix edit --status`, `move_issue`); here the
                    // honest record is that the import did it.
                    let guard = crate::commands::mv::blocked_move_guard(
                        config,
                        store,
                        &overwritten,
                        overwritten.status.display(),
                    )?;
                    if let Some(warning) = guard.warning() {
                        overwritten.history.append_now(
                            &crate::storage::actor_identity(),
                            crate::model::HistoryEventKind::BlockedMoveAcknowledged,
                            &format!("imported to {}: {warning}", overwritten.status.display()),
                        );
                    }
                    store.update(&filename, &overwritten)?;
                    writeln!(
                        out,
                        "overwrote {tool} issue {} \"{}\" (remote newer; backup at {backup})",
                        remote.id, overwritten.title
                    )?;
                    handled += 1;
                } else {
                    writeln!(
                        out,
                        "kept {tool} issue {} \"{}\" (local updated later or equal)",
                        remote.id, remote.title
                    )?;
                }
            }
        }
    }
    restore_imported_parents(store, tool, &claims, &imported, &mut report, out)?;
    writeln!(out, "imported {handled} {tool} issue(s)")?;
    report.handled = handled;
    Ok(report)
}

/// Restore the parent references an import's payload reported.
///
/// A **second pass**, because a payload names a parent by *remote* id and the
/// parent may well be imported after its child. Setting the field while building
/// each issue would therefore succeed or fail depending on the order the remote
/// happened to return, which is the order-dependence NFR-003 forbids.
///
/// Every write goes through [`crate::hierarchy::set_parent`] rather than a field
/// assignment, so an imported reference obeys the same rules as a CLI write: it is
/// validated before anything is written, and a refusal leaves the file
/// byte-identical. T032's note is explicit — "an import that would create a cycle
/// is a defect, not a special case" — and the service is what decides that, not
/// this loop.
///
/// `claims` is `(child remote id, parent remote id)` and `imported` is
/// `(remote id, local number)`. A pair where either side does not resolve becomes a
/// diagnostic rather than a write: a reference to an issue this run did not import
/// is exactly the unresolved-parent state WP05 added a finding for, and
/// manufacturing it here would be this loop's own defect.
fn restore_imported_parents(
    store: &Store,
    tool: Tool,
    claims: &[(String, String)],
    imported: &[(String, u32)],
    report: &mut SyncReport,
    out: &mut dyn Write,
) -> Result<()> {
    for (child_remote, parent_remote) in claims {
        let child = imported
            .iter()
            .find(|(id, _)| id == child_remote)
            .map(|(_, number)| *number);
        let parent = imported
            .iter()
            .find(|(id, _)| id == parent_remote)
            .map(|(_, number)| *number);
        let (Some(child), Some(parent)) = (child, parent) else {
            report.note_parent(
                MappedParent::Unsupported(RemoteMappingDiagnostic {
                    relation_id: format!("{child_remote}->{parent_remote}"),
                    field: parent_field(tool).to_string(),
                    tool,
                    message: format!(
                        "remote issue {child_remote} reports parent {parent_remote}, \
                         which this import did not create — it may be closed, \
                         filtered out, or in another project; no local reference is \
                         written, so the issue stays parentless rather than \
                         unresolved"
                    ),
                }),
                out,
            )?;
            continue;
        };
        // Through `Store::set_parent`, which resolves, validates with the
        // hierarchy service, writes, and records the one History entry — the
        // same path `tix edit --parent` takes, so an imported reference is
        // indistinguishable from a typed one. A refusal is reported and nothing is
        // written.
        let (child_sel, parent_sel) = (child.to_string(), parent.to_string());
        match store.set_parent(&child_sel, &parent_sel) {
            Ok(_) => writeln!(out, "restored parent of {tool} issue #{child} to #{parent}")?,
            Err(e) => {
                writeln!(
                    out,
                    "could not restore the parent of {tool} issue #{child}: {e}; the \
                     reference was not written"
                )?;
                report.diagnostics.push(RemoteMappingDiagnostic {
                    relation_id: format!("{child}->{parent}"),
                    field: parent_field(tool).to_string(),
                    tool,
                    message: format!(
                        "the remote reports #{child} under #{parent}, but the hierarchy \
                         service refused it: {e}"
                    ),
                });
            }
        }
    }
    Ok(())
}

/// Whether a computed **remote** status conveys "done" in that tracker's own
/// vocabulary.
///
/// Deliberately **not** the completion decision. `closed` is GitLab's word and
/// `Done` is Linear's; neither is a local column name, so this cannot be a
/// category question, and routing it through the service would mean asking the
/// service about a string from a different vocabulary.
///
/// It used to decide *local* completion at the export call sites, by mapping the
/// local status out to a remote string and testing that — a round trip that can
/// disagree with the category rule on any board with a category_map. Those call
/// sites now ask \`workflow::is_completed\` about the local issue (C-004), and this
/// function keeps only the narrower job it can actually do: telling an adapter
/// whether its own status update already closed the remote issue.
fn remote_ref(tool: Tool, issue: &Issue) -> Option<&str> {
    match tool {
        Tool::GitLab => issue.gitlab_id.as_deref(),
        Tool::Linear => issue.linear_id.as_deref(),
    }
}

/// Build and configure the adapter for `tool`: resolves the token with env
/// precedence, validates the `[export]` target section, and returns the
/// tool-specific adapter wired to a [`ProcessRunner`].
fn adapter_for(tool: Tool, config: &Config) -> Result<Box<dyn TrackerAdapter>> {
    // The contract's warning starts with "warning:" — no `tix:` prefix.
    let mut warn = |w: &str| eprintln!("{w}");
    let resolution = token::resolve(tool, config, &token::RealEnv, &mut warn);
    let secret = resolution.secret().map(str::to_string);
    match tool {
        Tool::GitLab => {
            let rc = config.export.gitlab.as_ref().ok_or_else(|| {
                TixError::Config("no `[export.gitlab]` section in tix.toml — run `tix init --with gitlab` or edit tix.toml".to_string())
            })?;
            let project = rc.project.clone().ok_or_else(|| {
                TixError::Config("`[export.gitlab].project` is not set — add `project = \"acme/tix\"` to tix.toml".to_string())
            })?;
            Ok(Box::new(glab::GitLabAdapter::new(
                ProcessRunner,
                secret,
                rc.base_url.clone(),
                project,
            )))
        }
        Tool::Linear => {
            let rc = config.export.linear.as_ref().ok_or_else(|| {
                TixError::Config("no `[export.linear]` section in tix.toml — run `tix init --with linear` or edit tix.toml".to_string())
            })?;
            let team = rc.team.clone().ok_or_else(|| {
                TixError::Config(
                    "`[export.linear].team` is not set — add `team = \"Eng\"` to tix.toml"
                        .to_string(),
                )
            })?;
            Ok(Box::new(linear::LinearAdapter::new(
                ProcessRunner,
                secret,
                team,
            )))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn target_parsing_accepts_only_the_two_contract_targets() {
        assert_eq!(Tool::from_target("gitlab").unwrap(), Tool::GitLab);
        assert_eq!(Tool::from_target("linear").unwrap(), Tool::Linear);
        assert!(Tool::from_target("github").is_err());
        assert_eq!(Tool::GitLab.token_var(), "GITLAB_TOKEN");
        assert_eq!(Tool::Linear.token_var(), "LINEAR_TOKEN");
        assert_eq!(Tool::GitLab.binary(), "glab");
        assert_eq!(Tool::Linear.binary(), "linear-cli");
    }

    #[test]
    fn gitlab_status_mapping() {
        let config = Config::default();
        assert_eq!(
            local_to_remote_status(Tool::GitLab, "todo", &config),
            "opened"
        );
        assert_eq!(
            local_to_remote_status(Tool::GitLab, "done", &config),
            "closed"
        );
        assert_eq!(
            remote_to_local_status(Tool::GitLab, "opened", &config),
            "todo"
        );
        assert_eq!(
            remote_to_local_status(Tool::GitLab, "closed", &config),
            "done"
        );
        assert_eq!(
            remote_to_local_status(Tool::GitLab, "anything-else", &config),
            "todo"
        );
    }

    #[test]
    fn linear_status_mapping() {
        let config = Config::default();
        assert_eq!(
            local_to_remote_status(Tool::Linear, "todo", &config),
            "todo"
        );
        assert_eq!(
            local_to_remote_status(Tool::Linear, "in review", &config),
            "todo"
        );
        assert_eq!(
            local_to_remote_status(Tool::Linear, "done", &config),
            "Done"
        );
        assert_eq!(
            remote_to_local_status(Tool::Linear, "In Progress", &config),
            "in progress"
        );
        assert_eq!(
            remote_to_local_status(Tool::Linear, "Done", &config),
            "done"
        );
        assert_eq!(
            remote_to_local_status(Tool::Linear, "Unknown", &config),
            "todo"
        );
    }

    #[test]
    fn days_from_civil_roundtrips_civil_from_days() {
        // spot-check independent epoch anchors (known values)
        assert_eq!(days_from_civil(1970, 1, 1), 0);
        assert_eq!(days_from_civil(2000, 1, 1), 10957);
        assert_eq!(days_from_civil(1970, 1, 2), 1);
        assert_eq!(days_from_civil(2026, 5, 11), 20584);
    }

    #[test]
    fn date_to_epoch_days_parses_only_yyyymmdd() {
        assert_eq!(date_to_epoch_days("1970-01-01"), Some(0));
        assert_eq!(date_to_epoch_days("2026-05-11"), Some(20_584));
        assert_eq!(date_to_epoch_days("not-a-date"), None);
        assert_eq!(date_to_epoch_days("2026-13-01"), None);
        assert_eq!(date_to_epoch_days("2026-05-11T10:00:00"), None);
    }

    #[test]
    fn iso_to_epoch_secs_accepts_contract_timestamp_shapes() {
        let day = days_from_civil(2026, 5, 11) * 86_400;
        assert_eq!(iso_to_epoch_secs("2026-05-11T00:00:00Z"), Some(day));
        assert_eq!(iso_to_epoch_secs("2026-05-11 00:00:00"), Some(day));
        assert_eq!(iso_to_epoch_secs("2026-05-11T00:00:00.123Z"), Some(day));
        assert_eq!(
            iso_to_epoch_secs("2026-05-11T00:00:00+02:00"),
            Some(day - 7200)
        );
        assert_eq!(
            iso_to_epoch_secs("2026-05-11T00:00:00-05:30"),
            Some(day + 19_800)
        );
        assert_eq!(
            iso_to_epoch_secs("2026-05-11T10:30:00Z"),
            Some(day + 37_800)
        );
        assert_eq!(iso_to_epoch_secs("garbage"), None);
    }

    #[test]
    fn remote_newer_wins_only_when_strictly_after_local_end_of_day() {
        // local `updated` = 2026-05-11 is interpreted as end of day.
        assert!(is_remote_newer("2026-05-12T00:00:00Z", "2026-05-11"));
        assert!(!is_remote_newer("2026-05-11 13:00:00", "2026-05-11"));
        assert!(!is_remote_newer("2026-05-11T23:59:59Z", "2026-05-11"));
        assert!(!is_remote_newer("2026-05-10T23:59:59Z", "2026-05-11"));
        // unparseable remote timestamp keeps the local issue
        assert!(!is_remote_newer("not-a-time", "2026-05-11"));
    }

    #[test]
    fn scrub_replaces_secret_everywhere_and_preserves_text() {
        assert_eq!(
            scrub_secret("token=sekrit end", "sekrit"),
            "token=<token> end"
        );
        assert_eq!(
            scrub_secret("token=sekrit token=sekrit", "sekrit"),
            "token=<token> token=<token>"
        );
        assert_eq!(scrub_secret("no secret here", "sekrit"), "no secret here");
        assert_eq!(scrub_secret("empty secret", ""), "empty secret");
    }

    // ---- WP07 T029: the relationship mapping seam ----

    fn rel(kind: crate::relationships::RelationKind) -> crate::relationships::Relationship {
        let mut r = crate::relationships::Relationship::new(1, 2, kind, "Ship it");
        r.id = "rel_TEST".to_string();
        r
    }

    /// Every relationship diagnoses today, and the diagnostic distinguishes the two
    /// reasons (T029 step 5).
    ///
    /// Both trackers' *models* can express a blocking edge; neither *CLI* verb is
    /// verified, so nothing is sent. The two reasons are different claims and the
    /// message says which, because a reader told "GitLab cannot express this" will
    /// not go looking for the verb:
    ///
    /// - `blocks`/`blocked_by` — expressible in the model, no verified CLI verb
    /// - `related`/`duplicates` — no remote field at all
    ///
    /// Written so it still holds once a tool joins `RELATION_WIRE_VERIFIED`: the
    /// `blocks` case then takes the mapped branch instead.
    #[test]
    fn every_relationship_diagnoses_with_its_field_its_tool_and_its_reason() {
        for tool in [Tool::GitLab, Tool::Linear] {
            for kind in [
                crate::relationships::RelationKind::Blocks,
                crate::relationships::RelationKind::BlockedBy,
                crate::relationships::RelationKind::Related,
                crate::relationships::RelationKind::Duplicates,
            ] {
                let model_supports = matches!(
                    kind,
                    crate::relationships::RelationKind::Blocks
                        | crate::relationships::RelationKind::BlockedBy
                );
                match map_relation_to_remote(tool, &rel(kind)) {
                    MappedRelation::Remote { field, value } => {
                        assert!(
                            !RELATION_WIRE_VERIFIED.contains(&tool),
                            "{tool}/{kind} mapped, so the wire must be verified"
                        );
                        assert!(!field.is_empty() && value.contains('#'));
                    }
                    MappedRelation::Unsupported(d) => {
                        assert_eq!(d.tool, tool, "the diagnostic names the tool");
                        assert_eq!(d.relation_id, "rel_TEST");
                        assert!(
                            !d.field.is_empty(),
                            "the diagnostic must name the specific field: {d}"
                        );
                        assert!(d.to_string().contains(&d.field), "and print it: {d}");
                        if model_supports {
                            assert!(
                                d.message.contains("not verified"),
                                "{tool}/{kind}: a model-supported kind must say the \
                                 verb is unverified, not that the model lacks it: {d}"
                            );
                        } else {
                            assert!(
                                !d.message.contains("not verified"),
                                "{tool}/{kind}: a kind with no remote field must not \
                                 blame an unverified verb: {d}"
                            );
                        }
                    }
                }
            }
        }
    }

    /// The forward and reverse directions agree about the verified list.
    ///
    /// Symmetry used to be asserted as a round trip, which cannot run while the list
    /// is empty. What matters while it is empty is that the reverse direction does
    /// **not** invent an edge from a payload the forward direction would never have
    /// written — otherwise an import could create a relationship the export never
    /// made, which is the mirror image of the silent drop the contract forbids.
    #[test]
    fn neither_direction_maps_without_a_verified_verb() {
        for tool in [Tool::GitLab, Tool::Linear] {
            let field = match tool {
                Tool::GitLab => "blocking",
                Tool::Linear => "blocks",
            };
            match map_relation_from_remote(tool, field, "blocks #2", "rel_TEST") {
                MappedRelation::Remote { .. } => assert!(
                    !RELATION_WIRE_VERIFIED.contains(&tool),
                    "{tool}: the reverse direction mapped, so the wire must be verified"
                ),
                MappedRelation::Unsupported(d) => {
                    assert_eq!(d.tool, tool);
                    assert!(!d.relation_id.is_empty());
                }
            }
        }
    }

    /// A remote payload the export could not have written is **ignored with a
    /// diagnostic**, never turned into a local edge.
    ///
    /// The alternative — coercing an unrecognised field to a default kind — would
    /// let an import invent a relationship the export never made, which is the
    /// mirror image of silently dropping a local one.
    #[test]
    fn an_unrecognised_remote_relation_field_never_becomes_a_local_edge() {
        for tool in [Tool::GitLab, Tool::Linear] {
            for (field, value) in [
                ("parent", "#2"),
                ("blocks", "not-a-number"),
                ("whatever", ""),
            ] {
                match map_relation_from_remote(tool, field, value, "rel_X") {
                    MappedRelation::Remote { .. } => {
                        panic!("{tool}: `{field}={value}` must not become a local edge")
                    }
                    MappedRelation::Unsupported(d) => {
                        assert_eq!(d.tool, tool);
                        assert_eq!(d.field, field, "the diagnostic names the field");
                    }
                }
            }
        }
    }

    /// The two adapters cannot drift: the seam is one function, keyed on `Tool`
    /// (T033 step 5, and T029's note).
    ///
    /// Asserted by construction — a single `map_relation_to_remote` serves both —
    /// and pinned here so adding a tracker-specific branch to one of them is a
    /// red test rather than a silent divergence.
    #[test]
    fn both_trackers_share_one_mapping_seam() {
        let source = include_str!("mod.rs");
        let fns = [
            "pub fn map_relation_to_remote",
            "pub fn map_relation_from_remote",
        ];
        for f in fns {
            assert_eq!(
                source.matches(&format!("{f}(")).count(),
                1,
                "{f} must be *defined* exactly once, in this module, for both \
                 trackers — a doc comment naming it is not a second implementation"
            );
        }
        // And neither adapter file may define its own copy. `include_str!` needs a
        // literal, so the pair is spelled out rather than looped over.
        for (name, text) in [
            ("glab.rs", include_str!("glab.rs")),
            ("linear.rs", include_str!("linear.rs")),
        ] {
            assert!(
                !text.contains("fn map_relation_to_remote")
                    && !text.contains("fn map_relation_from_remote"),
                "{name} must not define its own mapping seam; the shared one is \\
                 keyed on `Tool` precisely so the two cannot diverge"
            );
        }
    }

    /// A `SyncReport` records the count and the diagnostics together, so a caller
    /// cannot report success while quietly dropping a relationship.
    #[test]
    fn a_sync_report_carries_both_the_count_and_the_diagnostics() {
        let mut report = SyncReport::default();
        let mut sink: Vec<u8> = Vec::new();
        report
            .note(
                map_relation_to_remote(
                    Tool::GitLab,
                    &rel(crate::relationships::RelationKind::Related),
                ),
                &mut sink,
            )
            .unwrap();
        report
            .note(
                map_relation_to_remote(
                    Tool::GitLab,
                    &rel(crate::relationships::RelationKind::Blocks),
                ),
                &mut sink,
            )
            .unwrap();
        // Both are diagnostics today: nothing is wire-verified, so the mapped
        // branch is not reachable and the count cannot be 1.
        let expected = if RELATION_WIRE_VERIFIED.contains(&Tool::GitLab) {
            1
        } else {
            2
        };
        assert_eq!(
            report.diagnostics.len(),
            expected,
            "the report records every relation the tool cannot carry"
        );
        assert_eq!(report.handled, 0, "no issues were handled here");
        // It is on the human stream too, so the count and the output agree.
        let text = String::from_utf8(sink).unwrap();
        assert!(
            text.contains("cannot represent"),
            "the stream says so: {text}"
        );
    }
    // ---- WP07 T032/T033: completion comes from the service, nowhere else ----

    /// A board whose `category_map` puts `completed` on `shipped` while
    /// `done_column` is `done` — so the two disagree, and a name comparison picks the
    /// wrong one. Every assertion below is vacuous on the default board, which is why
    /// this fixture exists rather than `Config::default()`.
    fn split_completion_config() -> Config {
        Config {
            kanban: crate::config::KanbanSection {
                configurations: indexmap::IndexMap::from([(
                    "default".to_string(),
                    crate::config::BoardConfiguration {
                        columns: vec!["todo".into(), "shipped".into(), "done".into()],
                        done_column: Some("done".to_string()),
                        category_map: indexmap::IndexMap::from([
                            ("todo".to_string(), "unstarted".to_string()),
                            ("shipped".to_string(), "completed".to_string()),
                            ("done".to_string(), "active".to_string()),
                        ]),
                        ..Default::default()
                    },
                )]),
            },
            ..Config::default()
        }
    }

    #[test]
    fn t032_a_remote_closed_state_maps_to_the_services_completion_column() {
        // Not to `done_column`. The remote's `closed` must round-trip to the column
        // the *service* calls complete, or export and import disagree with each other
        // and with the board.
        let config = split_completion_config();
        assert_eq!(
            remote_to_local_status(Tool::GitLab, "closed", &config),
            "shipped",
            "a closed GitLab issue belongs in the column that is actually complete"
        );
        assert_eq!(
            remote_to_local_status(Tool::Linear, "Done", &config),
            "shipped"
        );
    }

    #[test]
    fn t032_export_closes_the_column_the_service_calls_complete() {
        // The other direction. A name comparison exported `shipped` as *open* and
        // closed `done` instead — the tracker and the board disagreeing about the same
        // issue in both directions at once.
        let config = split_completion_config();
        assert_eq!(
            local_to_remote_status(Tool::GitLab, "shipped", &config),
            "closed"
        );
        assert_eq!(
            local_to_remote_status(Tool::GitLab, "done", &config),
            "opened"
        );
        assert_eq!(
            local_to_remote_status(Tool::Linear, "shipped", &config),
            "Done"
        );
    }

    #[test]
    fn t032_a_closed_remote_state_mapped_to_a_canceled_column_is_not_complete() {
        // T033 step 4. `canceled` is terminal but **not** complete (contract §4), so
        // an export that sends a `canceled` column as closed would be claiming the
        // work is finished when it was abandoned. The local side is the service's
        // answer, so it says no.
        let mut config = split_completion_config();
        config
            .kanban
            .configurations
            .get_mut("default")
            .unwrap()
            .category_map
            .insert("done".to_string(), "canceled".to_string());
        let board = config.default_config();
        // `shipped` is still `completed`, so it still exports as closed…
        assert_eq!(
            local_to_remote_status(Tool::GitLab, "shipped", &config),
            "closed"
        );
        // …and `done` is now `canceled`, which is terminal and not complete, so it does
        // not. The remote has only two states, so the honest outcome is that `canceled`
        // cannot be represented distinctly — and the local definition is what decides,
        // not the remote's vocabulary.
        assert!(
            !is_done_column(board, "done", &config),
            "a canceled column is not locally complete"
        );
    }

    #[test]
    fn t032_the_existing_round_trips_are_unchanged() {
        // T032 step 5: this is a refactor of *where the decision comes from*, not a
        // protocol change. The default board's behaviour must be identical.
        let config = Config::default();
        assert_eq!(
            local_to_remote_status(Tool::GitLab, "done", &config),
            "closed"
        );
        assert_eq!(
            local_to_remote_status(Tool::GitLab, "todo", &config),
            "opened"
        );
        assert_eq!(
            remote_to_local_status(Tool::GitLab, "closed", &config),
            "done"
        );
        assert_eq!(
            remote_to_local_status(Tool::Linear, "Done", &config),
            "done"
        );
        // "In Progress" case-insensitively matches the board's `in progress` column,
        // and a name match wins over the first column. The first draft of this
        // assertion expected `todo` — which is the *first* column, and therefore the
        // answer when no name matches. It was asserting the opposite rule to the one
        // it claimed to pin.
        assert_eq!(
            remote_to_local_status(Tool::Linear, "In Progress", &config),
            "in progress",
            "a name match wins over the first column"
        );
        assert_eq!(
            remote_to_local_status(Tool::Linear, "No Such State", &config),
            "todo",
            "and with no match at all, the first column"
        );
    }

    #[test]
    fn t032_the_sync_seam_holds_no_local_completion_definition() {
        // T032 step 4, as a structural guard. The module header says a second local
        // definition is a C-004 defect, and this is what keeps that from being
        // "improved" back in: the seam may only *translate* a remote state word, and
        // the completion test may only come from the service.
        let source = include_str!("mod.rs");
        // Assembled from fragments so this assertion does not match **itself**: the
        // first version spelled the forbidden name out in full, so the very line
        // asserting its absence satisfied the check. That is the grep equivalent of a
        // test that proves itself, and it was found because the test went red while
        // the function was, in fact, absent.
        let forbidden = ["fn remote", "status_is_done"].concat();
        assert!(
            !source.contains(&forbidden),
            "the dead second definition is removed and must not come back"
        );
        // The only local completion question in the module is the service call.
        let uses_service = source.matches("WorkflowCategory::is_complete").count();
        assert!(
            uses_service >= 2,
            "both `is_done_column` and `completion_column` must ask the service, found \\
             {uses_service} uses"
        );
    }
}