btctax-cli 0.13.0

btctax — an offline, single-user US Bitcoin tax ledger (CLI: import, reconcile, and compute).
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
//! Conservative-filing Task 8 (CLI wiring) — the VOID-direction BG-D9 prior-year fold-diff advisory
//! reaches the real `btctax reconcile void` verb. Voiding a live `PromoteTranche` reverts a filed floor
//! basis toward `$0`, which HIFO-reorders a PRIOR filed year's disposals (amend-to-PAY). This drives the
//! actual binary (`std::process::Command`) so the wiring — not just the core builder — is exercised: the
//! `Direction::Void` lines must PRINT before the void is recorded.
//!
//! Setup is hand-built via `persistence` (there is no CLI `promote` verb yet — that consent screen is
//! Task 10 — so the promote is appended directly, exactly as `declare_tranche_cli.rs` hand-crafts a raw
//! void). PRIVACY: synthetic values in a tempdir; no user file is read.

use btctax_cli::cli::FormArg;
use btctax_cli::cmd::promote::ProvenanceKind;
use btctax_cli::eventref::parse_event_id;
use btctax_cli::{cmd, return_inputs, CliError, Session, PROMOTE_ACK_PHRASE};
use btctax_core::conservative::{flagged_years, Coverage};
use btctax_core::event::{
    Acknowledgment, Acquire, BasisSource, ConsentTerm, DeclareTranche, Dispose, DisposeKind,
    EventPayload, FloorMethod, OutflowClass, PromoteTranche, TransferOut,
};
use btctax_core::identity::{EventId, Source, SourceRef, WalletId};
use btctax_core::persistence::{append_decision, append_import_batch, load_all};
use btctax_core::LedgerEvent;
use btctax_store::Passphrase;
use rust_decimal_macros::dec;
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use time::macros::{date, datetime};
use time::UtcOffset;

fn pp() -> Passphrase {
    Passphrase::new("pw".into())
}
fn now() -> time::OffsetDateTime {
    datetime!(2026 - 01 - 01 0:00 UTC)
}
/// The single Exchange wallet the documented buy, the tranche, and the sell all share — so a promoted
/// tranche can HIFO-reorder the sell's draw.
fn wallet() -> WalletId {
    WalletId::Exchange {
        provider: "coinbase".into(),
        account: "main".into(),
    }
}
fn imp(rf: &str, ts: time::OffsetDateTime, payload: EventPayload) -> LedgerEvent {
    LedgerEvent {
        id: EventId::import(Source::Coinbase, SourceRef::new(rf)),
        utc_timestamp: ts,
        original_tz: UtcOffset::UTC,
        wallet: Some(wallet()),
        payload,
    }
}

/// A vault with a documented 0.6-BTC lot ($5,000/BTC), a 0.4-BTC tranche PROMOTED to a $12,000 floor
/// ($30,000/BTC — higher per-sat, so HIFO draws it FIRST), and a 2018 sell of EXACTLY 0.4 BTC. WITH the
/// promote the sell drains the tranche (gain $8,000); voiding it reverts the tranche to $0 (sorted LAST),
/// so the sell instead drains the documented lot (gain $18,000) — the amend-to-PAY reorder the advisory
/// warns about. Returns (vault, promote decision id).
fn build_promoted_vault(dir: &Path) -> (PathBuf, EventId) {
    let vault = dir.join("vault.pgp");
    let mut s = Session::create(&vault, &pp()).unwrap();
    let buy = imp(
        "BUY",
        datetime!(2017-01-01 00:00 UTC),
        EventPayload::Acquire(Acquire {
            sat: 60_000_000,
            usd_cost: dec!(3_000),
            fee_usd: dec!(0),
            basis_source: BasisSource::ExchangeProvided,
        }),
    );
    let sell = imp(
        "SELL",
        datetime!(2018-09-01 00:00 UTC),
        EventPayload::Dispose(Dispose {
            sat: 40_000_000,
            usd_proceeds: dec!(20_000),
            fee_usd: dec!(0),
            kind: DisposeKind::Sell,
        }),
    );
    append_import_batch(s.conn(), &[buy, sell]).unwrap();

    // DeclareTranche (decision 1) then PromoteTranche targeting it (decision 2).
    let tranche_id = append_decision(
        s.conn(),
        EventPayload::DeclareTranche(DeclareTranche {
            sat: 40_000_000,
            wallet: wallet(),
            window_start: time::macros::date!(2018 - 01 - 01),
            window_end: time::macros::date!(2018 - 03 - 31),
        }),
        now(),
        UtcOffset::UTC,
        None,
    )
    .unwrap();
    let promote_id = append_decision(
        s.conn(),
        EventPayload::PromoteTranche(PromoteTranche {
            target: tranche_id,
            method: FloorMethod::WindowLowClose,
            filed_basis: dec!(12_000),
            coverage: Coverage::Full,
            provenance_attested: true,
            acknowledgment: Acknowledgment {
                phrase: "I understand and accept the risk".into(),
                shown_terms: vec![],
                provenance_text: "acquired by purchase within the declared window".into(),
                provenance_version: "v1".into(),
            },
            part_ii_narrative: "cash P2P purchase, no records; window bounded on-chain".into(),
        }),
        now(),
        UtcOffset::UTC,
        None,
    )
    .unwrap();
    s.save().unwrap();
    (vault, promote_id)
}

/// Run `btctax --vault <vault> reconcile void <target>`; returns (exit, stdout, stderr).
fn run_void(vault: &Path, target: &str) -> (i32, String, String) {
    let bin = env!("CARGO_BIN_EXE_btctax");
    let out = std::process::Command::new(bin)
        .arg("--vault")
        .arg(vault.to_str().unwrap())
        .arg("reconcile")
        .arg("void")
        .arg(target)
        .env("BTCTAX_PASSPHRASE", "pw")
        .output()
        .expect("btctax binary must execute");
    (
        out.status.code().expect("exits normally"),
        String::from_utf8_lossy(&out.stdout).into_owned(),
        String::from_utf8_lossy(&out.stderr).into_owned(),
    )
}

fn decision_count(vault: &Path) -> usize {
    let s = Session::open(vault, &pp()).unwrap();
    load_all(s.conn())
        .unwrap()
        .iter()
        .filter(|e| matches!(e.id, EventId::Decision { .. }))
        .count()
}

/// ★ Task 8 (§6 / arch r1 I-3): `reconcile void` on a live promote PRINTS the `Direction::Void`
/// prior-year advisory (amend-to-PAY) before recording, and still records the void. Dropping the wiring
/// leaves stdout without the 1040-X / additional-tax warning (surfacing mutation).
#[test]
fn voiding_a_promoted_tranche_prints_the_void_direction_advisory() {
    let dir = tempfile::tempdir().unwrap();
    let (vault, promote_id) = build_promoted_vault(dir.path());
    let before = decision_count(&vault);

    let (code, stdout, stderr) = run_void(&vault, &promote_id.canonical());
    assert_eq!(code, 0, "the void must succeed; stderr: {stderr}");
    // The VOID-direction lines: the 2018 rewrite, its 1040-X implication, and the amend-to-PAY wording.
    assert!(
        stdout.contains("2018"),
        "the advisory names the affected filed year 2018: {stdout}"
    );
    assert!(
        stdout.contains("1040-X"),
        "the advisory names the Form 1040-X implication: {stdout}"
    );
    assert!(
        stdout.to_lowercase().contains("additional tax"),
        "voiding a promote over a filed floor-year is amend-to-PAY (additional tax): {stdout}"
    );
    // The void was still recorded (the advisory is non-gating).
    assert_eq!(
        decision_count(&vault),
        before + 1,
        "the void decision is still recorded after the warning"
    );
}

/// ★ arch r1 M-3 (Phase-1a fold): voiding the promoted **DeclareTranche** (NOT the promote) is REFUSED
/// upstream by `guard_decision_conflict`/`would_conflict` at record time — the engine holds the tranche in
/// force via its live promote (an inert `DecisionConflict`, `resolve.rs` tranche-void adjudication). The
/// refusal fires BEFORE `promote_void_advisory_lines`, so NO Void-direction amend-to-PAY advisory is ever
/// printed for this (inert) void. This regression-locks the guard so the removed `.or_else` DeclareTranche
/// branch (which would have wrongly printed a reversion + amend-to-PAY for a void that changes nothing)
/// stays unreachable. Green both before AND after the `.or_else` removal — it pins the reachable guardrail,
/// not a mutation of the dead branch (the behavior was already correct; this locks it).
#[test]
fn voiding_a_promoted_declare_tranche_is_refused_and_prints_no_amend_advisory() {
    let dir = tempfile::tempdir().unwrap();
    let (vault, _promote_id) = build_promoted_vault(dir.path());
    // The DeclareTranche decision the promote targets (build_promoted_vault appends it as decision 1).
    let tranche_id = {
        let s = Session::open(&vault, &pp()).unwrap();
        let id = load_all(s.conn())
            .unwrap()
            .into_iter()
            .find(|e| matches!(e.payload, EventPayload::DeclareTranche(_)))
            .map(|e| e.id)
            .expect("the promoted DeclareTranche is present");
        id
    };
    let before = decision_count(&vault);

    let (code, stdout, stderr) = run_void(&vault, &tranche_id.canonical());

    // Refused at record time with the inert-void `DecisionConflict` reason (the resolver == record-time
    // guard by construction).
    assert_ne!(
        code, 0,
        "voiding a promote-held DeclareTranche must be refused; stdout={stdout} stderr={stderr}"
    );
    assert!(
        stderr.contains("cannot record this decision")
            && stderr.contains("held in force by a live PromoteTranche"),
        "the refusal names the inert-void reason: {stderr}"
    );
    // The wrong guidance never prints: no Void-direction amend-to-PAY advisory reaches stdout.
    assert!(
        !stdout.to_lowercase().contains("additional tax") && !stdout.contains("1040-X"),
        "an inert (refused) void must print NO amend-to-PAY promote-void advisory: {stdout}"
    );
    // Fail-closed: nothing was recorded.
    assert_eq!(
        decision_count(&vault),
        before,
        "a refused void appends no decision"
    );
}

