btctax-core 0.11.0

Offline US Bitcoin tax engine — per-lot cost basis, realized gains, and IRS-form projection (part of btctax).
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
use crate::conservative_promote::{clamped_leg_basis, estimate_share_of, PromoteSet};
use crate::conventions::{
    is_long_term, long_term_default_acquired, round_cents, split_pro_rata, Sat, TaxDate, Usd,
    TRANSITION_DATE,
};
use crate::event::{BasisSource, DisposeKind};
use crate::identity::{EventId, LotId};
use crate::price::{fmv_of, PriceProvider};
use crate::project::pools::{pool_key, Consumed, PoolKey, PoolSet};
use crate::project::resolve::{sort_canonical, Eff, ElectionRec, Op, Resolution};
use crate::project::transition;
use crate::state::{
    BlockerKind, Disposal, DisposalLeg, FoldStats, GiftZone, IncomeRecord, LedgerState, Lot,
    PendingLeg, PendingTransfer, Removal, RemovalKind, RemovalLeg, ShortfallRecord, Term,
};
use crate::{FeeTreatment, LotMethod, ProjectionConfig};
use std::collections::BTreeMap;

/// Read-only context threaded through the PASS-2 fold: the projection config plus the resolved
/// forward method elections (§A.5(a)) and per-disposal named-lot selections (§A.4). Carried as ONE
/// borrow so `fold_event` (and `transition::universal_snapshot`, which reuses it) stay in lock-step.
pub(crate) struct FoldCtx<'a> {
    pub config: &'a ProjectionConfig,
    pub elections: &'a [ElectionRec],
    pub selections: &'a BTreeMap<EventId, Vec<crate::event::LotPick>>,
    /// BG-D4: the live promotion set (`Resolution.promotes`), keyed by a promoted leg's
    /// `lot_id.origin_event_id`. Threaded so `make_disposal_legs` (and, via `consume_fee`, the fee
    /// mini-disposition) can clamp a promoted tranche leg's estimate basis. Carried at EVERY FoldCtx
    /// site (incl. `universal_snapshot`) so no fold path silently sees an un-clamped basis.
    pub promotes: PromoteSet,
}

/// The lot-identification method applicable to a disposal on `wallet` at `date`:
/// pre-2025 (Universal pool) → the declared `pre2025_method`; post-2025 (Wallet pool) → the SHARED
/// wallet-aware resolver `resolve::resolve_election` (§A.5(a), two independent tiers: latest in-force
/// election SCOPED to `wallet`, else latest in-force GLOBAL election, else the HIFO default).
/// `None ⇒ Hifo` here — the app's realistic no-election default (most elected method; §reconcile-defaults).
/// This is the ONLY method-resolution path in the fold; `disposal_compliance` calls the same resolver.
fn applicable_method(
    date: TaxDate,
    wallet: &crate::identity::WalletId,
    ctx: &FoldCtx,
) -> LotMethod {
    if date < TRANSITION_DATE {
        ctx.config.pre2025_method
    } else {
        crate::project::resolve::resolve_election(date, wallet, ctx.elections)
            .map(|e| e.method)
            .unwrap_or(LotMethod::Hifo)
    }
}

/// Consume a method-honoring op's principal: the applicable method plus any `LotSelection` for `ev`.
/// On a selection-validation failure → hard `LotSelectionInvalid` (carrying the disposal id + reason);
/// consumption falls back to method order so Σsat conservation holds and the hard blocker gates tax.
/// (Selections are an empty map this task; the fallback path is exercised once Task 4 populates them.)
#[allow(clippy::too_many_arguments)]
fn consume_principal(
    pools: &mut PoolSet,
    key: &PoolKey,
    need: Sat,
    date: TaxDate,
    wallet: &crate::identity::WalletId,
    ctx: &FoldCtx,
    st: &mut LedgerState,
    ev: &EventId,
) -> (Vec<Consumed>, Sat) {
    let method = applicable_method(date, wallet, ctx);
    let selection = ctx.selections.get(ev).map(|v| v.as_slice());
    let r = pools.consume(key, need, method, selection);
    if let Some(reason) = r.selection_error {
        st.add_blocker(BlockerKind::LotSelectionInvalid, Some(ev.clone()), reason);
    }
    (r.consumed, r.shortfall)
}

/// TP4 term for a consumed fragment given the disposition date (gain side / no-dual uses gain_hp_start).
fn term_for(start: TaxDate, disposed: TaxDate) -> Term {
    if is_long_term(start, disposed) {
        Term::LongTerm
    } else {
        Term::ShortTerm
    }
}

/// §7.4: emit the pre-2025 disposal advisory ONCE (a Dispose/Removal consumed the Universal pool),
/// naming the DECLARED `pre2025_method`. Pre-2025 ⇔ the disposition routed through `PoolKey::Universal`.
/// `attested` branches the advisory text (D2): unattested → actionable warning; attested → informational.
/// Severity is always Advisory (never gates `compute_tax_year`).
fn note_pre2025_once(
    st: &mut LedgerState,
    date: TaxDate,
    ev: &EventId,
    method: LotMethod,
    attested: bool,
) {
    if date < TRANSITION_DATE
        && !st
            .blockers
            .iter()
            .any(|b| b.kind == BlockerKind::Pre2025MethodNote)
    {
        let m = match method {
            LotMethod::Fifo => "FIFO",
            LotMethod::Lifo => "LIFO",
            LotMethod::Hifo => "HIFO",
        };
        let detail = if attested {
            format!(
                "pre-2025 lots reconstructed under your DECLARED + ATTESTED filed method {m} (§7.4); \
                 carryforward basis into 2025 reflects that method"
            )
        } else {
            format!(
                "pre-2025 lots reconstructed under {m} (FIFO is the §7.4 legal default); \
                 you have NOT declared your filed pre-2025 lot method — if your filed pre-2025 returns \
                 used a different method your carryforward basis may differ. \
                 Declare it: config --set-pre2025-method <m> --attest-pre2025-method"
            )
        };
        st.add_blocker(BlockerKind::Pre2025MethodNote, Some(ev.clone()), detail);
    }
}