/// ★ Task 11 (BG-D3, arch r3 M-1): the verify-drift advisory is WIRED into `verify`/`build_verify`, not
/// just the core fn. `build_promoted_vault` files a $12,000 floor for a 0.4-BTC 2018-Q1 tranche
/// ($30,000/BTC — far ABOVE any 2018 daily close), so recomputing `filed_basis_for` against the CURRENT
/// bundled prices lands well below the stored floor ⇒ the OVERSTATED-basis drift advisory fires and rides
/// the `VerifyReport.drift` field. Threading a `PriceProvider` into `verify` is what makes this non-vacuous.
#[test]
fn verify_surfaces_the_promote_drift_advisory_for_a_drifted_promote() {
    let dir = tempfile::tempdir().unwrap();
    let (vault, _promote_id) = build_promoted_vault(dir.path());
    let report = cmd::inspect::verify(&vault, &pp()).unwrap();
    assert!(
        !report.drift.is_empty(),
        "verify's VerifyReport.drift must be non-empty for a drifted promote (wired into build_verify): \
         {:?}",
        report.drift
    );
    assert!(
        report
            .drift
            .iter()
            .any(|l| l.contains("void") && l.contains("re-promote") && l.contains("not yet filed")),
        "the stored floor is OVERSTATED (recomputes lower) → the conditional void+re-promote copy: {:?}",
        report.drift
    );
}

// ════════════════════════════════════════════════════════════════════════════════════════════════
// Task 10 — the `promote-tranche` verb: BG-D5 provenance + BG-D6 consent recording + BG-D7 Part II.
// ════════════════════════════════════════════════════════════════════════════════════════════════

/// The wallet MY OWN `declare_tranche` fixtures below use (distinct from `wallet()` above, which the T8
/// fixtures share with a documented buy/sell).
fn tranche_wallet() -> WalletId {
    WalletId::SelfCustody {
        label: "promote-t10".into(),
    }
}

fn count<P: Fn(&EventPayload) -> bool>(vault: &Path, pred: P) -> usize {
    let s = Session::open(vault, &pp()).unwrap();
    load_all(s.conn())
        .unwrap()
        .iter()
        .filter(|e| pred(&e.payload))
        .count()
}

/// The single recorded `PromoteTranche` payload (panics if there isn't exactly one).
fn only_promote(vault: &Path) -> PromoteTranche {
    let s = Session::open(vault, &pp()).unwrap();
    load_all(s.conn())
        .unwrap()
        .into_iter()
        .find_map(|e| match e.payload {
            EventPayload::PromoteTranche(p) => Some(p),
            _ => None,
        })
        .expect("exactly one PromoteTranche recorded")
}

/// A vault with a single declared (UNPROMOTED) tranche inside a fully price-covered window
/// (2020-01-01..2020-01-10 — the bundled daily-close dataset spans 2010-07-17..release with no gaps, so
/// `filed_basis_for` always succeeds here). Returns (vault, the tranche's canonical target ref).
fn vault_with_tranche(dir: &Path) -> (PathBuf, String) {
    let vault = dir.join("vault.pgp");
    cmd::init::run(&vault, &pp(), &dir.join("k.asc")).unwrap();
    let id = cmd::tranche::declare_tranche(
        &vault,
        &pp(),
        40_000_000,
        tranche_wallet(),
        date!(2020 - 01 - 01),
        date!(2020 - 01 - 10),
        now(),
    )
    .unwrap();
    (vault, id.canonical())
}

/// A vault with a tranche that is ALREADY promoted (hand-crafted, mirroring `declare_tranche_cli.rs`'s
/// `promote_ev` style) — so a SECOND `promote_tranche` call on the same target must be refused by
/// `would_conflict` (BG-D9). Returns (vault, the ORIGINAL tranche's target ref).
fn vault_with_promoted_tranche(dir: &Path) -> (PathBuf, String) {
    let (vault, target_ref) = vault_with_tranche(dir);
    let target = parse_event_id(&target_ref).unwrap();
    let mut s = Session::open(&vault, &pp()).unwrap();
    append_decision(
        s.conn(),
        EventPayload::PromoteTranche(PromoteTranche {
            target,
            method: FloorMethod::WindowLowClose,
            filed_basis: dec!(1_000),
            coverage: Coverage::Full,
            provenance_attested: true,
            acknowledgment: Acknowledgment {
                phrase: PROMOTE_ACK_PHRASE.into(),
                shown_terms: vec![],
                provenance_text: "acquired by purchase within the declared window".into(),
                provenance_version: "v1".into(),
            },
            part_ii_narrative: "cash P2P purchase, no records; window bounded on-chain".into(),
        }),
        now(),
        UtcOffset::UTC,
        None,
    )
    .unwrap();
    s.save().unwrap();
    (vault, target_ref)
}

fn consent_terms_fixture() -> Vec<ConsentTerm> {
    vec![ConsentTerm::ComputedTax {
        year: 2020,
        delta_usd: dec!(500),
        deduction_delta_usd: None,
    }]
}

fn consent_terms_with_deduction_and_unrealized() -> Vec<ConsentTerm> {
    vec![
        ConsentTerm::ComputedTax {
            year: 2020,
            delta_usd: dec!(0),
            deduction_delta_usd: Some(dec!(300)),
        },
        ConsentTerm::Unrealized {
            sat: 10_000_000,
            hypothetical_reduction: Some(dec!(1_000)),
            as_of: Some(date!(2020 - 06 - 01)),
        },
    ]
}

/// §6 / tax r1 M-6: refuse Gift/Inheritance/Mining/Earned/Airdrop/Fork — not just Gift (BG-D5's closed
/// enumeration). Fail-closed: nothing is ever recorded across the whole sweep.
#[test]
fn every_non_purchase_provenance_is_refused_fail_closed() {
    let dir = tempfile::tempdir().unwrap();
    let (vault, target) = vault_with_tranche(dir.path());
    for pk in [
        ProvenanceKind::Gift,
        ProvenanceKind::Inheritance,
        ProvenanceKind::Mining,
        ProvenanceKind::Earned,
        ProvenanceKind::Airdrop,
        ProvenanceKind::Fork,
    ] {
        let err =
            cmd::promote::promote_tranche(&vault, &pp(), &target, pk, "facts".into(), None, now())
                .unwrap_err();
        assert!(
            matches!(err, CliError::Usage(ref m) if m.contains("purchase") && m.contains("real acquisition")),
            "{pk:?} must be refused naming 'purchase' + 'real acquisition': {err}"
        );
    }
    assert_eq!(
        count(&vault, |p| matches!(p, EventPayload::PromoteTranche(_))),
        0,
        "fail-closed: nothing recorded across the whole non-purchase sweep (BG-D5)"
    );
}

/// BG-D7: an empty/whitespace Part II narrative is refused AT RECORD TIME (present-by-construction) —
/// even with a valid provenance and a correct acknowledgment.
#[test]
fn empty_part_ii_narrative_is_refused_at_record_time() {
    let dir = tempfile::tempdir().unwrap();
    let (vault, target) = vault_with_tranche(dir.path());
    let err = cmd::promote::promote_tranche(
        &vault,
        &pp(),
        &target,
        ProvenanceKind::Purchase,
        "  ".into(),
        Some(PROMOTE_ACK_PHRASE),
        now(),
    )
    .unwrap_err();
    assert!(
        matches!(err, CliError::Usage(ref m) if m.contains("Part II")),
        "an empty narrative must be refused naming 'Part II': {err}"
    );
    assert_eq!(
        count(&vault, |p| matches!(p, EventPayload::PromoteTranche(_))),
        0
    );
}

/// A fully-valid promote records: the filed_basis floor is `>$0`, the acknowledgment phrase is stored
/// verbatim, and `provenance_attested` is `true`.
#[test]
fn a_recorded_promote_carries_the_acknowledgment_and_stored_floor() {
    let dir = tempfile::tempdir().unwrap();
    let (vault, target) = vault_with_tranche(dir.path());
    cmd::promote::promote_tranche(
        &vault,
        &pp(),
        &target,
        ProvenanceKind::Purchase,
        "cash P2P, no records".into(),
        Some(PROMOTE_ACK_PHRASE),
        now(),
    )
    .unwrap();
    let p = only_promote(&vault);
    assert!(
        p.filed_basis > btctax_core::Usd::ZERO,
        "filed_basis must be > $0: {p:?}"
    );
    assert!(!p.acknowledgment.phrase.is_empty());
    assert_eq!(p.acknowledgment.phrase, PROMOTE_ACK_PHRASE);
    assert!(p.provenance_attested);
    assert_eq!(p.part_ii_narrative, "cash P2P, no records");
}

/// BG-D9: a second promote on an already-promoted target is refused via the `would_conflict` pre-check
/// (NOT last-wins) — the record-time UX-P4-3 layer over the engine's own `DecisionConflict`.
#[test]
fn a_second_promote_is_refused_by_would_conflict() {
    let dir = tempfile::tempdir().unwrap();
    let (vault, target) = vault_with_promoted_tranche(dir.path());
    let err = cmd::promote::promote_tranche(
        &vault,
        &pp(),
        &target,
        ProvenanceKind::Purchase,
        "x".into(),
        Some(PROMOTE_ACK_PHRASE),
        now(),
    )
    .unwrap_err();
    assert!(
        matches!(err, CliError::Usage(ref m) if m.contains("conflict")),
        "a second promote must be refused naming 'conflict': {err}"
    );
    assert_eq!(
        count(&vault, |p| matches!(p, EventPayload::PromoteTranche(_))),
        1,
        "still exactly the ORIGINAL promote — the second attempt appended nothing"
    );
}

/// §6 copy bullet covers the CONSENT copy too (not just the 8275/T13 narrative): the penalty base names
/// "of the resulting additional tax" + "plus interest", and NEVER says "safe harbor" (not even to deny it).
#[test]
fn the_consent_copy_names_the_underpayment_base_and_never_says_safe_harbor() {
    let screen = cmd::promote::render_consent(&consent_terms_fixture(), &BTreeSet::new());
    assert!(!screen.to_lowercase().contains("safe harbor"));
    assert!(screen.contains("of the resulting additional tax") && screen.contains("plus interest"));
}

/// tax r2 M-2: a fixture with a `ComputedTax{deduction_delta: Some}` term AND an `Unrealized` term pins
/// BOTH labels the consent screen must carry.
#[test]
fn consent_copy_pins_the_deduction_exclusion_and_unrealized_labels() {
    let screen = cmd::promote::render_consent(
        &consent_terms_with_deduction_and_unrealized(),
        &BTreeSet::new(),
    );
    assert!(
        screen.contains("does NOT capture this charitable-deduction change"),
        "tax-Δ-excludes-deduction sentence: {screen}"
    );
    assert!(
        screen.contains("hypothetical, not a filed figure"),
        "unrealized label rendered: {screen}"
    );
}

/// T9 handoff (progress.md): `consent_terms`'s `deduction_delta_usd` sums the §170(e) charitable-deduction
/// change AND the §1015 gift-basis change into one figure. When the render is told (via
/// `gift_only_years`) that a flagged year's removal was GIFT-only, it must label that year's Δ as a
/// donee-basis (§1015) documentation change — the donor's 1040 is unaffected — NEVER a Schedule-A
/// deduction.
#[test]
fn consent_copy_labels_a_gift_only_year_as_donee_basis_not_schedule_a() {
    let terms = vec![ConsentTerm::ComputedTax {
        year: 2020,
        delta_usd: dec!(0),
        deduction_delta_usd: Some(dec!(400)),
    }];
    let mut gift_only_years = BTreeSet::new();
    gift_only_years.insert(2020);
    let screen = cmd::promote::render_consent(&terms, &gift_only_years);
    assert!(
        screen.contains("donee-basis (§1015)") && screen.contains("donor's 1040 is unaffected"),
        "a gift-only year must be labeled donee-basis, not Schedule-A: {screen}"
    );
    // The disambiguation is an explicit "NOT a Schedule-A deduction" qualifier (not a bare, unqualified
    // "Schedule-A deduction" claim) — assert the qualifier, not mere absence of the substring (which
    // would also fail the correct denial wording, unlike the SPEC's literal "never says safe harbor").
    assert!(
        screen.contains("NOT a Schedule-A deduction"),
        "the gift-only year's Δ must be explicitly denied as a Schedule-A deduction: {screen}"
    );
}

/// The SAME gift-only relabeling applies to an `Uncomputable` term (its `deduction_delta_usd` is a bare
/// `Usd`, not `Option`, but the mislabeling risk — and the T9 handoff — is identical).
#[test]
fn consent_copy_labels_a_gift_only_uncomputable_year_as_donee_basis_not_schedule_a() {
    let terms = vec![ConsentTerm::Uncomputable {
        year: 2019,
        gain_delta_usd: dec!(0),
        deduction_delta_usd: dec!(250),
    }];
    let mut gift_only_years = BTreeSet::new();
    gift_only_years.insert(2019);
    let screen = cmd::promote::render_consent(&terms, &gift_only_years);
    assert!(
        screen.contains("donee-basis (§1015)") && screen.contains("NOT a Schedule-A deduction"),
        "a gift-only UNCOMPUTABLE year must also be labeled donee-basis, not Schedule-A: {screen}"
    );
}

/// Run `btctax --vault <vault> reconcile promote-tranche <target> --provenance purchase --part-ii-file
/// <path> [extra...]`; returns (exit, stdout, stderr). stdin is NOT a terminal under `Command::output()`,
/// so this always drives the NON-interactive main.rs branch.
fn run_promote(
    vault: &Path,
    target: &str,
    part_ii_path: &Path,
    extra: &[&str],
) -> (i32, String, String) {
    let bin = env!("CARGO_BIN_EXE_btctax");
    let mut c = std::process::Command::new(bin);
    c.arg("--vault")
        .arg(vault.to_str().unwrap())
        .arg("reconcile")
        .arg("promote-tranche")
        .arg(target)
        .arg("--provenance")
        .arg("purchase")
        .arg("--part-ii-file")
        .arg(part_ii_path.to_str().unwrap())
        .env("BTCTAX_PASSPHRASE", "pw");
    for a in extra {
        c.arg(a);
    }
    let out = c.output().expect("btctax binary must execute");
    (
        out.status.code().expect("exits normally"),
        String::from_utf8_lossy(&out.stdout).into_owned(),
        String::from_utf8_lossy(&out.stderr).into_owned(),
    )
}

/// N-2 (BG-D6): the non-TTY path with no `--i-acknowledge` still REFUSES (exit != 0) but prints the
/// computed consent figures to stdout BEFORE refusing — a scripted caller can always see what it declined
/// to acknowledge. Drives the REAL binary so the main.rs wiring (not just the library fn) is exercised.
#[test]
fn non_tty_missing_acknowledge_still_prints_the_consent_screen_and_refuses() {
    let dir = tempfile::tempdir().unwrap();
    let (vault, target) = vault_with_tranche(dir.path());
    let part_ii = dir.path().join("part_ii.txt");
    std::fs::write(
        &part_ii,
        "cash P2P purchase, no records; window bounded on-chain",
    )
    .unwrap();

    let (code, stdout, stderr) = run_promote(&vault, &target, &part_ii, &[]);
    assert_ne!(
        code, 0,
        "missing --i-acknowledge must refuse; stderr: {stderr}"
    );
    assert!(
        stdout.contains("of the resulting additional tax"),
        "the consent screen prints even on refusal (N-2): {stdout}"
    );
    assert_eq!(
        count(&vault, |p| matches!(p, EventPayload::PromoteTranche(_))),
        0,
        "the refused promote must NOT be appended (fail-closed)"
    );

    // The non-interactive success path: --i-acknowledge with the exact phrase records it.
    let (code2, stdout2, stderr2) = run_promote(
        &vault,
        &target,
        &part_ii,
        &["--i-acknowledge", PROMOTE_ACK_PHRASE],
    );
    assert_eq!(
        code2, 0,
        "a correct --i-acknowledge must succeed; stderr: {stderr2}"
    );
    assert!(stdout2.contains("of the resulting additional tax"));
    assert_eq!(
        count(&vault, |p| matches!(p, EventPayload::PromoteTranche(_))),
        1
    );
}

/// A vault with a tranche declared over a WIDE (> 1 year) window — still fully price-covered.
fn vault_with_wide_window_tranche(dir: &Path) -> (PathBuf, String) {
    let vault = dir.join("vault.pgp");
    cmd::init::run(&vault, &pp(), &dir.join("k.asc")).unwrap();
    let id = cmd::tranche::declare_tranche(
        &vault,
        &pp(),
        40_000_000,
        tranche_wallet(),
        date!(2015 - 01 - 01),
        date!(2018 - 01 - 01),
        now(),
    )
    .unwrap();
    (vault, id.canonical())
}

/// SPEC §1 "two honest limits": a wide (> 1 year) declared window tends to yield a LOW ("trivial")
/// floor — the CONSENT flow must surface this caution so the filer can weigh whether promoting is even
/// worth the Form 8275 disclosure surface.
#[test]
fn a_wide_window_promote_prints_the_trivial_floor_caution() {
    let dir = tempfile::tempdir().unwrap();
    let (vault, target) = vault_with_wide_window_tranche(dir.path());
    let part_ii = dir.path().join("part_ii.txt");
    std::fs::write(
        &part_ii,
        "cash P2P purchase, no records; wide multi-year window",
    )
    .unwrap();

    let (code, stdout, stderr) = run_promote(
        &vault,
        &target,
        &part_ii,
        &["--i-acknowledge", PROMOTE_ACK_PHRASE],
    );
    assert_eq!(code, 0, "stderr: {stderr}");
    let lower = stdout.to_lowercase();
    assert!(
        lower.contains("trivial") && lower.contains("wide"),
        "a wide window must print the trivial-floor caution: {stdout}"
    );
}

// ════════════════════════════════════════════════════════════════════════════════════════════════
// Task 14 — BG-D8 the export-refusal COMPLETENESS gate: a promoted-basis DISPOSAL leg filed WITHOUT its
// complete Form 8275 is a HARD REFUSAL (Reg §1.6662-4(f): disclosure is adequate only on a COMPLETED
// Form 8275). A REAL refuse-before-bytes gate (the pseudo-export-block precedent), NOT the always-written
// basis_methodology.txt pattern; on SUCCESS the disclosure is emitted by its OWN name (form_8275.txt).
// ════════════════════════════════════════════════════════════════════════════════════════════════

/// The tax year both Task-14 fixtures dispose in — a SHIPPED IRS-PDF year (this build bundles 2017/2024/
/// 2025) so the CLEAN export actually fills a packet; the tranche is declared pre-2025 so a promote is
/// meaningful.
const T14_YEAR: i32 = 2024;

/// A 2024 sell of exactly 0.4 BTC in `wallet()` — drains the 0.4-BTC tranche (its only lot), so the
/// resulting disposal leg is a PROMOTED leg filed in `T14_YEAR`.
fn t14_sell() -> LedgerEvent {
    imp(
        "T14-SELL",
        datetime!(2024 - 09 - 01 0:00 UTC),
        EventPayload::Dispose(Dispose {
            sat: 40_000_000,
            usd_proceeds: dec!(20_000),
            fee_usd: dec!(0),
            kind: DisposeKind::Sell,
        }),
    )
}

/// ★ The raw-vault BYPASS: declare a tranche (CLI), then HAND-APPEND a `PromoteTranche` with an EMPTY
/// `part_ii_narrative` — the T10 CLI refuses an empty narrative at record time (BG-D7), so only a raw
/// `append_decision` can force `disclosure_8275().incomplete == true` — then import a sell that drains the
/// promoted tranche. Net effect: a promoted DISPOSAL leg filed in 2024 whose Form 8275 Part II is empty.
fn raw_vault_promote_with_empty_part_ii(dir: &Path) -> PathBuf {
    let vault = dir.join("vault.pgp");
    cmd::init::run(&vault, &pp(), &dir.join("k.asc")).unwrap();
    let tranche_id = cmd::tranche::declare_tranche(
        &vault,
        &pp(),
        40_000_000,
        wallet(),
        date!(2024 - 01 - 01),
        date!(2024 - 03 - 31),
        now(),
    )
    .unwrap();
    let mut s = Session::open(&vault, &pp()).unwrap();
    append_decision(
        s.conn(),
        EventPayload::PromoteTranche(PromoteTranche {
            target: tranche_id,
            method: FloorMethod::WindowLowClose,
            filed_basis: dec!(12_000),
            coverage: Coverage::Full,
            provenance_attested: true,
            acknowledgment: Acknowledgment {
                phrase: PROMOTE_ACK_PHRASE.into(),
                shown_terms: vec![],
                provenance_text: "acquired by purchase within the declared window".into(),
                provenance_version: "v1".into(),
            },
            part_ii_narrative: String::new(), // ★ EMPTY — the raw-vault bypass (the CLI refuses this)
        }),
        now(),
        UtcOffset::UTC,
        None,
    )
    .unwrap();
    append_import_batch(s.conn(), &[t14_sell()]).unwrap();
    s.save().unwrap();
    vault
}