/// Build disposal legs from consumed fragments and a TOTAL net proceeds amount, allocated pro-rata by sat
/// (remainder-takes-the-rest so Σproceeds is exact). Dual-basis gift logic (TP11) is added in Task 10;
/// here every leg is the simple `gift_zone = None` path.
fn make_disposal_legs(
    consumed: &[Consumed],
    total_net_proceeds: Usd,
    disposed: TaxDate,
    st: &mut LedgerState,
    ev: &EventId,
    ev_pseudo: bool,
    promotes: &PromoteSet,
) -> Vec<DisposalLeg> {
    let total_sat: i64 = consumed.iter().map(|c| c.sat).sum();
    let mut legs = Vec::new();
    let mut allocated = Usd::ZERO;
    for (i, c) in consumed.iter().enumerate() {
        let proceeds = if i + 1 == consumed.len() {
            total_net_proceeds - allocated
        } else {
            let (p, _) = split_pro_rata(total_net_proceeds, c.sat, total_sat);
            allocated += p;
            p
        };
        if c.basis_pending {
            // FMV-missing income / unknown-basis gift in this lot's history → gate the gain (§7.3).
            st.add_blocker(
                BlockerKind::FmvMissing,
                Some(ev.clone()),
                "disposal consumes a basis-pending lot",
            );
        }
        // Task 10: four-zone §1015(a) dual-basis computation (TP11).
        // When `c.dual = false` (no dual basis): simple single-carryover path.
        // When `c.dual = true` (dual-basis gift, FMV-at-gift < donor-basis at gift date):
        //   Gain zone  : proceeds > gain_basis  → basis = gain_basis, term tacks (gain_hp_start).
        //   Loss zone  : proceeds < loss_basis  → basis = loss_basis, HP from gift date (loss_hp_start).
        //   NoGainNoLoss: otherwise             → reported basis = proceeds, gain = 0, term from gain_hp_start.
        // Note: in the NoGainNoLoss zone, `lot.usd_basis` was already reduced by pro-rata `gain_basis`
        // on consume (pools.rs), so Σbasis is conserved exactly even though we report basis = proceeds.
        // acquired_at is set from the SAME HP-start branch that selects term_for's first arg,
        // so it can never contradict the leg's ST/LT classification [R0-C1].
        let (basis, gain, term, gift_zone, acquired_at) = if c.dual {
            let loss_basis = c.loss_basis.expect("dual=true implies loss_basis is Some");
            if proceeds > c.gain_basis {
                // Gain zone: basis = gain_basis (tacks, gain_hp_start).
                let t = term_for(c.gain_hp_start, disposed);
                (
                    c.gain_basis,
                    round_cents(proceeds - c.gain_basis),
                    t,
                    Some(GiftZone::Gain),
                    c.gain_hp_start, // tacked donor date
                )
            } else if proceeds < loss_basis {
                // Loss zone: basis = FMV-at-gift (loss_basis), HP from gift date.
                let t = term_for(c.loss_hp_start, disposed);
                (
                    loss_basis,
                    round_cents(proceeds - loss_basis),
                    t,
                    Some(GiftZone::Loss),
                    c.loss_hp_start, // gift date — loss basis does NOT tack (Pub 551)
                )
            } else {
                // NoGainNoLoss zone: reported basis = proceeds → gain = 0; term from gain_hp_start.
                let t = term_for(c.gain_hp_start, disposed);
                (
                    proceeds,
                    Usd::ZERO,
                    t,
                    Some(GiftZone::NoGainNoLoss),
                    c.gain_hp_start,
                )
            }
        } else {
            // BG-D4: a promoted tranche leg files the floor as basis but NEVER a loss off the estimate —
            // clamp the estimate component against the proceeds remaining after the documented component.
            // `promotes.get(..)` is `None` for a non-promoted lot ⇒ `clamped_leg_basis` returns
            // `c.gain_basis` unchanged (byte-identical to the pre-BG-D4 path). `proceeds` is this leg's
            // pro-rata share of `net` (the cent-remainder-takes-rest split above). A tranche lot never
            // enters the dual arm (`rehome_onto_lot` never promotes `dual_loss_basis` None→Some), so this
            // non-dual-arm placement is complete. The pool's `usd_basis` is still reduced by the FULL
            // `gain_basis` on consume (pools.rs); the unclaimed floor evaporates — the §1015 NoGainNoLoss
            // precedent (reported basis ≠ pool basis) makes this legal.
            let basis = clamped_leg_basis(
                promotes.get(&c.lot_id.origin_event_id),
                c.sat,
                c.gain_basis,
                proceeds,
            );
            let t = term_for(c.gain_hp_start, disposed);
            (
                basis,
                round_cents(proceeds - basis),
                t,
                None,
                c.gain_hp_start,
            )
        };
        legs.push(DisposalLeg {
            lot_id: c.lot_id.clone(),
            sat: c.sat,
            proceeds,
            basis,
            gain,
            term,
            basis_source: c.basis_source,
            gift_zone,
            acquired_at,
            wallet: c.wallet.clone(),
            // [R0-C1] leg is [PSEUDO] if its BASIS traces to a pseudo lot (`c.pseudo`) OR the disposal
            // event itself is synthetic (`ev_pseudo`). A REAL Sell on a pseudo $0-basis lot ⇒ flagged.
            pseudo: c.pseudo || ev_pseudo,
        });
    }
    legs
}

/// Build removal legs from consumed fragments and a TOTAL FMV amount, allocated pro-rata by sat
/// (remainder-takes-the-rest so Σfmv is exact). Zero recognized gain (TP10): no Disposal emitted.
/// Returns (legs, donor_acquired_at) where donor_acquired_at is the first non-None across lots.
fn make_removal_legs(
    consumed: &[Consumed],
    total_fmv: Usd,
    removed: TaxDate,
    st: &mut LedgerState,
    ev: &EventId,
    ev_pseudo: bool,
    promotes: &PromoteSet,
) -> (Vec<RemovalLeg>, Option<TaxDate>) {
    let total_sat: i64 = consumed.iter().map(|c| c.sat).sum();
    let mut legs = Vec::new();
    let mut allocated = Usd::ZERO;
    let mut donor = None;
    for (i, c) in consumed.iter().enumerate() {
        if c.basis_pending {
            st.add_blocker(
                BlockerKind::UnknownBasisInbound,
                Some(ev.clone()),
                "removal consumes a basis-pending lot",
            );
        }
        let fmv = if i + 1 == consumed.len() {
            total_fmv - allocated
        } else {
            let (f, _) = split_pro_rata(total_fmv, c.sat, total_sat);
            allocated += f;
            f
        };
        donor = donor.or(c.donor_acquired_at);
        // BG-D11: a removal leg drawn from a PROMOTED lot carries its DOCUMENTED component ONLY — the
        // ESTIMATE share EVAPORATES. A removal recognizes no gain (§170 for a donation, §1015 for a gift),
        // so there is nothing to clamp the estimate INTO; the estimate must never fund a charitable
        // deduction or an outbound §1015 carryover. Reuse the exact Task-4/5 clamp (`clamped_leg_basis`)
        // with `net_proceeds_share = $0` — a removal's LITERAL proceeds: the estimate can be absorbed by
        // nothing, so the clamp returns exactly the documented component (`gain_basis − estimate_share`),
        // floored at $0 for any cent-scale rounding residue, while a GENUINE documented fee carry already
        // baked into `c.gain_basis` (a prior self-transfer's `rehome_onto_lot`) is preserved unchanged.
        // `promotes.get(..)` is `None` for a non-promoted lot ⇒ identity (returns `c.gain_basis`
        // unchanged, byte-identical to the pre-BG-D11 path). This ONE site funds every downstream §170(e)
        // consumer by construction — the fold's `claimed_deduction`, the full-return engine's
        // `crypto_charitable_gifts` (Schedule A line 12), and Form 8283's `cost_basis` column — none is
        // patched separately. The pool's `usd_basis` is still debited by the FULL `gain_basis` on consume
        // (pools.rs `take_from`); the unclaimed floor evaporates — the §1015 NoGainNoLoss precedent
        // (reported basis ≠ pool basis) makes this legal. A removal never enters the dual arm.
        let basis = clamped_leg_basis(
            promotes.get(&c.lot_id.origin_event_id),
            c.sat,
            c.gain_basis,
            Usd::ZERO,
        );
        legs.push(RemovalLeg {
            lot_id: c.lot_id.clone(),
            sat: c.sat,
            basis,
            fmv_at_transfer: fmv,
            // acquired_at MUST be the SAME HP-start argument fed to `term_for` below so it can never
            // contradict `term`. Removals recognize no gain/loss → no loss-zone branching (unlike
            // disposals): this is always `gain_hp_start` (the tacked donor date for received gifts,
            // §1223). [D1/R0-M2]
            term: term_for(c.gain_hp_start, removed),
            basis_source: c.basis_source,
            acquired_at: c.gain_hp_start,
            pseudo: c.pseudo || ev_pseudo, // [R0-C1] a pseudo lot gifted/donated flags the removal leg
        });
    }
    (legs, donor)
}

/// Carried basis of the burned fee-sats, to be RE-HOMED onto a surviving destination lot / removal leg /
/// disposal leg under TP8 (c) so the FULL basis carries (C1) — EXCEPT a promoted tranche's ESTIMATE
/// component, which `consume_fee` withholds before it ever reaches this struct (BG-D4 fee-evaporation:
/// only the DOCUMENTED remainder of a promoted fragment carries; C1 still holds for whatever `consume_fee`
/// decided IS the fee-sat basis). Under (b) this is empty (basis rode the mini-disposition).
#[derive(Default)]
struct FeeCarry {
    gain_basis: Usd,
    loss_basis: Option<Usd>,
}

impl FeeCarry {
    /// Re-home the fee-sat basis onto the surviving destination lot (C1: full basis carries).
    /// `gain_basis` always carries onto `lot.usd_basis` (C1 invariant; must not be dropped).
    /// `loss_basis` carries onto `lot.dual_loss_basis` ONLY when the survivor is ALREADY a
    /// dual-basis lot (`Some(existing)` → add to existing). When the survivor is non-dual
    /// (`None`), the `loss_basis` fragment is dropped instead of promoting the lot to `Some`:
    /// promoting would set `dual_loss_basis.is_some() == true`, causing a later disposition to
    /// route through the §1015(a) four-zone logic (`make_disposal_legs` keys on this field)
    /// and misclassify a normal purchased/transferred lot as a received-gift dual-basis lot —
    /// a worse error than the cents-scale conservative loss-basis understatement that results
    /// from the drop. Conservative: future loss-zone basis understated by fee-cents; gain basis
    /// fully conserved (C1 intact).
    fn rehome_onto_lot(&self, lot: &mut Lot) {
        lot.usd_basis += self.gain_basis;
        if let Some(l) = self.loss_basis {
            // Add to existing dual_loss_basis only; when None (non-dual survivor) the fragment
            // is dropped — promoting None → Some would misroute a later disposition through the
            // §1015(a) four-zone logic (see doc comment above for full rationale).
            if let Some(dl) = lot.dual_loss_basis.as_mut() {
                *dl += l;
            }
        }
    }

    /// Re-home the fee-sat gain basis onto the last removal leg (C1: full basis carries to donee).
    /// Note: `loss_basis` is a donor's private tax attribute and does not carry onto removal legs.
    fn rehome_onto_removal_leg(&self, leg: &mut RemovalLeg) {
        leg.basis += self.gain_basis;
    }

    /// Re-home the fee-sat gain basis onto the last disposal leg (I-1: Dispose+fee_sat, TP8 (c)).
    /// Under (c): adds gain_basis to the reported leg basis → gain decreases by carry amount.
    /// Under (b): carry is empty (gain_basis = 0) so this is a no-op; the fee-sat basis rode the
    /// mini-disposition emitted by consume_fee instead.
    fn rehome_onto_disposal_leg(&self, leg: &mut DisposalLeg) {
        leg.basis += self.gain_basis;
        leg.gain = round_cents(leg.proceeds - leg.basis);
    }
}

/// Consume `fee_sat` FIFO from the source pool, record them in the FR9 fee-sat home, and (per config)
/// either return their carried basis for re-homing (c) or emit a mini-disposition recognition record (b).
/// §7.1 totality: a fee shortfall raises `uncovered_disposal`, never panics.
#[allow(clippy::too_many_arguments)]
fn consume_fee(
    pools: &mut PoolSet,
    key: &PoolKey,
    fee_sat: Sat,
    config: &ProjectionConfig,
    prices: &dyn PriceProvider,
    date: TaxDate,
    wallet: &crate::identity::WalletId,
    stats: &mut FoldStats,
    st: &mut LedgerState,
    ev: &EventId,
    ev_pseudo: bool,
    promotes: &PromoteSet,
) -> FeeCarry {
    if fee_sat <= 0 {
        return FeeCarry::default();
    }
    let (consumed, shortfall) = pools.consume_fifo(key, fee_sat);
    if shortfall > 0 {
        st.add_blocker(
            BlockerKind::UncoveredDisposal,
            Some(ev.clone()),
            format!("self-transfer/gift fee short by {shortfall} sat"),
        );
        // Defensive Filing Wizard Task 5 (arch-m-new-2): the fee-side sat-carrying site — a PURE-fee
        // short (principal fully covered) has fee_sat == short_sat once aggregated.
        st.shortfalls.push(ShortfallRecord {
            event: ev.clone(),
            wallet: Some(wallet.clone()),
            date,
            principal_sat: 0,
            fee_sat: shortfall,
        });
    }
    stats.fee_sats_consumed += consumed.iter().map(|c| c.sat).sum::<Sat>(); // sole FR9 home
    match config.self_transfer_fee {
        FeeTreatment::TreatmentC => {
            // Non-taxable: return the fee-sat basis for re-homing onto the survivor (C1: full basis carries)
            // — EXCEPT for a promoted-tranche fragment's ESTIMATE component (BG-D4 fee-evaporation): a
            // promoted tranche is usually the OLDEST lot, so a FIFO fee draw hits it first; re-homing its
            // raw (floor-inflated) `gain_basis` onto the survivor would let that estimate money leak onto
            // a LATER disposal as reported basis — a below-floor sale could then file a loss that is 100%
            // estimate money (the exact corner `tranche_fee_draw_evaporates_estimate_then_sale_files_zero_loss`
            // pins). So for a fragment whose `lot_id.origin_event_id ∈ promotes`, withhold its estimate
            // share (`round_cents(filed_basis × frag.sat / tranche_sat)`, the SAME decomposition
            // `clamped_leg_basis` uses) before summing — only the DOCUMENTED remainder re-homes; the
            // estimate EVAPORATES (never re-appears anywhere else — basis forfeiture is always
            // conservative). `promotes.get(..)` is `None` for a non-promoted lot ⇒ the fragment's full
            // `gain_basis` carries unchanged (byte-identical to the pre-BG-D4 path). Only `gain_basis` is
            // adjusted: a promoted `Acquire` lot is never dual-basis (`dual_loss_basis` starts `None` and
            // only ever gets a gift's dual basis), so a promoted fragment's `loss_basis` is always `None`
            // and the summation below already excludes it via `filter_map`.
            let gain_basis: Usd = consumed
                .iter()
                .map(|c| match promotes.get(&c.lot_id.origin_event_id) {
                    // Withhold this fragment's estimate share (the SHARED `estimate_share_of` formula —
                    // byte-identical to `clamped_leg_basis`, arch Minor-1) so only the DOCUMENTED remainder
                    // re-homes. `.max($0)` (tax N2): a cent-scale rounding residue must never make a
                    // fragment's re-homed remainder (`gain_basis − estimate_share`) negative — the
                    // direction is already conservative, this just floors each re-homed fragment at $0.
                    Some(entry) => (c.gain_basis - estimate_share_of(entry, c.sat)).max(Usd::ZERO),
                    None => c.gain_basis,
                })
                .sum();
            let has_loss = consumed.iter().any(|c| c.loss_basis.is_some());
            let loss_basis = has_loss.then(|| consumed.iter().filter_map(|c| c.loss_basis).sum());
            FeeCarry {
                gain_basis,
                loss_basis,
            }
        }
        FeeTreatment::TreatmentB => {
            // mini-disposition recognition record; proceeds = FMV(fee_sat); basis rides it (NOT re-homed).
            if !consumed.is_empty() {
                let net = fmv_of(prices, date, fee_sat).unwrap_or(Usd::ZERO);
                // NB (Opus r3 arch N-1): this call is INSIDE `consume_fee`, which takes `config`, not
                // `ctx` — so it forwards `consume_fee`'s own `promotes` param, NOT `&ctx.promotes`. The
                // TreatmentB fee mini-disposition thus clamps a promoted tranche's fee leg by construction.
                let legs = make_disposal_legs(&consumed, net, date, st, ev, ev_pseudo, promotes);
                st.disposals.push(Disposal {
                    event: ev.clone(),
                    kind: DisposeKind::Spend,
                    disposed_at: date,
                    legs,
                    fee_mini_disposition: true,
                });
            }
            FeeCarry::default()
        }
    }
}