/// The T10-path CLEAN fixture: declare a tranche (CLI) + promote it via the REAL `promote-tranche` verb
/// (which enforces a non-empty Part II — a COMPLETE Form 8275), then import a sell that drains it — a
/// promoted 2024 disposal leg with a complete disclosure.
fn vault_with_promoted_disposal_via_cli(dir: &Path) -> PathBuf {
    let vault = dir.join("vault.pgp");
    cmd::init::run(&vault, &pp(), &dir.join("k.asc")).unwrap();
    let tranche_id = cmd::tranche::declare_tranche(
        &vault,
        &pp(),
        40_000_000,
        wallet(),
        date!(2024 - 01 - 01),
        date!(2024 - 03 - 31),
        now(),
    )
    .unwrap();
    cmd::promote::promote_tranche(
        &vault,
        &pp(),
        &tranche_id.canonical(),
        ProvenanceKind::Purchase,
        "cash P2P purchase, no records; window bounded on-chain".into(),
        Some(PROMOTE_ACK_PHRASE),
        now(),
    )
    .unwrap();
    let mut s = Session::open(&vault, &pp()).unwrap();
    append_import_batch(s.conn(), &[t14_sell()]).unwrap();
    s.save().unwrap();
    vault
}

/// ★ BG-D8: an export whose packet contains a promoted-basis leg but only an INCOMPLETE Form 8275 (empty
/// Part II) is REFUSED — and refused BEFORE any bytes are written (the out_dir is left untouched). The
/// refusing state is reached only via the raw-vault bypass (the T10 CLI can't record an empty narrative).
#[test]
fn export_with_a_promoted_leg_but_incomplete_8275_refuses_before_bytes() {
    let dir = tempfile::tempdir().unwrap();
    let vault = raw_vault_promote_with_empty_part_ii(dir.path());
    let out = dir.path().join("export_out"); // deliberately NOT pre-created

    let err = cmd::admin::export_irs_pdf(&vault, &pp(), &out, T14_YEAR, &[], None).unwrap_err();
    assert!(
        matches!(err, CliError::Usage(ref m) if m.contains("Form 8275")),
        "a promoted leg without a complete Form 8275 must be REFUSED naming 'Form 8275': {err}"
    );
    // Refuse-before-bytes: a refused export writes ZERO bytes — the out_dir was never even created (or is
    // empty). This is what makes it a REAL gate, not the always-writes basis_methodology.txt pattern.
    assert!(
        std::fs::read_dir(&out)
            .map(|mut d| d.next().is_none())
            .unwrap_or(true),
        "a refused export leaves out_dir untouched (zero bytes written)"
    );
}

/// ★ BG-D8: a CLEAN promoted export (real ledger, complete Form 8275) SUCCEEDS and emits the disclosure by
/// its OWN name — `form_8275.txt`, NOT `form_8275.txt || basis_methodology.txt` (basis_methodology is
/// ALWAYS written, so the disjunction would be a vacuous assertion — tax r1 I-8). No DRAFT watermark.
#[test]
fn a_clean_promoted_export_writes_the_8275_by_name_no_watermark() {
    let dir = tempfile::tempdir().unwrap();
    let vault = vault_with_promoted_disposal_via_cli(dir.path());
    let out = dir.path().join("export_out");

    let report = cmd::admin::export_irs_pdf(&vault, &pp(), &out, T14_YEAR, &[], None).unwrap();
    assert!(
        out.join("form_8275.txt").exists(),
        "a clean promoted export emits the 8275 content by its OWN name (form_8275.txt)"
    );
    // Clean export — a real (not pseudo) ledger is never DRAFT-watermarked.
    assert!(
        !report.watermarked,
        "a real promoted ledger exports CLEAN (no DRAFT watermark)"
    );
}

// ════════════════════════════════════════════════════════════════════════════════════════════════
// T-f8275-part-ii-overflow round 2 finding 2 — the export-time Part II CAPACITY gate: an overflowing
// narrative must refuse BEFORE any packet file (`basis_methodology.txt`, `form_8275.txt`, …) is
// written, mirroring the BG-D8 completeness gate just above. Record time does NOT reject an overflowing
// narrative (a follow-up, `design/f8275-part-ii-overflow/FOLLOWUPS.md` — the vault is append-only, so a
// record-time bound cannot be relaxed later), so the REAL `promote-tranche` verb happily records one.
// ════════════════════════════════════════════════════════════════════════════════════════════════

/// A promoted 2024 disposal (same shape as [`vault_with_promoted_disposal_via_cli`]) whose Part II
/// narrative needs far more single-line fields than Form 8275 has (900 repeats of `"word "` — the SAME
/// adversarial fixture `btctax-forms`'s `sp4.rs` uses, needing 37 lines against the 28 available).
fn vault_with_promoted_disposal_and_overflowing_part_ii(dir: &Path) -> PathBuf {
    let vault = dir.join("vault.pgp");
    cmd::init::run(&vault, &pp(), &dir.join("k.asc")).unwrap();
    let tranche_id = cmd::tranche::declare_tranche(
        &vault,
        &pp(),
        40_000_000,
        wallet(),
        date!(2024 - 01 - 01),
        date!(2024 - 03 - 31),
        now(),
    )
    .unwrap();
    // Record time does not bound the narrative's length (follow-up) — the real verb records it as-is.
    cmd::promote::promote_tranche(
        &vault,
        &pp(),
        &tranche_id.canonical(),
        ProvenanceKind::Purchase,
        "word ".repeat(900),
        Some(PROMOTE_ACK_PHRASE),
        now(),
    )
    .unwrap();
    let mut s = Session::open(&vault, &pp()).unwrap();
    append_import_batch(s.conn(), &[t14_sell()]).unwrap();
    s.save().unwrap();
    vault
}

/// ★ round 2 finding 2: an overflowing Part II narrative is REFUSED before `mkdir_out` — the crypto-slice
/// export path (`export_irs_pdf`). Before this fix, the overflow was only discovered mid-write inside
/// `fill_form_8275_slice`, well after `basis_methodology.txt` / `form_8275.txt` (and possibly
/// `f8949.pdf`) were already on disk — an estimated-basis 8949 filed with no 8275 PDF behind it.
#[test]
fn export_irs_pdf_with_an_overflowing_part_ii_narrative_refuses_before_bytes() {
    let dir = tempfile::tempdir().unwrap();
    let vault = vault_with_promoted_disposal_and_overflowing_part_ii(dir.path());
    let out = dir.path().join("export_out"); // deliberately NOT pre-created

    let err = cmd::admin::export_irs_pdf(&vault, &pp(), &out, T14_YEAR, &[], None).unwrap_err();
    assert!(
        matches!(err, CliError::Usage(ref m)
            if m.contains(&T14_YEAR.to_string())
            && m.contains("Part II")
            && m.contains("--part-ii-file")),
        "must name the year, 'Part II', and the --part-ii-file remedy: {err}"
    );
    assert!(
        std::fs::read_dir(&out)
            .map(|mut d| d.next().is_none())
            .unwrap_or(true),
        "a refused export leaves out_dir untouched (zero bytes written) — NOT a half-populated packet"
    );
}

/// ★ round 2 finding 2 ("do it uniformly"): the SAME refusal, on the full-return export path (reached
/// via `plant_full_return_ri`, the SAME dispatch-forcing helper `export_full_return_refuses_before_bytes_
/// on_incomplete_8275` below uses). This path was already byte-safe without the pre-flight
/// (`fill_full_return` is all-or-nothing, called before `mkdir_out`) — this pins that the nicer,
/// year/remedy-naming message applies here too, not just the generic `FormsError::Overflow` Display.
#[test]
fn export_full_return_with_an_overflowing_part_ii_narrative_refuses_with_a_named_remedy() {
    let dir = tempfile::tempdir().unwrap();
    let vault = vault_with_promoted_disposal_and_overflowing_part_ii(dir.path());
    plant_full_return_ri(&vault, T14_YEAR);
    let out = dir.path().join("export_out");

    let err = cmd::admin::export_irs_pdf(&vault, &pp(), &out, T14_YEAR, &[], None).unwrap_err();
    assert!(
        matches!(err, CliError::Usage(ref m)
            if m.contains(&T14_YEAR.to_string())
            && m.contains("Part II")
            && m.contains("--part-ii-file")),
        "the full-return path must give the SAME named-remedy refusal: {err}"
    );
    assert!(
        std::fs::read_dir(&out)
            .map(|mut d| d.next().is_none())
            .unwrap_or(true),
        "a refused full-return export leaves out_dir untouched"
    );
}

/// ★ Whole-branch tax M-1: the Form 8275 is the MANDATORY disclosure — it must travel WITH the promoted
/// 8949 position, so it rides UNCONDITIONALLY even when `--forms f8949` narrows the slice to exclude it.
/// Otherwise the estimate position would export without its official disclosure PDF (Reg §1.6662-4(f)
/// makes disclosure adequate only on a COMPLETED Form 8275). Mutation-verified: restoring the
/// `wants(forms, FormArg::Form8275)` gate around the 8275 fill reds this.
#[test]
fn a_narrowed_forms_f8949_slice_still_emits_the_mandatory_8275_pdf_on_a_promoted_year() {
    let dir = tempfile::tempdir().unwrap();
    let vault = vault_with_promoted_disposal_via_cli(dir.path());
    let out = dir.path().join("export_out");

    // `--forms f8949` ONLY — deliberately excludes f8275 from the requested slice.
    let report =
        cmd::admin::export_irs_pdf(&vault, &pp(), &out, T14_YEAR, &[FormArg::F8949], None).unwrap();
    assert!(
        out.join("f8949.pdf").exists(),
        "the requested 8949 slice is written"
    );
    assert!(
        out.join("form_8275.pdf").exists(),
        "the MANDATORY 8275 disclosure PDF rides even though --forms excluded it (BG-D8)"
    );
    assert!(
        report.form_8275_path.is_some(),
        "the report records the mandatory 8275 PDF path"
    );
}