pub fn fold(
    mut res: Resolution,
    prices: &dyn PriceProvider,
    config: &ProjectionConfig,
) -> LedgerState {
    sort_canonical(&mut res.timeline);
    // Eng-review Minor (§7.4): the boundary seed must fire on the TAX-DATE, not raw UTC order. A STABLE
    // partition by tax-date side (pre-2025 first) means a sub-day offset straddling 2025-01-01 (e.g. a
    // +12:00 post-2025 event with an earlier UTC than a −05:00 pre-2025 event) folds on the correct side
    // of the one-shot seed, and the pre-seed Universal residue matches `transition::universal_snapshot`
    // exactly (I-1). `sort_by_key` is stable, so canonical FIFO order is preserved within each side.
    res.timeline.sort_by_key(|e| e.date() >= TRANSITION_DATE);
    // Pseudo-reconcile (sub-project 2): the count of contributing synthetics (the projection-wide signal
    // for the banner + [R0-I3] export guard) and the loud `PseudoReconcileActive` advisory.
    let pseudo_count = res.pseudo_decisions.len();
    let mut st = LedgerState {
        blockers: res.blockers,
        pseudo_synthetic_count: pseudo_count,
        ..Default::default()
    };
    if pseudo_count > 0 {
        st.add_blocker(
            BlockerKind::PseudoReconcileActive,
            None,
            format!(
                "pseudo-reconcile mode is ON — {pseudo_count} synthetic default(s) are filling \
                 unresolved classifications with DELIBERATELY-FICTIONAL guesses. Rows flagged [PSEUDO] \
                 are placeholders, NOT real tax data. Correct them toward truth (or `reconcile pseudo \
                 approve` to attest chosen ones); export/forms are BLOCKED while this is active."
            ),
        );
    }
    let mut pools = PoolSet::default();
    let mut stats = FoldStats::default(); // M3/FR9: fee_sats_consumed (Task 11), sigma_in here
    let mut seeded = false;

    // Thread the resolved elections/selections (and config) through every per-event arm (NFR4).
    let ctx = FoldCtx {
        config,
        elections: &res.elections,
        selections: &res.selections,
        promotes: res.promotes.clone(), // BG-D4: real set at EVERY site (never PromoteSet::new())
    };
    // Task 11 (BG-D3 tag-side census): record which tranche origins are promoted so the state-only
    // advisories can distinguish a promoted `>$0` estimate floor from a documented fee carry (both are
    // `EstimatedConservative`, `>$0`). Keys of the live promote set == the promoted `DeclareTranche` ids.
    st.promoted_origins = ctx.promotes.keys().cloned().collect();

    for eff in &res.timeline {
        if !seeded && eff.date() >= TRANSITION_DATE {
            // Path A drain / Path B seed of the per-wallet pools from the Universal residue, ONCE (§7.4).
            transition::seed_transition(&res.transition, &mut pools, &mut st);
            seeded = true;
        }
        fold_event(eff, prices, &ctx, &mut pools, &mut st, &mut stats);
    }

    finalize(&mut st, pools, stats); // if no ≥2025 event ever seeds, Universal lots remain (carry their wallet)
    st
}

/// Fold the canonical timeline up to (but NOT including) `target`, returning the `PoolSet` exactly as the
/// real `fold` holds it at the instant it is about to process `target`. Used by the optimizer's
/// available-lots pre-pass (`optimize::available_lots_before`) so the pool it sees at a disposal matches
/// the real fold under BOTH transition paths.
///
/// **The §7.4 boundary seed fires at the correct boundary.** Exactly as in `fold`, the one-shot seed
/// (Path A drain / Path B seed) fires when the first `≥ TRANSITION_DATE` event is crossed — CRUCIALLY it
/// therefore also fires when `target` is ITSELF that first post-2025 event (the seed check runs before the
/// `target` short-circuit below). The old "truncate-then-refold" approach broke precisely here: when the
/// target disposal was the chronologically-first 2025 timeline event, the truncated prefix contained no
/// `≥ TRANSITION_DATE` event, so the re-fold never seeded and `finalize` surfaced the UN-seeded Universal
/// residue — harmless under Path A (the residue relocates by wallet, lot_ids/basis preserved) but WRONG
/// under Path B (the seed DISCARDS the residue and installs allocation lots with different lot_ids/basis,
/// so the residue lot_ids don't exist in the real pool). Reusing the real `seed_transition` (never a
/// re-implementation of its Path-A/Path-B behavior) guarantees the returned pool matches the live fold.
///
/// If `target` is absent from the timeline this folds the whole timeline; callers needing the
/// "not found ⇒ empty" contract must check existence first (`available_lots_before` does).
pub fn pools_before(
    mut res: Resolution,
    prices: &dyn PriceProvider,
    config: &ProjectionConfig,
    target: &EventId,
) -> PoolSet {
    // Mirror `fold`'s exact ordering: canonical FIFO, then the stable pre-2025 (tax-date) partition.
    sort_canonical(&mut res.timeline);
    res.timeline.sort_by_key(|e| e.date() >= TRANSITION_DATE);
    let mut st = LedgerState::default(); // discarded — we only read the pool residue (blockers irrelevant)
    let mut pools = PoolSet::default();
    let mut stats = FoldStats::default();
    let mut seeded = false;
    let ctx = FoldCtx {
        config,
        elections: &res.elections,
        selections: &res.selections,
        promotes: res.promotes.clone(), // BG-D4: real set at EVERY site (never PromoteSet::new())
    };
    for eff in &res.timeline {
        // Fire the one-shot boundary seed the instant we cross into ≥2025 — BEFORE `target` is reached,
        // so even a target that is the first post-2025 event reads the POST-seed pool (matches `fold`).
        if !seeded && eff.date() >= TRANSITION_DATE {
            transition::seed_transition(&res.transition, &mut pools, &mut st);
            seeded = true;
        }
        if &eff.id == target {
            return pools; // stop BEFORE folding the target (the seed has already fired if applicable)
        }
        fold_event(eff, prices, &ctx, &mut pools, &mut st, &mut stats);
    }
    pools
}

/// Fold the canonical timeline TRUNCATED to events with `date() <= at`, returning the finalized
/// `LedgerState` exactly as the real `fold` would hold it AS OF `at`. Used by the optimizer's Mode-2
/// consult (`optimize::consult_sale`) so the available-lots pool reflects holdings as of `at` (R0-M3):
/// the end-of-timeline pool would be WRONG for an interleaved/past `at` (lots later disposed are
/// missing; lots later acquired are wrongly present). Sibling of `pools_before` (which truncates before
/// a specific disposal id); both reuse `fold`'s exact ordering so truncation is by TIME, not load order.
///
/// **The §7.4 boundary seed fires at the correct boundary (matches `pools_before`).** The one-shot seed
/// (Path A drain / Path B install) fires when the first `>= TRANSITION_DATE` event is crossed. If no
/// real `>= 2025` event precedes `at` but `at >= TRANSITION_DATE`, the seed is FORCED before `finalize`:
/// a hypothetical disposal at `at` is itself a `>= 2025` event, so the real fold (which would include it)
/// fires the seed before it. Forcing here makes the as-of pool match that fold under BOTH transition
/// paths — Path A (residue relocated, lot_ids/basis preserved) and Path B (residue DISCARDED, allocation
/// seed lots installed). Skipping the force would surface the un-seeded Universal residue (harmless under
/// Path A, but WRONG under Path B). `continue` (not `break`) is required for heterogeneous-timezone
/// timelines: `sort_canonical` orders by `utc` ascending, but `date() = tax_date(utc, original_tz)`
/// uses each event's own `original_tz`. Under mixed timezones utc-ascending does NOT imply
/// date-ascending — an event dated `at+1` in a +14:00 timezone can sort UTC-before one dated `at` in
/// +00:00. A `break` would fire on the `at+1` event and skip the later-sorted `at` event. `continue`
/// folds every event with `date() <= at` regardless of its utc position (trivially cheap: timelines
/// are short). The boundary seed fires exactly once (guarded by `seeded`); the `continue` path does
/// not re-fire or skip it.
pub fn state_as_of(
    mut res: Resolution,
    prices: &dyn PriceProvider,
    config: &ProjectionConfig,
    at: TaxDate,
) -> LedgerState {
    sort_canonical(&mut res.timeline);
    res.timeline.sort_by_key(|e| e.date() >= TRANSITION_DATE);
    let mut st = LedgerState {
        blockers: res.blockers,
        ..Default::default()
    };
    let mut pools = PoolSet::default();
    let mut stats = FoldStats::default();
    let mut seeded = false;
    let ctx = FoldCtx {
        config,
        elections: &res.elections,
        selections: &res.selections,
        promotes: res.promotes.clone(), // BG-D4: real set at EVERY site (never PromoteSet::new())
    };
    for eff in &res.timeline {
        // Fire the one-shot boundary seed the instant we cross into >= 2025, BEFORE folding any such
        // event (matches `fold`/`pools_before`).
        if !seeded && eff.date() >= TRANSITION_DATE {
            transition::seed_transition(&res.transition, &mut pools, &mut st);
            seeded = true;
        }
        // Truncate by TIME: skip events strictly after `at`. Cannot break early: `sort_canonical`
        // orders by utc but `date()` uses each event's own `original_tz`, so utc-ascending ≠
        // date-ascending under heterogeneous timezones (e.g. an event dated `at+1` in +14:00 sorts
        // UTC-before one dated `at` in +00:00). `continue` ensures every `date() <= at` event is folded.
        if eff.date() > at {
            continue;
        }
        fold_event(eff, prices, &ctx, &mut pools, &mut st, &mut stats);
    }
    // Force the seed when `at` is on/after the boundary but no real >= 2025 event preceded it: a
    // hypothetical disposal at `at` would itself trigger the seed (Path A drain / Path B install).
    if !seeded && at >= TRANSITION_DATE {
        transition::seed_transition(&res.transition, &mut pools, &mut st);
    }
    finalize(&mut st, pools, stats);
    st
}

/// PASS-2 per-event dispatcher. Lifted out of `fold` so that BOTH the real fold and the pass-1
/// `transition::universal_snapshot` pre-fold run the IDENTICAL per-event arms — the conservation guard's
/// pre-2025 residue therefore provably matches the real fold's pre-seed residue (I-1). Pure: mutates only
/// the passed pools/state/stats.
pub(crate) fn fold_event(
    eff: &Eff,
    prices: &dyn PriceProvider,
    ctx: &FoldCtx,
    pools: &mut PoolSet,
    st: &mut LedgerState,
    stats: &mut FoldStats,
) {
    let date = eff.date();
    // [R0-C1] pseudo taint seam: an event whose effective `Op` is a synthetic default (pseudo mode)
    // stamps every `Lot`/leg it creates. `false` outside pseudo mode ⇒ byte-identical projection.
    let ev_pseudo = eff.pseudo;
    match &eff.op {
        Op::Acquire(a) => {
            let wallet = match &eff.wallet {
                Some(w) => w.clone(),
                None => {
                    st.add_blocker(
                        BlockerKind::Unclassified,
                        Some(eff.id.clone()),
                        "acquire without wallet",
                    );
                    return;
                }
            };
            let lot = Lot {
                lot_id: LotId {
                    origin_event_id: eff.id.clone(),
                    split_sequence: 0,
                },
                wallet: wallet.clone(),
                acquired_at: date,
                original_sat: a.sat,
                remaining_sat: a.sat,
                usd_basis: a.usd_cost + a.fee_usd, // TP2: basis = cost + acquisition fee
                basis_source: a.basis_source,
                dual_loss_basis: None,
                donor_acquired_at: None,
                basis_pending: false,
                pseudo: ev_pseudo, // [R0-C1] e.g. an accept-first ImportConflict that became an Acquire
            };
            pools.new_origin_lot(pool_key(date, &wallet), lot);
            stats.sigma_in += a.sat; // FR9 Σin: externally-sourced acquisition
        }
        Op::Dispose {
            sat,
            proceeds,
            fee_usd,
            fee_sat,
            kind,
        } => {
            let wallet = match &eff.wallet {
                Some(w) => w.clone(),
                None => {
                    st.add_blocker(
                        BlockerKind::UncoveredDisposal,
                        Some(eff.id.clone()),
                        "dispose without wallet",
                    );
                    return;
                }
            };
            let key = pool_key(date, &wallet);
            note_pre2025_once(
                st,
                date,
                &eff.id,
                ctx.config.pre2025_method,
                ctx.config.pre2025_method_attested,
            ); // §7.4: pre-2025 disposal advisory (once)
            let (consumed, shortfall) =
                consume_principal(pools, &key, *sat, date, &wallet, ctx, st, &eff.id);
            if shortfall > 0 {
                st.add_blocker(
                    BlockerKind::UncoveredDisposal,
                    Some(eff.id.clone()),
                    format!("dispose short by {shortfall} sat"),
                );
                // Defensive Filing Wizard Task 5 (arch-m-new-2): the principal-side sat-carrying site.
                st.shortfalls.push(ShortfallRecord {
                    event: eff.id.clone(),
                    wallet: Some(wallet.clone()),
                    date,
                    principal_sat: shortfall,
                    fee_sat: 0,
                });
            }
            if !consumed.is_empty() {
                let net = round_cents(*proceeds - *fee_usd); // TP2: disposition fee reduces proceeds
                let mut legs =
                    make_disposal_legs(&consumed, net, date, st, &eff.id, ev_pseudo, &ctx.promotes);
                // I-1: Task 11 fee step — consume fee_sat FIFO from source pool AFTER principal.
                // Mirrors the gift/SelfTransfer pattern; native Dispose passes fee_sat=None (no-op).
                // (c) default: re-home carry onto last disposal leg; fee-sat basis rolls into the
                //     disposition (reported basis increases → gain decreases); fee non-taxable.
                // (b) config:  emits mini-disposition; returns empty carry; leg basis unchanged.
                let carry = consume_fee(
                    pools,
                    &key,
                    fee_sat.unwrap_or(0),
                    ctx.config,
                    prices,
                    date,
                    &wallet,
                    stats,
                    st,
                    &eff.id,
                    ev_pseudo,
                    &ctx.promotes,
                );
                if let Some(last) = legs.last_mut() {
                    carry.rehome_onto_disposal_leg(last);
                } else if carry.gain_basis > Usd::ZERO {
                    // m3: degenerate guard — no surviving leg (principal == 0); unreachable for real events.
                    st.add_blocker(
                        BlockerKind::UncoveredDisposal,
                        Some(eff.id.clone()),
                        "fee carry has no surviving disposal leg to re-home onto (principal == 0)",
                    );
                }
                st.disposals.push(Disposal {
                    event: eff.id.clone(),
                    kind: *kind,
                    disposed_at: date,
                    legs,
                    fee_mini_disposition: false,
                });
            }
        }
        Op::Income {
            sat,
            fmv,
            kind,
            business,
        } => {
            let wallet = match &eff.wallet {
                Some(w) => w.clone(),
                None => {
                    st.add_blocker(
                        BlockerKind::FmvMissing,
                        Some(eff.id.clone()),
                        "income without wallet",
                    );
                    return;
                }
            };
            let (basis, pending) = match fmv {
                Some(v) => {
                    st.income_recognized.push(IncomeRecord {
                        event: eff.id.clone(),
                        recognized_at: date,
                        sat: *sat,
                        usd_fmv: *v,
                        kind: *kind,
                        business: *business,
                        pseudo: ev_pseudo, // [R0-I2] a pseudo daily-close FMV taints the income row
                    });
                    (*v, false)
                }
                None => {
                    st.add_blocker(
                        BlockerKind::FmvMissing,
                        Some(eff.id.clone()),
                        "income FMV missing",
                    );
                    (Usd::ZERO, true) // basis pending; lot still created so Σsat conservation holds (§7.3)
                }
            };
            let lot = Lot {
                lot_id: LotId {
                    origin_event_id: eff.id.clone(),
                    split_sequence: 0,
                },
                wallet: wallet.clone(),
                acquired_at: date,
                original_sat: *sat,
                remaining_sat: *sat,
                usd_basis: basis,
                basis_source: BasisSource::FmvAtIncome,
                dual_loss_basis: None,
                donor_acquired_at: None,
                basis_pending: pending,
                pseudo: ev_pseudo,
            };
            pools.new_origin_lot(pool_key(date, &wallet), lot);
            stats.sigma_in += *sat; // FR9 Σin: income is externally-sourced (counts even while FMV is pending)
        }
        Op::PendingOut { sat, fee_sat } => {
            let wallet = match &eff.wallet {
                Some(w) => w.clone(),
                None => {
                    st.add_blocker(
                        BlockerKind::UncoveredDisposal,
                        Some(eff.id.clone()),
                        "pending out without wallet",
                    );
                    return;
                }
            };
            let key = pool_key(date, &wallet);
            let total_sat = *sat + fee_sat.unwrap_or(0);
            let (consumed, shortfall) = pools.consume_fifo(&key, total_sat);
            if shortfall > 0 {
                st.add_blocker(
                    BlockerKind::UncoveredDisposal,
                    Some(eff.id.clone()),
                    format!("pending out short by {shortfall} sat"),
                );
                // Defensive Filing Wizard Task 5 (arch-m-new-2): PendingOut draws principal+fee in ONE
                // combined FIFO need (`total_sat`) — the shortfall is recorded as principal_sat (there is
                // no separate fee-only draw to attribute it to, unlike Dispose/SelfTransfer/GiftOut/Donate).
                st.shortfalls.push(ShortfallRecord {
                    event: eff.id.clone(),
                    wallet: Some(wallet.clone()),
                    date,
                    principal_sat: shortfall,
                    fee_sat: 0,
                });
            }
            let legs: Vec<PendingLeg> = consumed
                .iter()
                .map(|c| PendingLeg {
                    lot_id: c.lot_id.clone(),
                    sat: c.sat,
                    usd_basis: c.gain_basis,
                    acquired_at: c.acquired_at,
                    pseudo: c.pseudo || ev_pseudo, // [R0-C1] a pseudo lot withdrawn into pending stays tainted
                })
                .collect();
            st.pending_reconciliation.push(PendingTransfer {
                event: eff.id.clone(),
                principal_sat: *sat,
                fee_sat: *fee_sat,
                legs,
            });
            // Advisory blocker: unmatched outflow (may be resolved by a later TransferLink in Task 8+).
            st.add_blocker(
                BlockerKind::UnmatchedOutflows,
                Some(eff.id.clone()),
                "unmatched transfer out",
            );
        }
        Op::SelfTransfer { sat, fee_sat, dest } => {
            let wallet = match &eff.wallet {
                Some(w) => w.clone(),
                None => {
                    st.add_blocker(
                        BlockerKind::UncoveredDisposal,
                        Some(eff.id.clone()),
                        "self transfer without source wallet",
                    );
                    return;
                }
            };
            let key = pool_key(date, &wallet);
            let (consumed, shortfall) =
                consume_principal(pools, &key, *sat, date, &wallet, ctx, st, &eff.id);
            if shortfall > 0 {
                st.add_blocker(
                    BlockerKind::UncoveredDisposal,
                    Some(eff.id.clone()),
                    format!("self transfer short by {shortfall} sat"),
                );
                // Defensive Filing Wizard Task 5 (arch-m-new-2): the principal-side sat-carrying site.
                st.shortfalls.push(ShortfallRecord {
                    event: eff.id.clone(),
                    wallet: Some(wallet.clone()),
                    date,
                    principal_sat: shortfall,
                    fee_sat: 0,
                });
            }
            // Relocate consumed fragments to the destination pool: carry basis, HP, donor_acquired_at.
            // Non-taxable (TP7): no Disposal or Removal records. basis_source = CarriedFromTransfer.
            let mut relocated: Vec<Lot> = Vec::new();
            for c in &consumed {
                let seq = pools.bump_split(&c.lot_id.origin_event_id);
                relocated.push(Lot {
                    lot_id: LotId {
                        origin_event_id: c.lot_id.origin_event_id.clone(),
                        split_sequence: seq,
                    },
                    wallet: dest.clone(),
                    acquired_at: c.acquired_at,
                    original_sat: c.sat,
                    remaining_sat: c.sat,
                    usd_basis: c.gain_basis,
                    // D-8: a relocated tranche keeps its `EstimatedConservative` tag — exactly the
                    // Exchange→SelfCustody move P8 recommends — so the disposal leg keeps P3's dip advisory
                    // and P7's MANDATORY disclosure. usd_basis/acquired_at carry either way; only the tag
                    // (the advisory/disclosure key) is at stake.
                    basis_source: if c.basis_source == BasisSource::EstimatedConservative {
                        BasisSource::EstimatedConservative
                    } else {
                        BasisSource::CarriedFromTransfer
                    },
                    dual_loss_basis: c.loss_basis,
                    donor_acquired_at: c.donor_acquired_at,
                    basis_pending: c.basis_pending,
                    // [R0-C1] relocated fragment: taint propagates from the consumed source lot (fold.rs:766-813)
                    // OR the self-transfer event itself being synthetic.
                    pseudo: c.pseudo || ev_pseudo,
                });
            }
            // Task 11: fee handling — consume fee_sat FIFO from source pool AFTER principal (FIFO order).
            // (c) default: returns FeeCarry to re-home onto relocated.last(), so FULL basis carries (C1).
            // (b) config:  emits mini-disposition; returns empty carry; destination lot stays at principal basis.
            let carry = consume_fee(
                pools,
                &key,
                fee_sat.unwrap_or(0),
                ctx.config,
                prices,
                date,
                &wallet,
                stats,
                st,
                &eff.id,
                ev_pseudo,
                &ctx.promotes,
            );
            if let Some(last) = relocated.last_mut() {
                carry.rehome_onto_lot(last);
            } else if carry.gain_basis > Usd::ZERO {
                // m3: degenerate guard — no surviving lot to re-home onto (principal == 0).
                // Unreachable for a real TransferLink (always moves principal > 0), but never silent.
                st.add_blocker(
                    BlockerKind::UncoveredDisposal,
                    Some(eff.id.clone()),
                    "fee carry has no surviving lot to re-home onto (principal == 0)",
                );
            }
            let dest_key = pool_key(date, dest);
            for lot in relocated {
                pools.push_lot(dest_key.clone(), lot);
            }
        }
        Op::UnknownInbound { sat: _ } => {
            // Hard blocker: basis is unknown. NO lot — sats not yet in the ledger (FR9/§7.3).
            st.add_blocker(
                BlockerKind::UnknownBasisInbound,
                Some(eff.id.clone()),
                "unclassified TransferIn — basis unknown",
            );
        }
        Op::IncomeInbound {
            sat,
            fmv,
            kind,
            business,
        } => {
            // Identical to Op::Income: income lot at FMV + IncomeRecord. sigma_in += sat.
            let wallet = match &eff.wallet {
                Some(w) => w.clone(),
                None => {
                    st.add_blocker(
                        BlockerKind::FmvMissing,
                        Some(eff.id.clone()),
                        "income inbound without wallet",
                    );
                    return;
                }
            };
            let (basis, pending) = match fmv {
                Some(v) => {
                    st.income_recognized.push(IncomeRecord {
                        event: eff.id.clone(),
                        recognized_at: date,
                        sat: *sat,
                        usd_fmv: *v,
                        kind: *kind,
                        business: *business,
                        pseudo: ev_pseudo, // [R0-r2 I-B] taint the IncomeInbound row too (both push sites)
                    });
                    (*v, false)
                }
                None => {
                    st.add_blocker(
                        BlockerKind::FmvMissing,
                        Some(eff.id.clone()),
                        "income inbound FMV missing",
                    );
                    (Usd::ZERO, true)
                }
            };
            let lot = Lot {
                lot_id: LotId {
                    origin_event_id: eff.id.clone(),
                    split_sequence: 0,
                },
                wallet: wallet.clone(),
                acquired_at: date,
                original_sat: *sat,
                remaining_sat: *sat,
                usd_basis: basis,
                basis_source: BasisSource::FmvAtIncome,
                dual_loss_basis: None,
                donor_acquired_at: None,
                basis_pending: pending,
                pseudo: ev_pseudo,
            };
            pools.new_origin_lot(pool_key(date, &wallet), lot);
            stats.sigma_in += *sat;
        }
        Op::GiftReceived {
            sat,
            donor_basis,
            donor_acquired_at,
            fmv_at_gift,
        } => {
            // Task 10: §1015(a) dual-basis lot construction (TP11).
            // Four cases by (donor_basis, donor_acquired_at) × (fmv_at_gift vs donor_basis):
            //   1. donor_basis=Some(b), fmv_at_gift >= b  → single carryover (Gain zone only); tacks.
            //   2. donor_basis=Some(b), fmv_at_gift < b   → dual basis; tacks on gain side.
            //   3. donor_basis=None, donor_acquired_at=Some(d) → GiftFmvFallback: look up price at d.
            //   4. donor_basis=None, donor_acquired_at=None    → basis unknown; hard blocker + pending lot.
            let wallet = match &eff.wallet {
                Some(w) => w.clone(),
                None => {
                    st.add_blocker(
                        BlockerKind::FmvMissing,
                        Some(eff.id.clone()),
                        "gift received without wallet",
                    );
                    return;
                }
            };
            let (usd_basis, dual_loss_basis, basis_source, pending) = match donor_basis {
                Some(b) => {
                    if *fmv_at_gift >= *b {
                        // Case 1: FMV ≥ donor basis — single carryover; no dual.
                        (*b, None, BasisSource::GiftCarryover, false)
                    } else {
                        // Case 2: FMV < donor basis — dual: gain basis = donor basis, loss basis = FMV.
                        (*b, Some(*fmv_at_gift), BasisSource::GiftCarryover, false)
                    }
                }
                None => match donor_acquired_at {
                    Some(d) => {
                        // Case 3: GiftFmvFallback — derive basis from BTC price at donor's acquisition date.
                        match fmv_of(prices, *d, *sat) {
                            Some(fmv) => (fmv, None, BasisSource::GiftFmvFallback, false),
                            None => {
                                // Price unavailable at donor acquisition date → basis indeterminate.
                                st.add_blocker(
                                    BlockerKind::UnknownBasisInbound,
                                    Some(eff.id.clone()),
                                    "gift received: donor basis unknown and price unavailable at donor acquisition date",
                                );
                                (Usd::ZERO, None, BasisSource::GiftFmvFallback, true)
                            }
                        }
                    }
                    None => {
                        // Case 4: both donor basis and acquisition date unknown — hard blocker.
                        st.add_blocker(
                            BlockerKind::UnknownBasisInbound,
                            Some(eff.id.clone()),
                            "gift received: donor basis and acquisition date both unknown",
                        );
                        (Usd::ZERO, None, BasisSource::GiftCarryover, true)
                    }
                },
            };
            let lot = Lot {
                lot_id: LotId {
                    origin_event_id: eff.id.clone(),
                    split_sequence: 0,
                },
                wallet: wallet.clone(),
                acquired_at: date,
                original_sat: *sat,
                remaining_sat: *sat,
                usd_basis,
                basis_source,
                dual_loss_basis,
                donor_acquired_at: *donor_acquired_at,
                basis_pending: pending,
                pseudo: ev_pseudo,
            };
            pools.new_origin_lot(pool_key(date, &wallet), lot);
            stats.sigma_in += *sat; // classified GiftReceived is externally-sourced (FR9)
        }
        Op::SelfTransferInbound {
            sat,
            basis,
            acquired_at,
        } => {
            // Cycle A: "my own coins" returning — a NON-taxable receipt that CREATES a fresh origin lot.
            // Modeled on Op::IncomeInbound (fold.rs), but (G1) NEVER basis_pending, (G2) pushes NO
            // IncomeRecord, and (G3) donor_acquired_at: None (not a gift — no tacking).
            let wallet = match &eff.wallet {
                Some(w) => w.clone(),
                None => {
                    // [R0-M2 / G5] No wallet → nowhere to create the lot. Emit a Hard UnknownBasisInbound
                    // with a self-transfer message (NOT the IncomeInbound FmvMissing guard, which is
                    // semantically wrong for a non-income receipt) and return without creating a lot.
                    st.add_blocker(
                        BlockerKind::UnknownBasisInbound,
                        Some(eff.id.clone()),
                        "self-transfer inbound without wallet — nowhere to create the lot",
                    );
                    return;
                }
            };
            let usd_basis = basis.unwrap_or(Usd::ZERO); // conservative $0 default (max eventual gain)
                                                        // [reconcile-defaults C2] When no acquisition date is supplied, default to 1yr+1day before the
                                                        // receipt (`date`) so the holding period is LONG-TERM (leap-safe helper). Most received BTC is a
                                                        // long-held cold-storage deposit; this default is DISCLOSED below (independent of `basis`).
            let acq = acquired_at.unwrap_or_else(|| long_term_default_acquired(date));
            if basis.is_none() {
                // (G4) ADVISORY only — fires on None, NOT on usd_basis == 0 (an attested Some(0) is silent).
                st.add_blocker(
                    BlockerKind::SelfTransferInboundZeroBasis,
                    Some(eff.id.clone()),
                    "basis defaulted to $0 — likely overstates your eventual gain. To supply the real \
                     cost, VOID this classification (run `btctax reconcile void`, or press 'v' in the \
                     TUI editor) and re-classify with --basis — classify-inbound is first-wins, so \
                     re-running without voiding first would conflict, not update.",
                );
            }
            if acquired_at.is_none() {
                // [reconcile-defaults I2] Disclose the DEFAULTED long-term acquisition — gated on the
                // acquisition being defaulted (NOT on basis), so a supplied `--basis` with no `--acquired`
                // cannot silently backdate the holding period to long-term.
                st.add_blocker(
                    BlockerKind::SelfTransferInboundDefaultedAcquired,
                    Some(eff.id.clone()),
                    "acquisition date defaulted to 1 year + 1 day before receipt — holding period assumed \
                     LONG-TERM. If these coins were held for a year or less, correct it with --acquired \
                     (VOID this classification first: run `btctax reconcile void`, or press 'v' in the \
                     TUI editor — classify-inbound is first-wins).",
                );
            }
            let lot = Lot {
                lot_id: LotId {
                    origin_event_id: eff.id.clone(),
                    split_sequence: 0,
                },
                wallet: wallet.clone(),
                acquired_at: acq, // HP start; gain_hp_start() == acq (donor_acquired_at is None → no tacking)
                original_sat: *sat,
                remaining_sat: *sat,
                usd_basis,
                basis_source: BasisSource::SelfTransferInbound,
                dual_loss_basis: None,
                donor_acquired_at: None, // NOT a gift — it's your own coin
                basis_pending: false, // (G1) $0 is computable → NEVER gated (contrast Income-FMV-missing)
                // [R0-C1] the HEADLINE taint case: a pseudo `SelfTransferMine{$0}` default → this lot is
                // pseudo, so a later REAL Sell consuming it renders FLAGGED, never a clean `proceeds − 0`.
                pseudo: ev_pseudo,
            };
            // pool_key uses the RECEIPT date (`date`), while acquired_at carries the supplied-or-receipt
            // date — orthogonal (mirrors the gift path): a real old date lands in the receipt-year pool.
            pools.new_origin_lot(pool_key(date, &wallet), lot);
            stats.sigma_in += *sat; // FR9 Σin: coins enter the ledger (externally-sourced)
        }
        Op::GiftOut {
            sat,
            fmv,
            fee_sat,
            donee,
            ..
        } => {
            // TP10: gift outbound → Removal with zero recognized gain; no Disposal.
            let wallet = match &eff.wallet {
                Some(w) => w.clone(),
                None => {
                    st.add_blocker(
                        BlockerKind::UncoveredDisposal,
                        Some(eff.id.clone()),
                        "gift out without wallet",
                    );
                    return;
                }
            };
            let key = pool_key(date, &wallet);
            note_pre2025_once(
                st,
                date,
                &eff.id,
                ctx.config.pre2025_method,
                ctx.config.pre2025_method_attested,
            ); // §7.4: pre-2025 removal advisory (once)
            let (consumed, shortfall) =
                consume_principal(pools, &key, *sat, date, &wallet, ctx, st, &eff.id);
            if shortfall > 0 {
                st.add_blocker(
                    BlockerKind::UncoveredDisposal,
                    Some(eff.id.clone()),
                    format!("gift out short by {shortfall} sat"),
                );
                // Defensive Filing Wizard Task 5 (arch-m-new-2): the principal-side sat-carrying site.
                st.shortfalls.push(ShortfallRecord {
                    event: eff.id.clone(),
                    wallet: Some(wallet.clone()),
                    date,
                    principal_sat: shortfall,
                    fee_sat: 0,
                });
            }
            if !consumed.is_empty() {
                let (mut legs, donor_acquired_at) =
                    make_removal_legs(&consumed, *fmv, date, st, &eff.id, ev_pseudo, &ctx.promotes);
                // Task 11: fee step — consume fee_sat FIFO from source pool AFTER principal.
                // (c) default: re-home carry onto last removal leg so donee carries FULL basis (C1).
                // (b) config:  emits mini-disposition; empty carry; donee gets principal-only basis.
                let carry = consume_fee(
                    pools,
                    &key,
                    fee_sat.unwrap_or(0),
                    ctx.config,
                    prices,
                    date,
                    &wallet,
                    stats,
                    st,
                    &eff.id,
                    ev_pseudo,
                    &ctx.promotes,
                );
                if let Some(last) = legs.last_mut() {
                    carry.rehome_onto_removal_leg(last);
                } else if carry.gain_basis > Usd::ZERO {
                    // m3: degenerate guard (unreachable for real gifts, which always move principal > 0).
                    st.add_blocker(
                        BlockerKind::UncoveredDisposal,
                        Some(eff.id.clone()),
                        "fee carry has no surviving removal leg to re-home onto (principal == 0)",
                    );
                }
                st.removals.push(Removal {
                    event: eff.id.clone(),
                    kind: RemovalKind::Gift,
                    removed_at: date,
                    legs,
                    appraisal_required: false,
                    donor_acquired_at,
                    claimed_deduction: None,
                    donee: donee.clone(),
                });
            }
        }
        Op::Donate {
            sat,
            fmv,
            appraisal_required,
            fee_sat,
            donee,
            ..
        } => {
            // TP10: donation outbound → Removal with zero recognized gain; no Disposal.
            let wallet = match &eff.wallet {
                Some(w) => w.clone(),
                None => {
                    st.add_blocker(
                        BlockerKind::UncoveredDisposal,
                        Some(eff.id.clone()),
                        "donate without wallet",
                    );
                    return;
                }
            };
            let key = pool_key(date, &wallet);
            note_pre2025_once(
                st,
                date,
                &eff.id,
                ctx.config.pre2025_method,
                ctx.config.pre2025_method_attested,
            ); // §7.4: pre-2025 removal advisory (once)
            let (consumed, shortfall) =
                consume_principal(pools, &key, *sat, date, &wallet, ctx, st, &eff.id);
            if shortfall > 0 {
                st.add_blocker(
                    BlockerKind::UncoveredDisposal,
                    Some(eff.id.clone()),
                    format!("donate short by {shortfall} sat"),
                );
                // Defensive Filing Wizard Task 5 (arch-m-new-2): the principal-side sat-carrying site.
                st.shortfalls.push(ShortfallRecord {
                    event: eff.id.clone(),
                    wallet: Some(wallet.clone()),
                    date,
                    principal_sat: shortfall,
                    fee_sat: 0,
                });
            }
            if !consumed.is_empty() {
                let (mut legs, donor_acquired_at) =
                    make_removal_legs(&consumed, *fmv, date, st, &eff.id, ev_pseudo, &ctx.promotes);
                // Task 11: fee step — consume fee_sat FIFO from source pool AFTER principal.
                // (c) default: re-home carry onto last removal leg so donee carries FULL basis (C1).
                // (b) config:  emits mini-disposition; empty carry; donee gets principal-only basis.
                let carry = consume_fee(
                    pools,
                    &key,
                    fee_sat.unwrap_or(0),
                    ctx.config,
                    prices,
                    date,
                    &wallet,
                    stats,
                    st,
                    &eff.id,
                    ev_pseudo,
                    &ctx.promotes,
                );
                if let Some(last) = legs.last_mut() {
                    carry.rehome_onto_removal_leg(last);
                } else if carry.gain_basis > Usd::ZERO {
                    // m3: degenerate guard (unreachable for real donations, which always move principal > 0).
                    st.add_blocker(
                        BlockerKind::UncoveredDisposal,
                        Some(eff.id.clone()),
                        "fee carry has no surviving removal leg to re-home onto (principal == 0)",
                    );
                }
                // §170(e)(1)(A) charitable-deduction amount: exact for a non-dealer individual
                // investor donating a capital asset to a public charity (the modeled universe).
                // Computed from the FINAL persisted legs (after both make_removal_legs AND
                // carry.rehome_onto_removal_leg) so the re-homed fee-cent basis is included.
                // LT legs → FMV (the LT-capital-gain deduction under §170(e)); would-be gain is
                // LTCG → no reduction; also FMV when depreciated (a would-be loss is not a reduction).
                // ST legs → min(FMV, basis): when appreciated (basis<FMV) the ST gain reduces FMV
                // to basis; when depreciated (basis>FMV) there is no would-be gain → deduction = FMV.
                // Stored on the Removal; also drives §170(f)(11)(C) QualifiedAppraisalNote.
                // Does NOT read or modify the user's `appraisal_required` bool (independent cross-check).
                let claimed_deduction: Usd = legs
                    .iter()
                    .map(|leg| {
                        if leg.term == Term::LongTerm {
                            leg.fmv_at_transfer
                        } else {
                            leg.fmv_at_transfer.min(leg.basis)
                        }
                    })
                    .sum();
                if claimed_deduction > crate::tax::tables::QUALIFIED_APPRAISAL_THRESHOLD {
                    st.add_blocker(
                        BlockerKind::QualifiedAppraisalNote,
                        Some(eff.id.clone()),
                        format!(
                            "Claimed deduction ${claimed_deduction:.2} exceeds the \
                             §170(f)(11)(C) $5,000 threshold. Qualified appraisal likely required: \
                             CCA 202302012 — a crypto donation with a claimed deduction >$5,000 \
                             requires a qualified appraisal; the exchange-price/readily-valued \
                             exception does NOT apply to crypto. \
                             This is the exact §170(e) deduction for a non-dealer individual \
                             investor donating a capital asset (LT→FMV; ST→min(FMV,basis)). \
                             Caveat (a) dealer/inventory: crypto held as inventory/for sale in a \
                             trade or business (§1221(a)(1)) or other ordinary-income property \
                             deducts at basis under §170(e) REGARDLESS of holding period — this \
                             figure assumes capital-asset (investor) status and would OVER-STATE \
                             for a dealer; verify. \
                             Caveat (b) donee type: LT→FMV assumes a public charity (50%-limit org); \
                             a non-operating private foundation reduces appreciated LT crypto to \
                             basis (§170(e)(1)(B)(ii); crypto is not qualified appreciated stock) — \
                             donee type is not modeled; would OVER-STATE for a private-foundation \
                             gift; verify. \
                             §170(f)(11)(F) aggregation: this flags a single donation; the $5,000 \
                             test also aggregates similar donated items across the tax year — \
                             cross-donation aggregation is not considered here."
                        ),
                    );
                }
                st.removals.push(Removal {
                    event: eff.id.clone(),
                    kind: RemovalKind::Donation,
                    removed_at: date,
                    legs,
                    appraisal_required: *appraisal_required,
                    donor_acquired_at,
                    claimed_deduction: Some(claimed_deduction),
                    donee: donee.clone(),
                });
            }
        }
        Op::Unclassified => {
            st.add_blocker(
                BlockerKind::Unclassified,
                Some(eff.id.clone()),
                "unclassified BTC-side row",
            );
        }
        Op::Skip => {}
    }
}