/// Plant a minimally-valid `return_inputs` row for `year` so `export_irs_pdf` DISPATCHES to the
/// full-return pipeline (`return_inputs::exists` is the dispatch's own discriminator, admin.rs
/// `export_irs_pdf`). Mirrors `export_irs_pdf.rs`'s
/// `export_dispatches_a_full_return_year_to_the_full_packet` fixture — an identified Single filer with
/// every live declaration answered, so a real (non-refusing) full-return packet can assemble.
fn plant_full_return_ri(vault: &Path, year: i32) {
    use btctax_core::tax::return_inputs::{Person, ReturnInputs};
    use btctax_core::tax::types::FilingStatus;

    let mut s = Session::open(vault, &pp()).unwrap();
    let mut ri = ReturnInputs {
        filing_status: FilingStatus::Single,
        header: btctax_core::tax::testonly::not_a_dependent(),
        ..Default::default()
    };
    ri.header.taxpayer = Person {
        first_name: "Pat".into(),
        last_name: "Roe".into(),
        ssn: "222-33-4444".into(),
        ..Default::default()
    };
    btctax_core::tax::testonly::answer_all_live_declarations(&mut ri);
    return_inputs::set(s.conn(), year, &ri).unwrap();
    s.save().unwrap();
}

/// ★ Phase-1a T14 (BG-D8): the refuse-before-bytes gate at the FULL-RETURN placement
/// (`export_full_return`'s OWN `promote_export_gate` call, admin.rs) — distinct from the crypto-slice
/// call site `export_with_a_promoted_leg_but_incomplete_8275_refuses_before_bytes` pins above. Planting
/// a `return_inputs` row for `T14_YEAR` on the SAME raw-vault-incomplete fixture makes `export_irs_pdf`
/// DISPATCH to `export_full_return`, so this confirms that placement's gate call fires too — before any
/// bytes are written.
#[test]
fn export_full_return_refuses_before_bytes_on_incomplete_8275() {
    let dir = tempfile::tempdir().unwrap();
    let vault = raw_vault_promote_with_empty_part_ii(dir.path());
    plant_full_return_ri(&vault, T14_YEAR);
    let out = dir.path().join("export_out"); // deliberately NOT pre-created

    let err = cmd::admin::export_irs_pdf(&vault, &pp(), &out, T14_YEAR, &[], None).unwrap_err();
    assert!(
        matches!(err, CliError::Usage(ref m) if m.contains("Form 8275")),
        "the FULL-RETURN placement must refuse a promoted leg without a complete Form 8275: {err}"
    );
    assert!(
        std::fs::read_dir(&out)
            .map(|mut d| d.next().is_none())
            .unwrap_or(true),
        "a refused full-return export leaves out_dir untouched (zero bytes written)"
    );
}

/// ★ Phase-1a T14 (BG-D8): the SAME refuse-before-bytes gate at the `export_snapshot` placement — a
/// THIRD distinct call site (`export_snapshot`'s own `promote_export_gate` call, admin.rs) from both
/// `export_irs_pdf`'s crypto-slice and full-return placements.
#[test]
fn export_snapshot_refuses_before_bytes_on_incomplete_8275() {
    let dir = tempfile::tempdir().unwrap();
    let vault = raw_vault_promote_with_empty_part_ii(dir.path());
    let out = dir.path().join("export_out"); // deliberately NOT pre-created

    let err = cmd::admin::export_snapshot(&vault, &pp(), &out, Some(T14_YEAR), None).unwrap_err();
    assert!(
        matches!(err, CliError::Usage(ref m) if m.contains("Form 8275")),
        "export_snapshot must refuse a promoted leg without a complete Form 8275: {err}"
    );
    assert!(
        std::fs::read_dir(&out)
            .map(|mut d| d.next().is_none())
            .unwrap_or(true),
        "a refused export_snapshot leaves out_dir untouched (zero bytes written)"
    );
}

/// ★ Phase-1a T14 (BG-D8): the success-emit of `form_8275.txt` at the FULL-RETURN placement — a
/// COMPLETE promoted disclosure (T10-recorded, non-empty Part II), exported via `export_irs_pdf`
/// DISPATCHED to `export_full_return` (a `return_inputs` row planted for `T14_YEAR`), writes the
/// disclosure by its OWN name — exactly as `a_clean_promoted_export_writes_the_8275_by_name_no_
/// watermark` pins for the crypto-slice call site.
#[test]
fn export_full_return_writes_form_8275_txt_by_name() {
    let dir = tempfile::tempdir().unwrap();
    let vault = vault_with_promoted_disposal_via_cli(dir.path());
    plant_full_return_ri(&vault, T14_YEAR);
    let out = dir.path().join("export_out");

    cmd::admin::export_irs_pdf(&vault, &pp(), &out, T14_YEAR, &[], None)
        .expect("a complete promoted disclosure exports via the dispatched full-return path");
    assert!(
        out.join("form_8275.txt").exists(),
        "the full-return packet emits the 8275 content by its OWN name (form_8275.txt)"
    );
}

/// ★ Phase-1a T14 (BG-D8): the SAME success-emit of `form_8275.txt` at the `export_snapshot`
/// placement.
#[test]
fn export_snapshot_writes_form_8275_txt_by_name() {
    let dir = tempfile::tempdir().unwrap();
    let vault = vault_with_promoted_disposal_via_cli(dir.path());
    let out = dir.path().join("export_out");

    cmd::admin::export_snapshot(&vault, &pp(), &out, Some(T14_YEAR), None)
        .expect("a complete promoted disclosure exports via export_snapshot");
    assert!(
        out.join("form_8275.txt").exists(),
        "export_snapshot emits the 8275 content by its OWN name (form_8275.txt)"
    );
}

// ════════════════════════════════════════════════════════════════════════════════════════════════
// Task 16 — wiring the OFFICIAL Form 8275 fillable PDF into the export paths; BG-D8's gate re-pointed
// at it. Four KATs: year-2025/2017 end-to-end (arch r1 I-6 — the year-aliasing must reach the export
// layer, not just `fill_form_8275` itself, which `sp4.rs` already pins), the completeness gate still
// refuses before ANY byte (including the new PDF) when Part II is incomplete, a > 6-leg promoted year
// refuses CLEANLY (no panic, no half-written packet), and the all-years `export_snapshot` dump still
// co-emits one `form_8275_{year}.txt` per promoted year (M2).
// ════════════════════════════════════════════════════════════════════════════════════════════════

/// Generalizes `vault_with_promoted_disposal_via_cli` (T14, fixed to 2024) to an ARBITRARY supported
/// `year` — T16's KAT needs 2025 and 2017, since Form 8275's bundled asset aliases every
/// `SUPPORTED_YEAR`. Same shape: one declared+promoted tranche (a Q1 `year` window), drained by a
/// single Q3 `year` sell — a promoted DISPOSAL leg filed in `year` with a COMPLETE Form 8275.
fn vault_with_promoted_disposal_via_cli_year(dir: &Path, year: i32) -> PathBuf {
    let vault = dir.join("vault.pgp");
    cmd::init::run(&vault, &pp(), &dir.join("k.asc")).unwrap();
    let window_start = time::Date::from_calendar_date(year, time::Month::January, 1).unwrap();
    let window_end = time::Date::from_calendar_date(year, time::Month::March, 31).unwrap();
    let tranche_id = cmd::tranche::declare_tranche(
        &vault,
        &pp(),
        40_000_000,
        wallet(),
        window_start,
        window_end,
        now(),
    )
    .unwrap();
    cmd::promote::promote_tranche(
        &vault,
        &pp(),
        &tranche_id.canonical(),
        ProvenanceKind::Purchase,
        "cash P2P purchase, no records; window bounded on-chain".into(),
        Some(PROMOTE_ACK_PHRASE),
        now(),
    )
    .unwrap();
    let sell_ts = time::Date::from_calendar_date(year, time::Month::September, 1)
        .unwrap()
        .with_hms(0, 0, 0)
        .unwrap()
        .assume_utc();
    let sell = imp(
        "T16-SELL",
        sell_ts,
        EventPayload::Dispose(Dispose {
            sat: 40_000_000,
            usd_proceeds: dec!(20_000),
            fee_usd: dec!(0),
            kind: DisposeKind::Sell,
        }),
    );
    let mut s = Session::open(&vault, &pp()).unwrap();
    append_import_batch(s.conn(), &[sell]).unwrap();
    s.save().unwrap();
    vault
}

/// ★ T16 KAT 1 (plan Step-1; arch r1 I-6 — the most important). A promoted disposal filed in a
/// NON-2024 supported year (2025, then 2017) exports the OFFICIAL Form 8275 PDF via the crypto-slice
/// `export_irs_pdf` — proving the bundled 8275 asset's year-aliasing ({2017, 2024, 2025}) works
/// END-TO-END at the export layer (`sp4.rs` already pins the aliasing inside `fill_form_8275` itself;
/// this is the wiring on top of it). A promoted CURRENT-year (2025) export must never be permanently
/// refused for want of a "2025 revision" that does not exist.
#[test]
fn a_promoted_2025_export_fills_the_8275_and_the_gate_passes() {
    for year in [2025, 2017] {
        let dir = tempfile::tempdir().unwrap();
        let vault = vault_with_promoted_disposal_via_cli_year(dir.path(), year);
        let out = dir.path().join("export_out");

        let report = cmd::admin::export_irs_pdf(&vault, &pp(), &out, year, &[], None)
            .unwrap_or_else(|e| panic!("year {year}: a complete promote must export cleanly: {e}"));
        assert!(
            out.join("form_8275.pdf").exists(),
            "year {year}: the crypto-slice export must fill the official Form 8275 PDF"
        );
        assert_eq!(
            report.form_8275_path,
            Some(out.join("form_8275.pdf")),
            "year {year}: the report names the written 8275 PDF"
        );
        assert!(
            !report.watermarked,
            "year {year}: a real (non-pseudo) ledger exports CLEAN"
        );
    }
}