/// Collect remaining lots + holdings; sort all output deterministically (NFR4); commit the FoldStats (M3).
pub fn finalize(st: &mut LedgerState, pools: PoolSet, mut stats: FoldStats) {
    let mut holdings: BTreeMap<crate::identity::WalletId, Sat> = BTreeMap::new();
    let mut lots: Vec<Lot> = Vec::new();
    for (_key, pool) in pools.pools {
        for lot in pool {
            if lot.remaining_sat > 0 {
                *holdings.entry(lot.wallet.clone()).or_insert(0) += lot.remaining_sat;
                lots.push(lot);
            }
        }
    }
    lots.sort_by(|a, b| {
        a.wallet
            .cmp(&b.wallet)
            .then(a.acquired_at.cmp(&b.acquired_at))
            .then(a.lot_id.cmp(&b.lot_id))
    });
    st.lots = lots;
    st.holdings_by_wallet = holdings;
    // M1: sort blockers by the DERIVED Ord of (kind, Option<EventId>, detail) — a total order, no Debug strings.
    st.blockers.sort_by(|a, b| {
        a.kind
            .cmp(&b.kind)
            .then_with(|| a.event.cmp(&b.event))
            .then_with(|| a.detail.cmp(&b.detail))
    });
    // Σpending is reconstructable from the queue; sigma_in/fee_sats_consumed are accumulated during the fold.
    stats.sigma_pending = st
        .pending_reconciliation
        .iter()
        .map(|p| p.principal_sat + p.fee_sat.unwrap_or(0))
        .sum();
    st.stats = stats;
}