/// ★ T16 KAT 2 (plan Step-1). The SAME BG-D8 completeness gate — now with the crypto-slice path ALSO
/// trying to fill the official PDF (not just `form_8275.txt`) — still refuses BEFORE any byte reaches
/// disk when a promoted leg's Part II is incomplete: neither the content file nor the new PDF partially
/// writes.
#[test]
fn export_gate_now_refuses_when_the_8275_pdf_is_absent() {
    let dir = tempfile::tempdir().unwrap();
    let vault = raw_vault_promote_with_empty_part_ii(dir.path());
    let out = dir.path().join("export_out"); // deliberately NOT pre-created

    let err = cmd::admin::export_irs_pdf(&vault, &pp(), &out, T14_YEAR, &[], None).unwrap_err();
    assert!(
        matches!(err, CliError::Usage(ref m) if m.contains("Form 8275")),
        "an incomplete Form 8275 must still refuse the export post-T16: {err}"
    );
    assert!(
        std::fs::read_dir(&out)
            .map(|mut d| d.next().is_none())
            .unwrap_or(true),
        "a refused export leaves out_dir untouched — not even a partial form_8275.pdf"
    );
    assert!(!out.join("form_8275.pdf").exists());
    assert!(!out.join("form_8275.txt").exists());
}

/// A vault with `n` DISTINCT promoted disposal legs, each in its OWN wallet (so its sell can only
/// drain its own tranche's lot — no cross-wallet lot-selection ordering to reason about), all filed in
/// `year`.
fn vault_with_n_promoted_disposal_legs(dir: &Path, year: i32, n: u32) -> PathBuf {
    let vault = dir.join("vault.pgp");
    cmd::init::run(&vault, &pp(), &dir.join("k.asc")).unwrap();
    let window_start = time::Date::from_calendar_date(year, time::Month::January, 1).unwrap();
    let window_end = time::Date::from_calendar_date(year, time::Month::March, 31).unwrap();
    let sell_ts = time::Date::from_calendar_date(year, time::Month::September, 1)
        .unwrap()
        .with_hms(0, 0, 0)
        .unwrap()
        .assume_utc();
    for i in 0..n {
        let w = WalletId::Exchange {
            provider: "coinbase".into(),
            account: format!("overflow{i}"),
        };
        let tranche_id = cmd::tranche::declare_tranche(
            &vault,
            &pp(),
            40_000_000,
            w.clone(),
            window_start,
            window_end,
            now(),
        )
        .unwrap();
        cmd::promote::promote_tranche(
            &vault,
            &pp(),
            &tranche_id.canonical(),
            ProvenanceKind::Purchase,
            format!("cash P2P purchase #{i}, no records; window bounded on-chain"),
            Some(PROMOTE_ACK_PHRASE),
            now(),
        )
        .unwrap();
        let mut s = Session::open(&vault, &pp()).unwrap();
        append_import_batch(
            s.conn(),
            &[LedgerEvent {
                id: EventId::import(
                    Source::Coinbase,
                    SourceRef::new(format!("OVERFLOW-SELL-{i}")),
                ),
                utc_timestamp: sell_ts,
                original_tz: UtcOffset::UTC,
                wallet: Some(w),
                payload: EventPayload::Dispose(Dispose {
                    sat: 40_000_000,
                    usd_proceeds: dec!(20_000),
                    fee_usd: dec!(0),
                    kind: DisposeKind::Sell,
                }),
            }],
        )
        .unwrap();
        s.save().unwrap();
    }
    vault
}

/// ★ T16 KAT 3: Form 8275 v1 does not paginate — a year with MORE promoted disposal legs than the
/// revision's 6-row Part I capacity refuses CLEANLY (naming the year, the leg count, and a remedy),
/// never panics, and writes ZERO bytes (refuse-before-bytes) — pinning `export_full_return`'s Task-16 /
/// ADD-2 pre-check (admin.rs). Full-return tables are TY2024-only (v1), so the overflowing year must be
/// `T14_YEAR`.
#[test]
fn promoted_export_with_more_than_6_legs_refuses_cleanly_not_panics() {
    let dir = tempfile::tempdir().unwrap();
    let vault = vault_with_n_promoted_disposal_legs(dir.path(), T14_YEAR, 7);
    plant_full_return_ri(&vault, T14_YEAR);
    let out = dir.path().join("export_out"); // deliberately NOT pre-created

    // This KAT's own job is to prove there is NO panic — assert it directly rather than relying on the
    // harness to merely report one.
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        cmd::admin::export_irs_pdf(&vault, &pp(), &out, T14_YEAR, &[], None)
    }));
    let err = match result {
        Ok(Err(e)) => e,
        Ok(Ok(_)) => {
            panic!("a 7-leg promoted year (> the 6-row capacity) must refuse, not succeed")
        }
        Err(_) => panic!("a 7-leg promoted year must refuse CLEANLY, not panic"),
    };
    assert!(
        matches!(err, CliError::Usage(ref m)
            if m.contains(&T14_YEAR.to_string()) && m.contains("7 promoted disposal leg")),
        "the refusal names the year and the leg count: {err}"
    );
    assert!(
        err.to_string().contains("void one of the promotes"),
        "the refusal names a concrete remedy: {err}"
    );
    assert!(
        std::fs::read_dir(&out)
            .map(|mut d| d.next().is_none())
            .unwrap_or(true),
        "an overflow refusal leaves out_dir untouched (refuse-before-bytes) — no half-written packet"
    );
}

/// ADD-2 twin of the above for the CRYPTO-SLICE pre-check (admin.rs, the `printed_8275` block) — the
/// sibling above plants a full-return RI and so exercises only the full-return pre-check. This one
/// omits `plant_full_return_ri`, so `export_irs_pdf` takes the crypto-slice path and the >6-row refusal
/// must come from the crypto-slice block. Deleting only that block (leaving the full-return copy) would
/// survive the sibling KAT but must RED here.
#[test]
fn promoted_crypto_slice_export_with_more_than_6_legs_refuses_cleanly_not_panics() {
    let dir = tempfile::tempdir().unwrap();
    let vault = vault_with_n_promoted_disposal_legs(dir.path(), T14_YEAR, 7);
    // NB: no `plant_full_return_ri` — this drives the crypto-slice export path.
    let out = dir.path().join("export_out"); // deliberately NOT pre-created

    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        cmd::admin::export_irs_pdf(&vault, &pp(), &out, T14_YEAR, &[], None)
    }));
    let err = match result {
        Ok(Err(e)) => e,
        Ok(Ok(_)) => {
            panic!("a 7-leg promoted crypto-slice export (> the 6-row capacity) must refuse, not succeed")
        }
        Err(_) => panic!("a 7-leg promoted crypto-slice export must refuse CLEANLY, not panic"),
    };
    assert!(
        matches!(err, CliError::Usage(ref m)
            if m.contains(&T14_YEAR.to_string()) && m.contains("7 promoted disposal leg")),
        "the crypto-slice refusal names the year and the leg count: {err}"
    );
    assert!(
        err.to_string().contains("void one of the promotes"),
        "the crypto-slice refusal names a concrete remedy: {err}"
    );
    assert!(
        std::fs::read_dir(&out)
            .map(|mut d| d.next().is_none())
            .unwrap_or(true),
        "a crypto-slice overflow refusal leaves out_dir untouched (refuse-before-bytes)"
    );
}

/// A vault with TWO promoted disposal legs filed in DIFFERENT years — each its own declared+promoted
/// tranche, in its own wallet, drained by its own sell.
fn vault_with_two_promoted_years(dir: &Path, year_a: i32, year_b: i32) -> PathBuf {
    let vault = dir.join("vault.pgp");
    cmd::init::run(&vault, &pp(), &dir.join("k.asc")).unwrap();
    for (i, year) in [year_a, year_b].into_iter().enumerate() {
        let w = WalletId::Exchange {
            provider: "coinbase".into(),
            account: format!("m2-{i}"),
        };
        let window_start = time::Date::from_calendar_date(year, time::Month::January, 1).unwrap();
        let window_end = time::Date::from_calendar_date(year, time::Month::March, 31).unwrap();
        let tranche_id = cmd::tranche::declare_tranche(
            &vault,
            &pp(),
            40_000_000,
            w.clone(),
            window_start,
            window_end,
            now(),
        )
        .unwrap();
        cmd::promote::promote_tranche(
            &vault,
            &pp(),
            &tranche_id.canonical(),
            ProvenanceKind::Purchase,
            format!("cash P2P purchase, no records; {year} window bounded on-chain"),
            Some(PROMOTE_ACK_PHRASE),
            now(),
        )
        .unwrap();
        let sell_ts = time::Date::from_calendar_date(year, time::Month::September, 1)
            .unwrap()
            .with_hms(0, 0, 0)
            .unwrap()
            .assume_utc();
        let mut s = Session::open(&vault, &pp()).unwrap();
        append_import_batch(
            s.conn(),
            &[LedgerEvent {
                id: EventId::import(Source::Coinbase, SourceRef::new(format!("M2-SELL-{i}"))),
                utc_timestamp: sell_ts,
                original_tz: UtcOffset::UTC,
                wallet: Some(w),
                payload: EventPayload::Dispose(Dispose {
                    sat: 40_000_000,
                    usd_proceeds: dec!(20_000),
                    fee_usd: dec!(0),
                    kind: DisposeKind::Sell,
                }),
            }],
        )
        .unwrap();
        s.save().unwrap();
    }
    vault
}

/// ★ T16 KAT 4 (M2): the all-years `export_snapshot` dump (`tax_year: None`) with TWO different
/// promoted years in range must co-emit BOTH `form_8275_{year}.txt` files — never a bare,
/// collision-prone `form_8275.txt` that a second promoted year would silently overwrite.
#[test]
fn all_years_snapshot_writes_one_8275_txt_per_promoted_year() {
    let dir = tempfile::tempdir().unwrap();
    let vault = vault_with_two_promoted_years(dir.path(), 2024, 2017);
    let out = dir.path().join("export_out");

    cmd::admin::export_snapshot(&vault, &pp(), &out, None, None)
        .expect("an all-years snapshot with two complete promoted years must succeed");

    assert!(
        out.join("form_8275_2024.txt").exists(),
        "the 2024 promoted year's disclosure is co-emitted"
    );
    assert!(
        out.join("form_8275_2017.txt").exists(),
        "the 2017 promoted year's disclosure is co-emitted"
    );
    assert!(
        !out.join("form_8275.txt").exists(),
        "the all-years dump never uses the bare, collision-prone name"
    );
}

// ════════════════════════════════════════════════════════════════════════════════════════════════
// Defensive Filing Wizard sub-2, Task 3 (arch-C-1/m-new-1) — the EXPORT chokepoint extraction.
//
// Step 1/2: a TWO-ARM characterization of the shipped, self-opening `export_irs_pdf`, pinned BEFORE the
// `&Session` extraction so re-running it (unchanged) AFTER the refactor proves the thin opener emits the
// IDENTICAL packet. Arm (a) is the crypto-slice dispatch (no `return_inputs` row); arm (b) is the
// full-return dispatch (`return_inputs::exists(year)` — `admin.rs:373`) on the SAME underlying vault.
// Pinning arm (b) is load-bearing (arch-m-new-1): a slice-only `_from_session` would red ONLY this arm.
// ════════════════════════════════════════════════════════════════════════════════════════════════

/// Arm (a): the crypto-slice dispatch (`vault_with_promoted_disposal_via_cli` — no `return_inputs` row
/// for `T14_YEAR`). Pins the EXACT emitted file set and every `IrsPdfReport` field observed off the
/// shipped (pre-extraction) `export_irs_pdf`.
#[test]
fn characterization_crypto_slice_export_pins_the_shipped_file_set_and_report() {
    let dir = tempfile::tempdir().unwrap();
    let vault = vault_with_promoted_disposal_via_cli(dir.path());
    let out = dir.path().join("export_out");

    let report = cmd::admin::export_irs_pdf(&vault, &pp(), &out, T14_YEAR, &[], None)
        .expect("the crypto-slice arm exports cleanly");

    let mut names: Vec<String> = std::fs::read_dir(&out)
        .unwrap()
        .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
        .collect();
    names.sort();
    assert_eq!(
        names,
        vec![
            "basis_methodology.txt".to_string(),
            "f8949.pdf".to_string(),
            "form_1040_capgains.pdf".to_string(),
            "form_8275.pdf".to_string(),
            "form_8275.txt".to_string(),
            "schedule_d.pdf".to_string(),
        ],
        "the crypto-slice arm's emitted file set is pinned exactly — the Approach-B experimental \
         notice is INTERFACE-only (stderr) and must NEVER appear as a written file, even though this \
         fixture's vault has a live promoted tranche"
    );

    assert_eq!(report.f8949_path, Some(out.join("f8949.pdf")));
    assert_eq!(report.schedule_d_path, Some(out.join("schedule_d.pdf")));
    assert_eq!(report.tax_year, T14_YEAR);
    assert_eq!(report.unresolved_hard, 0);
    assert_eq!(report.broker_reported_rows, 1);
    assert!(
        !report.watermarked,
        "a real (non-pseudo) ledger exports CLEAN"
    );
    assert_eq!(report.schedule_se_path, None);
    assert!(!report.se_below_floor);
    assert_eq!(report.se_addl_medicare, None);
    assert!(!report.se_income_without_profile);
    assert_eq!(report.form_8283_path, None);
    assert!(!report.form_8283_needs_review);
    assert_eq!(report.form_8283_section_b, None);
    assert_eq!(
        report.form_1040_path,
        Some(out.join("form_1040_capgains.pdf"))
    );
    assert!(report.form_1040_filled_7a);
    assert!(!report.form_1040_loss);
    assert_eq!(report.form_8275_path, Some(out.join("form_8275.pdf")));
    assert!(
        report.full_return_paths.is_empty(),
        "the crypto-slice arm never populates the full-return fields"
    );
    assert_eq!(report.full_return_manifest, None);
    assert!(
        !report.forms_ignored_full_return,
        "the crypto-slice arm always honors --forms"
    );
    assert!(
        report.experimental_notice_active,
        "this fixture's vault has a live promoted tranche — Approach-B is in use"
    );
}

/// Arm (b) — ★ arch-m-new-1: the SAME underlying vault, but with a `return_inputs` row planted for
/// `T14_YEAR` so `export_irs_pdf` DISPATCHES to `export_full_return` (`admin.rs:373`). Pins the exact
/// emitted file set (sequence-prefixed packet + the two named-content files + the manifest) and every
/// `IrsPdfReport` field. Pinning THIS arm is what proves the retained dispatch survives extraction — a
/// slice-only `_from_session` would still pass arm (a) but red HERE.
#[test]
fn characterization_full_return_export_pins_the_shipped_file_set_and_report() {
    let dir = tempfile::tempdir().unwrap();
    let vault = vault_with_promoted_disposal_via_cli(dir.path());
    plant_full_return_ri(&vault, T14_YEAR);
    let out = dir.path().join("export_out");

    let report = cmd::admin::export_irs_pdf(&vault, &pp(), &out, T14_YEAR, &[], None)
        .expect("the full-return arm exports cleanly");

    let mut names: Vec<String> = std::fs::read_dir(&out)
        .unwrap()
        .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
        .collect();
    names.sort();
    assert_eq!(
        names,
        vec![
            "00_f1040.pdf".to_string(),
            "12A_f8949.pdf".to_string(),
            "12_schedule_d.pdf".to_string(),
            "92_f8275.pdf".to_string(),
            "basis_methodology.txt".to_string(),
            "form_8275.txt".to_string(),
            "manifest.txt".to_string(),
        ],
        "the full-return arm's emitted file set is pinned exactly — the Approach-B experimental \
         notice is INTERFACE-only (stderr) and must NEVER appear as a written file, even though this \
         fixture's vault has a live promoted tranche"
    );

    // The crypto-slice-only fields are ALWAYS absent on the full-return arm — its 8275 rides inside
    // `full_return_paths` (sequence-prefixed `92_f8275.pdf`), never the bare `form_8275_path`.
    assert_eq!(report.f8949_path, None);
    assert_eq!(report.schedule_d_path, None);
    assert_eq!(report.tax_year, T14_YEAR);
    assert_eq!(report.unresolved_hard, 0);
    assert_eq!(report.broker_reported_rows, 0);
    assert!(
        !report.watermarked,
        "a real (non-pseudo) ledger exports CLEAN"
    );
    assert_eq!(report.schedule_se_path, None);
    assert!(!report.se_below_floor);
    assert_eq!(report.se_addl_medicare, None);
    assert!(!report.se_income_without_profile);
    assert_eq!(report.form_8283_path, None);
    assert_eq!(report.form_1040_path, None);
    assert!(!report.form_1040_filled_7a);
    assert!(!report.form_1040_loss);
    assert_eq!(report.form_8275_path, None);
    assert!(
        !report.forms_ignored_full_return,
        "an EMPTY --forms slice is never reported as ignored"
    );
    assert_eq!(
        report.full_return_paths,
        vec![
            out.join("00_f1040.pdf"),
            out.join("12_schedule_d.pdf"),
            out.join("12A_f8949.pdf"),
            out.join("92_f8275.pdf"),
        ],
        "the full-return packet's paths are pinned exactly, in this order"
    );
    assert_eq!(report.full_return_manifest, Some(out.join("manifest.txt")));
    assert!(
        report.experimental_notice_active,
        "this fixture's vault has a live promoted tranche — Approach-B is in use"
    );
}

// ════════════════════════════════════════════════════════════════════════════════════════════════
// Defensive Filing Wizard sub-2, Task 3 (DFW-D11) — the fold-diff export year-set. (The composed
// `plan_export`/`apply_export` chokepoint trio these also covered was deleted in 0.13.0 with the wizard;
// `flagged_years` itself survives and is what `btctax defensive status` reports.)
// ════════════════════════════════════════════════════════════════════════════════════════════════

/// Seed ONE wallet's worth of "documented lot + a promoted 2016-window tranche + a LATER donation that
/// HIFO-reorders which lot is drawn" — the building block for the removal-reordered-prior-year KATs
/// below. The tranche is NEVER disposed (no `Dispose` at all) — WITH the promote the donation drains the
/// tranche (its floor is FAR above the documented lot's $1 cost, so HIFO draws it FIRST); WITHOUT it, the
/// tranche's filed $0 basis sorts LAST, so the donation instead drains the documented lot — a pure
/// REMOVAL-leg diff with NO promoted DISPOSAL leg in `donation_year` at all (mirrors the core-level
/// `prior_donation_only_reorder`, `btctax-core/tests/kat_promote.rs`, at CLI-driver altitude with REAL
/// verbs). `suffix` keeps refs and the wallet distinct across multiple calls against the SAME vault (the
/// two-live-promote KAT below).
fn seed_removal_reorder(vault: &Path, suffix: &str, donation_year: i32) -> WalletId {
    let w = WalletId::SelfCustody {
        label: format!("t3-flagged-years-{suffix}"),
    };
    let buy = LedgerEvent {
        id: EventId::import(Source::Coinbase, SourceRef::new(format!("T3-BUY-{suffix}"))),
        utc_timestamp: datetime!(2015-06-01 0:00 UTC),
        original_tz: UtcOffset::UTC,
        wallet: Some(w.clone()),
        payload: EventPayload::Acquire(Acquire {
            sat: 100_000_000,
            usd_cost: dec!(1), // far below ANY real 2016 BTC close — guarantees the HIFO flip
            fee_usd: dec!(0),
            basis_source: BasisSource::ExchangeProvided,
        }),
    };
    let give_rf = format!("T3-GIVEOUT-{suffix}");
    let give_ts = time::Date::from_calendar_date(donation_year, time::Month::June, 1)
        .unwrap()
        .with_hms(0, 0, 0)
        .unwrap()
        .assume_utc();
    let give = LedgerEvent {
        id: EventId::import(Source::Coinbase, SourceRef::new(give_rf.clone())),
        utc_timestamp: give_ts,
        original_tz: UtcOffset::UTC,
        wallet: Some(w.clone()),
        payload: EventPayload::TransferOut(TransferOut {
            sat: 40_000_000,
            fee_sat: None,
            dest_addr: None,
            txid: None,
        }),
    };
    {
        let mut s = Session::open(vault, &pp()).unwrap();
        append_import_batch(s.conn(), &[buy, give]).unwrap();
        s.save().unwrap();
    } // `s` (and its VaultLock) drops HERE — declare_tranche below opens its OWN session.

    let tranche_id = cmd::tranche::declare_tranche(
        vault,
        &pp(),
        40_000_000,
        w.clone(),
        date!(2016 - 01 - 01),
        date!(2016 - 03 - 31),
        now(),
    )
    .unwrap();
    cmd::promote::promote_tranche(
        vault,
        &pp(),
        &tranche_id.canonical(),
        ProvenanceKind::Purchase,
        format!("cash P2P purchase {suffix}, no records; window bounded on-chain"),
        Some(PROMOTE_ACK_PHRASE),
        now(),
    )
    .unwrap();

    cmd::reconcile::reclassify_outflow(
        vault,
        &pp(),
        &EventId::import(Source::Coinbase, SourceRef::new(give_rf)).canonical(),
        OutflowClass::Donate {
            appraisal_required: false,
        },
        dec!(5_000),
        None,
        None,
        now(),
    )
    .unwrap();

    w
}

/// ★ Task 3 Step 4: `flagged_years` (the fold-diff export year-set) catches a REMOVAL-reordered prior
/// year with NO promoted disposal leg at all — `promoted_filing_years` (the disposal-legs-only 8275-gate
/// enumeration) must NOT. Mutation: define the export set as `promoted_filing_years` alone → 2025 drops
/// → reds.
///
/// ★ whole-branch arch M-2: the complementary `promoted_filing_years` NEGATIVE assertion moved in-crate
/// (`chokepoint::tests::promoted_filing_years_enumerates_promoted_disposal_legs_only`) — it was the ONLY
/// caller forcing that fn onto btctax-cli's public API.
#[test]
fn flagged_years_includes_a_removal_reordered_prior_year_with_no_promoted_disposal() {
    let dir = tempfile::tempdir().unwrap();
    let vault = dir.path().join("vault.pgp");
    cmd::init::run(&vault, &pp(), &dir.path().join("k.asc")).unwrap();
    seed_removal_reorder(&vault, "a", 2025);

    let session = Session::open(&vault, &pp()).unwrap();
    let (events, state, cfg) = session.load_events_and_project().unwrap();
    let tables = btctax_adapters::BundledTaxTables::load();
    let current = 2026; // matches now()'s injected tax year (the recorded promote/donation's clock)

    let years = flagged_years(&events, &state, session.prices(), &tables, &cfg, current);
    assert!(
        years.contains(&2025),
        "the removal-only reorder (no promoted disposal leg) must be flagged: {years:?}"
    );

    // ★ 0.13.0: the composed `plan_export.years` assertions that stood here went with the multi-year
    // export trio. `flagged_years` itself — the year set this test actually pins, and the one
    // `btctax defensive status` reports — is unchanged, and the mutation above still kills it.
    assert!(
        !years.contains(&current),
        "the current year is not a REORDERED prior year and must not be flagged as one: {years:?}"
    );
}

/// ★ whole-branch tax I-1 — the DECLARE side of the DFW-D11 export set. A `$0` `DeclareTranche` with NO
/// promote ANYWHERE still changes the shortfall year's FILED forms: `make_disposal_legs`
/// (`project/fold.rs:~128`) splits the disposal's full net proceeds PRO-RATA across `consumed`, so adding
/// the tranche re-splits them, gives the previously-uncovered share its OWN Form 8949 row (`acquired_at =
/// window_end`, which also moves the Schedule D short-/long-term split), and clears the Hard
/// `UncoveredDisposal` that made the year not-computable at all. So `flagged_years` MUST carry that prior
/// year on the `$0` branch, exactly as it does on the promote branch — it is what `btctax defensive
/// status` reports as a year needing a re-export.
///
/// Mutation: revert `flagged_years` to the promote-only union (iterate `live_promote_ids` alone) — this
/// vault has NO live promote, so the set collapses to EMPTY and 2024 drops out of the assertion → reds.
#[test]
fn flagged_years_includes_the_prior_year_a_zero_dollar_declare_alone_fixed() {
    let dir = tempfile::tempdir().unwrap();
    let vault = dir.path().join("vault.pgp");
    cmd::init::run(&vault, &pp(), &dir.path().join("k.asc")).unwrap();

    let w = WalletId::SelfCustody {
        label: "t-declare-only".into(),
    };
    // A 2024 sale of coins with NO acquisition record anywhere → a Hard `UncoveredDisposal`: the exact
    // "a 2024 sale with no records" journey the wizard's `$0` branch exists to close.
    {
        let mut s = Session::open(&vault, &pp()).unwrap();
        append_import_batch(
            s.conn(),
            &[LedgerEvent {
                id: EventId::import(Source::Coinbase, SourceRef::new("DECLARE-ONLY-SELL")),
                utc_timestamp: datetime!(2024-06-01 0:00 UTC),
                original_tz: UtcOffset::UTC,
                wallet: Some(w.clone()),
                payload: EventPayload::Dispose(Dispose {
                    sat: 40_000_000,
                    usd_proceeds: dec!(20_000),
                    fee_usd: dec!(0),
                    kind: DisposeKind::Sell,
                }),
            }],
        )
        .unwrap();
        s.save().unwrap();
    } // the VaultLock drops HERE — `declare_tranche` opens its OWN session.

    // The `$0` declare that covers it — and NOTHING else (no `promote_tranche` call at all).
    cmd::tranche::declare_tranche(
        &vault,
        &pp(),
        40_000_000,
        w,
        date!(2016 - 01 - 01),
        date!(2016 - 03 - 31),
        now(),
    )
    .unwrap();

    let session = Session::open(&vault, &pp()).unwrap();
    let (events, state, cfg) = session.load_events_and_project().unwrap();
    let tables = btctax_adapters::BundledTaxTables::load();
    let current = 2026;

    assert!(
        state.promoted_origins.is_empty(),
        "fixture: this vault holds a $0 declare and NO promote — the promote-only union must be empty"
    );

    let years = flagged_years(&events, &state, session.prices(), &tables, &cfg, current);
    assert!(
        years.contains(&2024),
        "the year the $0 declare re-filed (proceeds re-split + UncoveredDisposal cleared) must be \
         flagged, exactly as a promote's reorder year is: {years:?}"
    );
}

/// ★ whole-branch r2 tax M-1 — a promoted tranche whose declare-void the ENGINE made INERT must stay in
/// the DFW-D11 export union. `project::resolve.rs`'s BG-D9 deferred adjudication holds a `DeclareTranche`
/// IN FORCE (raising a `DecisionConflict` instead of applying the void) whenever a LIVE `PromoteTranche`
/// still references it — "void the promote to revert the tranche to $0, or void both to drop it". But
/// `conservative::live_declare_ids` filtered on the NAIVE `voided_decision_targets` membership ("some
/// `VoidDecisionEvent` NAMES this id"), so it dropped exactly that still-in-force, still-PROMOTED tranche
/// from the declare half of the union.
///
/// This is the END-TO-END half of the pin, off a REAL vault: it establishes that the engine genuinely
/// DOES hold such a tranche in `state.promoted_origins` (the premise the fix reads), and that 2024
/// survives into `flagged_years`. It is deliberately NOT the mutation-killer: on this shape the two
/// halves of the union COINCIDE, because the promote-half's shadow fold removes the promote, which
/// un-defers the very void and drops the tranche anyway — so reverting `live_declare_ids` to the naive
/// filter leaves 2024 flagged by the promote half. That coincidence is a property of the CURRENT resolver,
/// not a guarantee, which is exactly why the declare half's own rule is pinned directly by the white-box
/// `btctax_core::conservative::tests::live_declare_ids_keeps_a_tranche_whose_void_the_engine_held_inert`
/// (mutation-verified there).
///
/// The void is a hand-crafted raw event on purpose: `reconcile void` REFUSES this shape at record time
/// (`reconcile.rs:~248`), so it is not product-reachable — the same "pinned anyway, as defense in depth"
/// precedent as
/// `declare_tranche_cli.rs::handcrafted_void_of_effective_alloc_then_tranche_admits_and_survives_via_path_a`.
/// The net-zero disposal (gross $500, fee $500) keeps the fixture's filed numbers trivially stable:
/// `conservative_promote::clamped_leg_basis` bounds the estimate at `net − documented = $0`, so the leg
/// files $0 basis / $0 gain with or without the promote.
#[test]
fn flagged_years_keeps_a_promoted_tranche_whose_declare_void_the_engine_made_inert() {
    let dir = tempfile::tempdir().unwrap();
    let vault = dir.path().join("vault.pgp");
    cmd::init::run(&vault, &pp(), &dir.path().join("k.asc")).unwrap();

    // A 2024 sale whose fee consumes the whole gross → NET proceeds $0.
    {
        let mut s = Session::open(&vault, &pp()).unwrap();
        append_import_batch(
            s.conn(),
            &[imp(
                "INERT-VOID-SELL",
                datetime!(2024-06-01 0:00 UTC),
                EventPayload::Dispose(Dispose {
                    sat: 40_000_000,
                    usd_proceeds: dec!(500),
                    fee_usd: dec!(500),
                    kind: DisposeKind::Sell,
                }),
            )],
        )
        .unwrap();
        s.save().unwrap();
    } // the VaultLock drops HERE — `declare_tranche` opens its OWN session.

    let tranche_id = cmd::tranche::declare_tranche(
        &vault,
        &pp(),
        40_000_000,
        wallet(),
        date!(2016 - 01 - 01),
        date!(2016 - 03 - 31),
        now(),
    )
    .unwrap();
    cmd::promote::promote_tranche(
        &vault,
        &pp(),
        &tranche_id.canonical(),
        ProvenanceKind::Purchase,
        "cash P2P purchase, no records; window bounded on-chain".into(),
        Some(PROMOTE_ACK_PHRASE),
        now(),
    )
    .unwrap();

    // The hand-crafted void of the DECLARE (the CLI verb refuses this shape at record time).
    {
        let mut s = Session::open(&vault, &pp()).unwrap();
        append_decision(
            s.conn(),
            EventPayload::VoidDecisionEvent(btctax_core::event::VoidDecisionEvent {
                target_event_id: tranche_id.clone(),
            }),
            now(),
            UtcOffset::UTC,
            None,
        )
        .unwrap();
        s.save().unwrap();
    }

    let session = Session::open(&vault, &pp()).unwrap();
    let (events, state, cfg) = session.load_events_and_project().unwrap();
    let tables = btctax_adapters::BundledTaxTables::load();

    // The ENGINE's verdict: the void is INERT — the promote is live, so the tranche stays in force.
    assert!(
        state.promoted_origins.contains(&tranche_id),
        "fixture: the engine must hold the voided tranche IN FORCE via its live promote (an inert void), \
         else this KAT is testing nothing"
    );

    let years = flagged_years(&events, &state, session.prices(), &tables, &cfg, 2026);
    assert!(
        years.contains(&2024),
        "a tranche the ENGINE holds in force must stay in the export year-set union — a naive \
         'some void names it' filter would silently shorten the packet set: {years:?}"
    );
}