Skip to main content

btctax_cli/
session.rs

1//! `Session` wraps one open `btctax_store::Vault` and is the single seam every command opens. The
2//! passphrase is ALWAYS a parameter — production resolves it in `main` (prompt/env); tests inject a
3//! constructed `Passphrase`. `project()` runs the pure core projection over the bundled price dataset.
4use crate::bulk_estimated;
5use crate::config::{self, CliConfig};
6use crate::donation_details;
7use crate::optimize_attest;
8use crate::CliError;
9use crate::{return_inputs, tax_profile};
10use btctax_adapters::{BundledFullReturnTables, BundledTaxTables};
11use btctax_core::conventions::{round_cents, tax_date, TRANSITION_DATE};
12use btctax_core::persistence::{init_schema, load_all};
13use btctax_core::tax::tables::FullReturnTables;
14use btctax_core::{project, LedgerEvent, LedgerState, PriceProvider, ProjectionConfig, TaxTables};
15use btctax_core::{
16    AllocLot, BlockerKind, DonationDetails, EventId, EventPayload, LotMethod, PendingTransfer, Sat,
17    TaxDate, TaxProfile, Usd, WalletId,
18};
19use btctax_store::{Passphrase, Vault};
20use rusqlite::Connection;
21use std::collections::{BTreeMap, BTreeSet};
22use std::path::Path;
23
24// ── Bulk link-transfer plan (bulk-link-transfer D1) ──────────────────────────
25//
26// The shared, READ-ONLY plan both the CLI (`cmd::reconcile::bulk_link_plan`) and the TUI priced
27// preview compute from the HELD session. Modeled on `optimize_proposal`/`safe_harbor_residue`: a
28// `&self` read helper that appends and persists NOTHING.
29
30/// Time-frame selector for a bulk link-transfer plan. `Range` bounds are INCLUSIVE.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub enum Frame {
33    All,
34    Year(i32),
35    Range { from: TaxDate, to: TaxDate },
36}
37
38/// Filter narrowing which pending outbound transfers a bulk plan selects.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct BulkFilter {
41    pub frame: Frame,
42    pub from_wallet: Option<WalletId>,
43}
44
45/// One enriched pending outbound transfer in a bulk link-transfer plan.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct BulkLinkRow {
48    pub out_event: EventId,
49    pub date: TaxDate,
50    /// [R0-N2] ALWAYS `Some` for a pending out (a wallet-less TransferOut never reaches
51    /// `pending_reconciliation`); `Option` kept defensively.
52    pub source_wallet: Option<WalletId>,
53    pub principal_sat: Sat,
54    /// `fmv_of(prices, date, principal_sat)` [R0-M1]; advisory, `None` on missing price / overflow.
55    pub usd_value: Option<Usd>,
56    /// Σ leg `usd_basis` carried (over the principal+fee sats the legs cover); non-taxable → carries.
57    pub basis_usd: Usd,
58}
59
60/// The read-only plan a bulk link-transfer would execute: the eligible/in-frame `included` rows, the
61/// `skipped_same_wallet` rows (source == dest — a meaningless self-link), and the preview totals.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct BulkLinkPlan {
64    pub dest: WalletId,
65    /// Eligible + in-frame + passes `from_wallet` + source != dest. Sorted by `date`.
66    pub included: Vec<BulkLinkRow>,
67    /// Source wallet == dest → cannot self-link to itself.
68    pub skipped_same_wallet: Vec<BulkLinkRow>,
69    pub total_sat: Sat,
70    /// [R0-I2] Σ of the priced `usd_value`s — a FLOOR, always a real number.
71    pub total_usd_value_floor: Usd,
72    /// [R0-I2] rows priced `None` → render "≥ $X (N unavailable)" vs exact "$X".
73    pub missing_price_count: usize,
74    /// Σ `basis_usd` over `included`.
75    pub total_basis_usd: Usd,
76}
77
78// ── Bulk classify-inbound-self-transfer plan (bulk-classify-inbound-self-transfer D1) ─
79//
80// The shared, READ-ONLY plan both the CLI (`cmd::reconcile::bulk_self_transfer_in_plan`) and the TUI
81// priced preview compute from the HELD session. A close MIRROR of `bulk_link_transfer_plan` applied to
82// Cycle A's `InboundClass::SelfTransferMine` ($0 conservative basis, non-taxable). Appends and
83// persists NOTHING.
84
85/// Filter narrowing which pending unknown-basis inbound deposits a bulk STI plan selects. `wallet`
86/// filters the RECEIVING wallet (the inbound has no "destination" — it IS the receiving leg).
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct BulkStiFilter {
89    pub frame: Frame,
90    pub wallet: Option<WalletId>,
91}
92
93/// One enriched pending unknown-basis inbound deposit in a bulk STI plan.
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct BulkStiRow {
96    pub in_event: EventId,
97    pub date: TaxDate,
98    /// [R0-M2] ALWAYS `Some` (wallet-less inbounds are excluded — they create no lot); `Option` kept
99    /// defensively / for display symmetry with `BulkLinkRow`.
100    pub wallet: Option<WalletId>,
101    pub sat: Sat,
102    /// `fmv_of(prices, date, sat)` — the market value being given $0 basis; `None` on missing price.
103    pub usd_fmv: Option<Usd>,
104}
105
106/// The read-only plan a bulk STI would execute: the eligible/in-frame `included` rows + preview totals.
107/// No `skipped_*` bucket (an inbound has no self-destination to skip).
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct BulkStiPlan {
110    /// Eligible + in-frame + passes `wallet` filter. Sorted by `date`.
111    pub included: Vec<BulkStiRow>,
112    pub total_sat: Sat,
113    /// Σ of the priced `usd_fmv`s — the HONEST FLOOR (the over-tax exposure), always a real number.
114    pub total_usd_fmv_floor: Usd,
115    /// Rows priced `None` → render "≥ $X (N unavailable)" vs exact "$X".
116    pub missing_price_count: usize,
117}
118
119// ── Bulk classify-inbound-income plan (bulk-classify-inbound-income, Cycle 4) ─
120//
121// The shared, READ-ONLY plan both the CLI (`cmd::reconcile::bulk_classify_income_plan`) and the TUI
122// `I` flow compute from the HELD session. A NEAR-CLONE of `bulk_self_transfer_in_plan` with ONE
123// load-bearing difference [#a tax-safety]: a candidate whose `fmv_of(date, sat)` is `None` (no bundled
124// price / overflow) is EXCLUDED from `included` (counted in `excluded_missing_price`), NOT included —
125// because a persisted `InboundClass::Income { fmv: None }` projects to a Hard `FmvMissing` year-gate
126// (and on the inbound path that is NOT clearable by `ManualFmv` — the sole escape is void + reclassify).
127// So `included` carries a RESOLVED `fmv: Usd` (non-Option), making `Income{fmv:None}` structurally
128// unrepresentable from the bulk path. Appends and persists NOTHING.
129
130/// Filter narrowing which pending unknown-basis inbound deposits a bulk classify-income plan selects.
131/// Mirrors `BulkStiFilter`; `wallet` filters the RECEIVING wallet (the inbound IS the receiving leg).
132#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct BulkIncomeFilter {
134    pub frame: Frame,
135    pub wallet: Option<WalletId>,
136}
137
138/// One enriched pending unknown-basis inbound in a bulk classify-income plan, carrying a RESOLVED FMV.
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub struct BulkIncomeRow {
141    pub in_event: EventId,
142    pub date: TaxDate,
143    pub sat: Sat,
144    /// [#a] The RESOLVED auto-FMV `fmv_of(prices, date, sat)` — ALWAYS a real number (the `None`
145    /// rows are EXCLUDED upstream). This is the income recognized AND the lot basis.
146    pub fmv: Usd,
147}
148
149/// The read-only plan a bulk classify-income would execute: the eligible/in-frame `included` rows (each
150/// with a resolved `fmv`) + the count of candidates dropped for a MISSING price + preview totals.
151#[derive(Debug, Clone, PartialEq, Eq)]
152pub struct BulkIncomePlan {
153    /// Eligible + in-frame + passes `wallet` filter + HAS a price. Sorted by `date`.
154    pub included: Vec<BulkIncomeRow>,
155    /// [#a] Candidates dropped because `fmv_of == None` (surfaced, NOT silently dropped — the user
156    /// learns N inbounds could not be auto-valued as income; they stay pending).
157    pub excluded_missing_price: usize,
158    pub total_sat: Sat,
159    /// Σ `fmv` over `included` — the total income being recognized (always a real number).
160    pub total_income_usd: Usd,
161}
162
163// ── Bulk reclassify-outflow plan (bulk-reclassify-outflow, Cycle 5 — the LAST) ─
164//
165// The shared, READ-ONLY plan both the CLI (`cmd::reconcile::bulk_reclassify_outflow_plan`) and the TUI
166// `O` flow compute from the HELD session. The bulk analog of the single `o` reclassify-outflow: it
167// sweeps MANY `pending_reconciliation` outflows to a `Dispose{Sell|Spend}` with the auto-FMV as
168// ESTIMATED proceeds. Enriches over `pending_reconciliation` exactly as `bulk_link_transfer_plan`
169// (session.rs) does. Appends/persists NOTHING.
170//
171// Load-bearing tax-safety [#a]: a candidate whose `fmv_of(date, principal_sat)` is `None` is EXCLUDED
172// (counted in `excluded_missing_price`), NOT included — `ReclassifyOutflow.principal_proceeds_or_fmv`
173// is `Usd` (NOT Option), so a missing-price row cannot be constructed WITHOUT fabricating a number, and
174// (unlike bulk-income's LOUD `FmvMissing`) a fabricated/`0` proceeds would be SILENT (gates nothing,
175// misreports gain/loss). So `included` carries a RESOLVED `fmv: Usd` (non-Option) — the load-bearing
176// structural defense, mirroring `BulkIncomeRow.fmv: Usd`.
177//
178// Estimated gain [Q3]: `basis_usd = Σ pt.legs.usd_basis` (already computed by the fold's SINGLE
179// chronological pass with all N candidate PendingOuts pending, so `Σ` over multiple rows' legs is NEVER
180// double-counted — an earlier-dated PendingOut has already drawn the pool down before a later one
181// folds). `estimated_gain = round_cents(fmv − basis_usd)` per row. Precedent: `bulk_link_transfer_plan`
182// already sums `pt.legs.usd_basis`.
183
184/// One enriched pending outbound transfer in a bulk reclassify-outflow plan, carrying a RESOLVED FMV.
185#[derive(Debug, Clone, PartialEq, Eq)]
186pub struct BulkReclassifyOutflowRow {
187    pub out_event: EventId,
188    pub date: TaxDate,
189    /// [R0-N1] ALWAYS `Some` for a pending out (a wallet-less TransferOut never reaches
190    /// `pending_reconciliation`); `Option` kept defensively (mirror `BulkLinkRow.source_wallet`).
191    pub wallet: Option<WalletId>,
192    pub principal_sat: Sat,
193    /// [#a] The RESOLVED auto-FMV `fmv_of(prices, date, principal_sat)` — ALWAYS a real number (the
194    /// `None` rows are EXCLUDED upstream). This is the ESTIMATED proceeds a `Dispose` recognizes.
195    pub fmv: Usd,
196    /// Σ leg `usd_basis` carried by the fold's PendingOut consumption (the disposal's basis).
197    pub basis_usd: Usd,
198    /// `round_cents(fmv − basis_usd)` — the per-row ESTIMATED gain (never double-counted; see above).
199    pub estimated_gain: Usd,
200}
201
202/// The read-only plan a bulk reclassify-outflow would execute: the eligible/in-frame `included` rows
203/// (each with a resolved `fmv`), the count of candidates dropped for a MISSING price, and preview
204/// totals. Mirrors `BulkIncomePlan`.
205#[derive(Debug, Clone, PartialEq, Eq)]
206pub struct BulkReclassifyOutflowPlan {
207    /// Eligible + in-frame + passes `from_wallet` filter + HAS a price. Sorted by `date`.
208    pub included: Vec<BulkReclassifyOutflowRow>,
209    /// [#a] Candidates dropped because `fmv_of == None` (surfaced, NOT silently dropped — a Sell with
210    /// fabricated proceeds would be a SILENT misreport; they stay pending).
211    pub excluded_missing_price: usize,
212    pub total_sat: Sat,
213    /// Σ `fmv` over `included` — the total ESTIMATED proceeds (always a real number).
214    pub total_proceeds_usd: Usd,
215    /// Σ `basis_usd` over `included`.
216    pub total_basis_usd: Usd,
217    /// Σ `estimated_gain` over `included` — the total ESTIMATED gain shown in the preview.
218    pub total_estimated_gain: Usd,
219}
220
221// ── Bulk resolve-conflict plan (bulk-resolve-conflict D1) ────────────────────
222//
223// The shared, READ-ONLY plan both the CLI (`cmd::reconcile::bulk_resolve_conflict_plan`) and the TUI
224// `C` flow compute from the HELD session. Candidate set = live `ImportConflict` blockers only (engine
225// post-filtered — an accepted/rejected conflict is no longer flagged → structural idempotence). Each
226// row carries the STRUCTURED current/new payloads (NOT pre-rendered strings) so each front-end renders
227// its own summary (CLI table formatter; TUI reuses `import_payload_summary`). Appends/persists NOTHING.
228
229/// One flagged import conflict in a bulk resolve-conflict plan. STRUCTURED (front-ends render summaries).
230#[derive(Debug, Clone, PartialEq, Eq)]
231pub struct BulkResolveRow {
232    /// The `ImportConflict` event id — the resolution target (`SupersedeImport`/`RejectImport` carry
233    /// this as `conflict_event`).
234    pub conflict_event: EventId,
235    /// Calendar date (tax tz) of the conflict event.
236    pub date: TaxDate,
237    /// The TARGET import event id whose payload the conflict proposes to supersede (≠ conflict_event).
238    pub target: EventId,
239    /// Payload currently at the target (front-end renders "current"; KEPT on reject).
240    pub current_payload: EventPayload,
241    /// `ImportConflict.new_payload` (front-end renders "→ new"; ADOPTED on accept).
242    pub new_payload: EventPayload,
243    /// The 8-char `new_fingerprint` disambiguator (front-end shows it).
244    pub new_fingerprint: String,
245}
246
247/// The read-only plan a bulk resolve-conflict would execute: the live `ImportConflict` rows (sorted by
248/// date). No $ number (a conflict resolution recognizes no gain); no time/wallet filter (per-row
249/// exclude is the precision tool at the front-end).
250#[derive(Debug, Clone, PartialEq, Eq)]
251pub struct BulkResolvePlan {
252    pub rows: Vec<BulkResolveRow>,
253}
254
255// ── Bulk void plan (bulk-void D1) ────────────────────────────────────────────
256//
257// The shared, READ-ONLY plan both the CLI (`cmd::reconcile::bulk_void_plan`) and the TUI `V` sweep
258// compute from the HELD session. Candidate set = the SINGLE shared predicate `voidable_decisions`
259// (btctax-core) over the projected events + blockers — the ONLY defense against voiding an EFFECTIVE
260// `SafeHarborAllocation` (#7 → Hard `DecisionConflict`). Each row carries the STRUCTURED decision
261// `payload` (front-ends render `summarize_void_payload`) + the precomputed `disposal_to_clear` (a
262// `LotSelection` target → `ls.disposal_event`) so the persist path never re-loads the log per row.
263// Appends/persists NOTHING; mirrors `bulk_resolve_conflict_plan`.
264
265/// One voidable reconcile decision in a bulk-void plan. STRUCTURED (front-ends render summaries).
266#[derive(Debug, Clone, PartialEq, Eq)]
267pub struct BulkVoidRow {
268    /// The Decision event id to void (`VoidDecisionEvent.target_event_id`).
269    pub target_event_id: EventId,
270    /// `decision|seq` sequence number (display + deterministic sort).
271    pub seq: u64,
272    /// Calendar date (tax tz) of the decision event.
273    pub date: TaxDate,
274    /// The decision's payload — front-ends render `summarize_void_payload` (tag + what the void undoes).
275    pub payload: EventPayload,
276    /// Precomputed side-effect target: a `LotSelection` target → `Some(ls.disposal_event)` (whose
277    /// optimizer attestation the void clears); every other decision → `None`.
278    pub disposal_to_clear: Option<EventId>,
279}
280
281/// The read-only plan a bulk-void would execute: the voidable decisions (shared predicate), sorted by
282/// `seq`. No $ number (a void recognizes no gain); no time/wallet filter (per-row exclude is the
283/// front-end precision tool).
284#[derive(Debug, Clone, PartialEq, Eq)]
285pub struct BulkVoidPlan {
286    pub rows: Vec<BulkVoidRow>,
287}
288
289// ── Self-transfer matcher (self-transfer-passthrough C2) ─────────────────────
290//
291// A READ-ONLY proposal helper (mirrors `bulk_link_transfer_plan`/`safe_harbor_residue`): it appends and
292// persists NOTHING. It pairs ONLY UNRECONCILED legs — candidate ins are `TransferIn`s still flagged
293// `UnknownBasisInbound` (an already-classified income / self-transfer-in is no longer flagged, so it is
294// structurally excluded), candidate outs are `pending_reconciliation` entries (an already-reclassified
295// sale is no longer pending). The user CONFIRMS every match; nothing is written by this helper.
296
297/// The confirm action a matched self-transfer pair resolves to.
298#[derive(Debug, Clone, Copy, PartialEq, Eq)]
299pub enum MatchAction {
300    /// Same tracked wallet on both legs (both counterparties external): DROP → `SelfTransferPassthrough`.
301    Drop,
302    /// Different tracked wallets (out from X, in to Y, X≠Y): RELOCATE → the EXISTING `TransferLink` out→in.
303    Relocate,
304}
305
306/// One proposed self-transfer match (C2). A PROPOSAL — never applied until the user confirms it.
307#[derive(Debug, Clone, PartialEq, Eq)]
308pub struct MatchProposal {
309    pub in_event: EventId,
310    pub out_event: EventId,
311    pub in_date: TaxDate,
312    pub out_date: TaxDate,
313    /// The in-leg's wallet (the RELOCATE destination). `None` legs are never proposed (can't relocate /
314    /// can't be same-wallet), so this is always `Some` for a real proposal; `Option` kept defensively.
315    pub in_wallet: Option<WalletId>,
316    /// The out-leg's (source) wallet. Always `Some` for a pending out; `Option` kept defensively.
317    pub out_wallet: Option<WalletId>,
318    pub in_sat: Sat,
319    pub out_principal_sat: Sat,
320    /// `fmv_of(prices, out_date, out_principal_sat)` — advisory, `None` on missing price / overflow.
321    pub usd_value: Option<Usd>,
322    /// Suggested action from wallet topology (same-wallet ⇒ Drop, cross-tracked-wallet ⇒ Relocate).
323    pub action: MatchAction,
324    /// True when this in OR this out matches >1 counterpart — surfaced FLAGGED, NEVER auto-picked (G-FALSE-MATCH).
325    pub ambiguous: bool,
326    /// True when `in.txid == out.txid` (both `Some`) — decisive cross-wallet corroboration (relaxes the
327    /// amount check, but NOT the ambiguity guard).
328    pub txid_match: bool,
329}
330
331pub struct Session {
332    vault: Vault,
333    /// The active price provider (§9.2 bundled daily-close dataset, cache-layered in Part C). The
334    /// projection and every priced plan read prices through THIS instance seam [R0-C1/r2 I-A] rather
335    /// than a hard-wired `BundledPrices::load()`, so tests inject a CONTROLLED synthetic dataset
336    /// (`set_prices`) — decoupling their asserted FMVs from the shipped data. Pure/deterministic; the
337    /// default is the layered bundled+cache provider (resolved at open time).
338    prices: Box<dyn PriceProvider>,
339}
340
341impl std::fmt::Debug for Session {
342    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
343        f.debug_struct("Session").finish_non_exhaustive()
344    }
345}
346
347/// Build the DEFAULT price provider a freshly-opened `Session` carries: the bundled daily-close dataset
348/// (§9.2) with the local price cache layered OVER it (Part C — cache-over-bundled; cache absent ⇒
349/// byte-identical to bundled-only). Pure/deterministic; NO network — the cache is a documented LOCAL
350/// INPUT populated only by the separate `btctax-update-prices` binary. The cache PATH is resolved HERE
351/// (btctax-cli, via `dirs`), NOT in btctax-adapters.
352fn default_prices() -> Result<Box<dyn PriceProvider>, CliError> {
353    let cache_path = crate::price_cache::default_cache_path();
354    Ok(Box::new(btctax_adapters::LayeredPrices::load_with_cache(
355        cache_path.as_deref(),
356    )?))
357}
358
359impl Session {
360    /// Create a brand-new encrypted vault, then initialize the core event schema and the CLI config
361    /// table, and persist. (`Vault::create` already saved once; we re-save after the DDL.)
362    pub fn create(vault_path: &Path, pp: &Passphrase) -> Result<Session, CliError> {
363        Self::from_fresh_vault(Vault::create(vault_path, pp)?)
364    }
365
366    /// Like `create`, but first clears a half-created vault (orphan key, no pgp/bak) under
367    /// explicit `--repair` consent. Delegates to `Vault::repair` which refuses if a real or
368    /// recoverable vault is present (see `Vault::repair` safety invariant).
369    pub fn repair(vault_path: &Path, pp: &Passphrase) -> Result<Session, CliError> {
370        Self::from_fresh_vault(Vault::repair(vault_path, pp)?)
371    }
372
373    /// Initialize the core schema + CLI config + tax profile table on a freshly-created vault,
374    /// then persist.
375    fn from_fresh_vault(mut vault: Vault) -> Result<Session, CliError> {
376        init_schema(vault.conn())?;
377        config::init_config_table(vault.conn())?;
378        tax_profile::init_table(vault.conn())?;
379        optimize_attest::init_table(vault.conn())?;
380        donation_details::init_table(vault.conn())?;
381        bulk_estimated::init_table(vault.conn())?;
382        vault.save()?;
383        Ok(Session {
384            vault,
385            prices: default_prices()?,
386        })
387    }
388
389    /// Open an existing vault (acquires the store single-instance lock; NFR7). A pathless I/O failure
390    /// (missing/unreadable `--vault`) is enriched with the path + a one-clause hint (UX-P4-8).
391    pub fn open(vault_path: &Path, pp: &Passphrase) -> Result<Session, CliError> {
392        let vault = Vault::open(vault_path, pp)
393            .map_err(|e| crate::store_io_with_path(e, vault_path, crate::VAULT_OPEN_HINT))?;
394        Ok(Session {
395            vault,
396            prices: default_prices()?,
397        })
398    }
399
400    /// Borrow the active price provider (§9.2). The projection and every priced plan read prices
401    /// through this instance seam [R0-C1].
402    pub fn prices(&self) -> &dyn PriceProvider {
403        self.prices.as_ref()
404    }
405
406    /// The lots available in `wallet` JUST BEFORE the disposal/removal/self-transfer `event` — the true
407    /// at-disposal pool the engine validates a specific-lot pick against (`btctax_core::optimize::
408    /// available_lots_before` over the current ledger). The interactive editor builds its select-lots
409    /// candidate rows from this (NOT the post-default residue), so the form offers exactly the lots — and
410    /// amounts — the engine's `selection_feasible` accepts (walkthrough J9 review C1..I3).
411    pub fn available_lots_before(
412        &self,
413        event: &btctax_core::EventId,
414        date: btctax_core::conventions::TaxDate,
415        wallet: &btctax_core::WalletId,
416    ) -> Result<Vec<btctax_core::Lot>, CliError> {
417        // Load events + config only — NOT a full projection. `optimize::available_lots_before` runs its own
418        // `resolve` + `pools_before` clone-fold internally, so projecting here (and discarding the state)
419        // would just double the fold on every interactive keypress (SL-r2-c / review r2 M-2).
420        let events = load_all(self.conn())?;
421        let cfg = self.config()?.to_projection();
422        Ok(btctax_core::optimize::available_lots_before(
423            &events,
424            self.prices(),
425            &cfg,
426            event,
427            date,
428            wallet,
429        ))
430    }
431
432    /// Test / advanced seam [R0-C1/r2 I-A]: replace the price provider on an OPEN session. A KAT injects
433    /// a CONTROLLED synthetic `BundledPrices::from_csv_str(...)` so its asserted FMVs are independent of
434    /// the shipped dataset; a caller may also inject a pre-resolved layered/cache provider. Pure; no I/O.
435    pub fn set_prices(&mut self, prices: Box<dyn PriceProvider>) {
436        self.prices = prices;
437    }
438
439    /// Borrow the live in-memory SQLite handle (core appenders use interior mutability over `&Connection`).
440    pub fn conn(&self) -> &Connection {
441        self.vault.conn()
442    }
443
444    /// Persist the current DB image (encrypted, atomic; NFR2/NFR3).
445    pub fn save(&mut self) -> Result<(), CliError> {
446        self.vault.save()?;
447        Ok(())
448    }
449
450    /// Snapshot the in-memory DB image (no disk I/O) for a possible `restore()` after a failed save.
451    pub fn snapshot(&self) -> Result<Vec<u8>, CliError> {
452        Ok(self.vault.snapshot()?)
453    }
454
455    /// Restore the in-memory DB from a prior `snapshot()` (no disk I/O). On `Err`, the in-memory DB
456    /// is UNCHANGED and unsaved residue may still be live — the caller MUST latch, never swallow.
457    pub fn restore(&mut self, image: &[u8]) -> Result<(), CliError> {
458        self.vault.restore(image)?;
459        Ok(())
460    }
461
462    /// Borrow the vault for store-level operations (`export_snapshot` / `backup_key`).
463    pub fn vault(&self) -> &Vault {
464        &self.vault
465    }
466
467    /// The persisted projection config (TP8 treatment + lot method); default = (c)+FIFO if unset.
468    pub fn config(&self) -> Result<CliConfig, CliError> {
469        config::read_config(self.conn())
470    }
471
472    /// The stored per-year `TaxProfile` for `year`, or `None` if none has been set.
473    /// Robust to older vaults (calls `tax_profile::init_table` as a defensive guard).
474    pub fn tax_profile(&self, year: i32) -> Result<Option<TaxProfile>, CliError> {
475        tax_profile::get(self.conn(), year)
476    }
477
478    /// Resolve + FULLY screen `year`'s profile through the single resolver (SPEC §4.12 / §4.10 / G4) — the
479    /// shared entry point every computing consumer (report / optimize / what-if / export) should use so
480    /// the app never shows two liabilities, or a wrong number, for one year. `state`/`tables` come from
481    /// the caller's projection (`tables` is injectable so `accept` can pass a test table for a later year).
482    pub fn resolve_screened(
483        &self,
484        state: &LedgerState,
485        year: i32,
486        tables: &dyn TaxTables,
487    ) -> Result<crate::resolve::ProfileOutcome, CliError> {
488        let pseudo = self.config()?.to_projection().pseudo_reconcile;
489        let fr = BundledFullReturnTables::load();
490        crate::resolve::resolve_and_screen(
491            self.conn(),
492            state,
493            year,
494            pseudo,
495            fr.full_return_for(year),
496            tables.table_for(year),
497        )
498    }
499
500    /// [`resolve_screened`] flattened to just the profile: an uncomputable outcome becomes a `Usage` error.
501    /// The drop-in replacement for `tax_profile(year)?` at a computing consumer that needs one figure.
502    pub fn resolve_screened_profile(
503        &self,
504        state: &LedgerState,
505        year: i32,
506        tables: &dyn TaxTables,
507    ) -> Result<Option<TaxProfile>, CliError> {
508        match self.resolve_screened(state, year, tables)? {
509            crate::resolve::ProfileOutcome::Uncomputable { detail } => Err(CliError::Usage(detail)),
510            crate::resolve::ProfileOutcome::Ready { profile, .. } => Ok(profile),
511        }
512    }
513
514    /// Resolve + screen EVERY year that has a stored `TaxProfile` or full-return `ReturnInputs`, for the
515    /// read-only viewer (which holds a `Snapshot`, not a live `Session`, so it cannot resolve on demand).
516    /// Returns per-year [`crate::resolve::ProfileOutcome`] so the TUI can render a derived number OR a
517    /// refusal — never a stale/absent profile (SPEC §4.12: the TUI is a consumer; review P2-C1).
518    pub fn resolve_all_screened(
519        &self,
520        state: &LedgerState,
521        tables: &dyn TaxTables,
522    ) -> Result<BTreeMap<i32, crate::resolve::ProfileOutcome>, CliError> {
523        // Enumerate keys WITHOUT deserializing every blob (N3: one corrupt row must not break enumeration),
524        // and hoist the config/full-return-table loads OUT of the per-year loop.
525        let pseudo = self.config()?.to_projection().pseudo_reconcile;
526        let fr = BundledFullReturnTables::load();
527        let mut years: BTreeSet<i32> = tax_profile::years(self.conn())?.into_iter().collect();
528        years.extend(return_inputs::years(self.conn())?);
529        let mut out = BTreeMap::new();
530        for year in years {
531            // A corrupt side-table blob for ONE year must surface as a per-year refusal, NOT a failure that
532            // bricks the whole read-only viewer (fail-closed availability — review N3).
533            let outcome = match crate::resolve::resolve_and_screen(
534                self.conn(),
535                state,
536                year,
537                pseudo,
538                fr.full_return_for(year),
539                tables.table_for(year),
540            ) {
541                Ok(o) => o,
542                Err(e) => crate::resolve::ProfileOutcome::Uncomputable {
543                    detail: format!("could not read the stored inputs for {year}: {e}"),
544                },
545            };
546            out.insert(year, outcome);
547        }
548        Ok(out)
549    }
550
551    /// All stored `TaxProfile`s, sorted by year ascending.
552    pub fn all_tax_profiles(
553        &self,
554    ) -> Result<std::collections::BTreeMap<i32, TaxProfile>, CliError> {
555        tax_profile::all(self.conn())
556    }
557
558    /// All attested disposal `EventId`s (NFR4-stable `BTreeSet`; feeds `compliance_overlay`).
559    /// Robust to older vaults (defensive `init_table` guard inside `attested_set`).
560    pub fn optimize_attested_set(
561        &self,
562    ) -> Result<std::collections::BTreeSet<btctax_core::EventId>, CliError> {
563        optimize_attest::attested_set(self.conn())
564    }
565
566    /// All stored `DonationDetails`, keyed by donation `EventId` (NFR4-stable `BTreeMap`).
567    /// Robust to older vaults (defensive `init_table` guard inside `donation_details::all`).
568    pub fn donation_details(
569        &self,
570    ) -> Result<std::collections::BTreeMap<EventId, DonationDetails>, CliError> {
571        donation_details::all(self.conn())
572    }
573
574    /// All disposals flagged as estimated-FMV proceeds by the bulk-reclassify-outflow path, keyed by
575    /// the `transfer_out_event` (== `Disposal.event`); value = the `date_marked` provenance stamp
576    /// (NFR4-stable `BTreeMap`). Robust to older vaults (defensive `init_table` guard inside
577    /// `bulk_estimated::all`). `build_snapshot` loads the `[est]` marker set via THIS accessor,
578    /// NEVER `conn()` directly [R0-M1].
579    pub fn bulk_estimated(&self) -> Result<std::collections::BTreeMap<EventId, String>, CliError> {
580        bulk_estimated::all(self.conn())
581    }
582
583    /// Load all events and run the pure deterministic projection (NFR4) over the bundled daily-close
584    /// dataset (§9.2). Returns the resolved `ProjectionConfig` too (so `verify` can display it).
585    pub fn project(&self) -> Result<(LedgerState, ProjectionConfig), CliError> {
586        let events = load_all(self.conn())?;
587        let cfg = self.config()?.to_projection();
588        let prices = self.prices();
589        let state = project(&events, prices, &cfg);
590        Ok((state, cfg))
591    }
592
593    /// Single-load variant: loads events ONCE and returns them alongside the projection. Callers
594    /// that need both the raw event log and the projected state (e.g. `verify`, `safe_harbor_attest`)
595    /// use this to avoid the double `load_all` call that the `project()` + separate `load_all()`
596    /// pattern incurs.
597    pub fn load_events_and_project(
598        &self,
599    ) -> Result<(Vec<LedgerEvent>, LedgerState, ProjectionConfig), CliError> {
600        let events = load_all(self.conn())?;
601        let cfg = self.config()?.to_projection();
602        let prices = self.prices();
603        let state = project(&events, prices, &cfg);
604        Ok((events, state, cfg))
605    }
606
607    /// §A.5(a): the distinct Exchange accounts in the vault, each with its currently-in-force
608    /// cost-basis method and whether that method is an explicit per-account election (`true`) vs
609    /// inherited from a global election / the HIFO default (`false`), as of `date`. Feeds the
610    /// btctax-tui-edit method-election flow's account list. Uses the SHARED resolver via
611    /// `btctax_core::in_force_methods` (the sole precedence path). Sorted by `WalletId: Ord`.
612    pub fn exchange_method_election_rows(
613        &self,
614        date: TaxDate,
615    ) -> Result<Vec<(WalletId, LotMethod, bool)>, CliError> {
616        let events = load_all(self.conn())?;
617        let cfg = self.config()?.to_projection();
618        let prices = self.prices();
619        // Distinct Exchange wallets (BTreeSet dedups AND sorts — NFR4).
620        let wallets: Vec<WalletId> = events
621            .iter()
622            .filter_map(|e| e.wallet.clone())
623            .filter(|w| matches!(w, WalletId::Exchange { .. }))
624            .collect::<std::collections::BTreeSet<_>>()
625            .into_iter()
626            .collect();
627        let methods = btctax_core::in_force_methods(&events, prices, &cfg, date, &wallets);
628        Ok(wallets
629            .into_iter()
630            .zip(methods)
631            .map(|(w, m)| (w, m.method, m.scoped))
632            .collect())
633    }
634
635    /// Recompute the Mode-1 optimizer proposal for `year` on the HELD session. READ-ONLY: appends and
636    /// persists NOTHING (a clone-fold-discard recompute).
637    ///
638    /// The TUI editor's optimize-accept opener calls this to obtain a FRESH proposal (NFR4 — never
639    /// trusts a stale one) WITHOUT opening a second `Session` (a second open would deadlock on the
640    /// held VaultLock, and `cmd::optimize::accept` is forbidden to the editor for the same reason).
641    /// Assembles `optimize_year`'s inputs exactly as `cmd::optimize::run`/`accept` do — events + config
642    /// from this conn, bundled prices + tables, a FRESH `tax_profile(year)` read (not the cached snap),
643    /// the attested set, and `proposal_made = tax_date(now, UtcOffset::UTC)` — and maps `OptimizeError`
644    /// through the crate-internal `map_opt_err` (which is `pub(crate)` and not TUI-reachable). `now`
645    /// is injected by the caller for determinism.
646    pub fn optimize_proposal(
647        &self,
648        year: i32,
649        now: time::OffsetDateTime,
650    ) -> Result<btctax_core::OptimizeProposal, CliError> {
651        let (events, state, cfg) = self.load_events_and_project()?;
652        let prices = self.prices();
653        let tables = BundledTaxTables::load();
654        let profile = self.resolve_screened_profile(&state, year, &tables)?;
655        let attested = self.optimize_attested_set()?;
656        let proposal_made = tax_date(now, time::UtcOffset::UTC);
657        btctax_core::optimize_year(
658            &events,
659            prices,
660            &cfg,
661            year,
662            profile.as_ref(),
663            &tables,
664            &attested,
665            proposal_made,
666        )
667        .map_err(crate::cmd::optimize::map_opt_err)
668    }
669
670    /// READ-ONLY: the 2025-01-01 pre-2025 Universal residue as `AllocLot`s, plus the `pre2025_method`
671    /// (`LotMethod`) it was computed under. Appends/persists NOTHING. The single source of the pre-2025
672    /// subset, shared by `cmd::reconcile::safe_harbor_allocate` and the TUI allocate opener.
673    ///
674    /// Reads the config ONCE: `cfg.pre2025_method` is the recorded method returned to the caller, and
675    /// `cfg.to_projection()` is the projection the residue is computed under — the two are STRUCTURALLY
676    /// the same config read, so the returned method can never diverge from the residue's [R0-M1]. The
677    /// pre-2025 subset keeps only imports whose tax-date `< 2025-01-01` plus ALL reconciliation decisions
678    /// (which shape the residue), and DROPs any prior `SafeHarborAllocation` so the residue stays
679    /// allocation-INDEPENDENT (matches `transition::universal_snapshot`).
680    pub fn safe_harbor_residue(&self) -> Result<(Vec<AllocLot>, LotMethod), CliError> {
681        let cfg = self.config()?;
682        let pre2025_method = cfg.pre2025_method; // recorded field == the one used below
683        let proj = cfg.to_projection();
684        let all = load_all(self.conn())?;
685        // T16 follow-up (arch r1 Minor 3 / tax r1 Minor 4): a pre-2025 tranche makes a safe-harbor
686        // allocation mutually-exclusive (D-8), so there is NO valid allocatable residue — and the residue
687        // projection below (which DROPs the tranche but keeps pre-2025 disposals that may have consumed its
688        // sats) would DISPLAY an understated/empty residue in the TUI allocate opener. Refuse opening the
689        // flow entirely, mirroring the record-time allocation guard: the CLI allocate path already refuses
690        // via `guard_allocation_vs_tranche` before reaching here, and the TUI opener surfaces this Err as
691        // its pre-flight status rather than showing a misleading residue.
692        if crate::cmd::tranche::pre2025_tranche_exists(&all) {
693            return Err(CliError::Usage(
694                "cannot open the safe-harbor allocate flow: a pre-2025 conservative-filing tranche ($0 \
695                 EstimatedConservative) is on file — v1 makes a tranche and a safe-harbor allocation \
696                 mutually exclusive (D-8). Void the tranche first (`reconcile void <decision-ref>`); if \
697                 you have already filed the tranche's $0 basis, unallocated pre-2025 units are a \
698                 facts-and-circumstances matter for a professional."
699                    .to_string(),
700            ));
701        }
702        let pre2025: Vec<LedgerEvent> = all
703            .into_iter()
704            .filter(|e| match &e.id {
705                EventId::Import { .. } => {
706                    tax_date(e.utc_timestamp, e.original_tz) < TRANSITION_DATE
707                }
708                // D-8: DROP SafeHarborAllocation (residue stays allocation-INDEPENDENT) AND DeclareTranche
709                // (a $0 conservative-filing tranche is NOT allocatable pre-2025 residue — else the allocate
710                // opener would self-poison by listing the tranche's $0 sats, authoring the very coexistence
711                // v1 forbids). A pre-2025 tranche makes the allocation refuse anyway; excluding it here keeps
712                // the opener honest and stops a ≥2025 tranche's post-transition lot from leaking in.
713                _ => !matches!(
714                    e.payload,
715                    EventPayload::SafeHarborAllocation(_) | EventPayload::DeclareTranche(_)
716                ),
717            })
718            .collect();
719        let prices = self.prices();
720        let residue = project(&pre2025, prices, &proj);
721        let lots = residue
722            .lots
723            .iter()
724            .filter(|l| l.remaining_sat > 0)
725            .map(|l| AllocLot {
726                wallet: l.wallet.clone(),
727                sat: l.remaining_sat,
728                usd_basis: l.usd_basis,
729                acquired_at: l.acquired_at,
730                dual_loss_basis: l.dual_loss_basis,
731                donor_acquired_at: l.donor_acquired_at,
732            })
733            .collect();
734        Ok((lots, pre2025_method))
735    }
736
737    /// READ-ONLY: compute the bulk link-transfer plan (bulk-link-transfer D1). Selects over the
738    /// PROJECTED `pending_reconciliation` (which already excludes already-decided / already-linked
739    /// outs), enriches each with date / source wallet / principal / advisory USD value / carried
740    /// basis, applies the frame + `from_wallet` filters, and routes `source == dest` rows to
741    /// `skipped_same_wallet`. Appends and persists NOTHING; mirrors `safe_harbor_residue`.
742    ///
743    /// The USD value is `btctax_core::price::fmv_of(prices, date, principal_sat)` [R0-M1] — the
744    /// vetted checked helper (round_cents + overflow→`None`), NOT a hand-rolled `principal × price`.
745    /// The total is the HONEST FLOOR [R0-I2]: `total_usd_value_floor` is Σ of the PRICED rows only,
746    /// and `missing_price_count` records how many rows lacked a price, so the caller renders exact
747    /// `$X` (when 0) or `≥ $X (N unavailable)`.
748    pub fn bulk_link_transfer_plan(
749        &self,
750        filter: BulkFilter,
751        dest: WalletId,
752    ) -> Result<BulkLinkPlan, CliError> {
753        let (events, state, _cfg) = self.load_events_and_project()?;
754        let prices = self.prices();
755        let index: std::collections::HashMap<EventId, &LedgerEvent> =
756            events.iter().map(|e| (e.id.clone(), e)).collect();
757
758        let enrich = |pt: &PendingTransfer| -> BulkLinkRow {
759            let ev = index.get(&pt.event).copied();
760            let date = ev
761                .map(|e| tax_date(e.utc_timestamp, e.original_tz))
762                .unwrap_or_else(|| {
763                    // Defensive: a pending out always has an indexed source event; fall back to the
764                    // epoch date rather than panic (mirrors the single link-transfer opener).
765                    tax_date(
766                        time::OffsetDateTime::from_unix_timestamp(0).unwrap(),
767                        time::UtcOffset::UTC,
768                    )
769                });
770            let source_wallet = ev.and_then(|e| e.wallet.clone());
771            let usd_value = btctax_core::price::fmv_of(prices, date, pt.principal_sat);
772            let basis_usd: Usd = pt.legs.iter().map(|l| l.usd_basis).sum();
773            BulkLinkRow {
774                out_event: pt.event.clone(),
775                date,
776                source_wallet,
777                principal_sat: pt.principal_sat,
778                usd_value,
779                basis_usd,
780            }
781        };
782
783        let in_frame = |date: TaxDate| match &filter.frame {
784            Frame::All => true,
785            Frame::Year(y) => date.year() == *y,
786            Frame::Range { from, to } => *from <= date && date <= *to,
787        };
788
789        let mut included: Vec<BulkLinkRow> = Vec::new();
790        let mut skipped_same_wallet: Vec<BulkLinkRow> = Vec::new();
791        for pt in &state.pending_reconciliation {
792            let row = enrich(pt);
793            if !in_frame(row.date) {
794                continue;
795            }
796            if let Some(w) = &filter.from_wallet {
797                if row.source_wallet.as_ref() != Some(w) {
798                    continue;
799                }
800            }
801            // Same-wallet guard: a self-link to the SAME wallet is meaningless — report, never link.
802            if row.source_wallet.as_ref() == Some(&dest) {
803                skipped_same_wallet.push(row);
804            } else {
805                included.push(row);
806            }
807        }
808        included.sort_by_key(|r| r.date);
809
810        let total_sat: Sat = included.iter().map(|r| r.principal_sat).sum();
811        let total_usd_value_floor: Usd = included.iter().filter_map(|r| r.usd_value).sum();
812        let missing_price_count = included.iter().filter(|r| r.usd_value.is_none()).count();
813        let total_basis_usd: Usd = included.iter().map(|r| r.basis_usd).sum();
814
815        Ok(BulkLinkPlan {
816            dest,
817            included,
818            skipped_same_wallet,
819            total_sat,
820            total_usd_value_floor,
821            missing_price_count,
822            total_basis_usd,
823        })
824    }
825
826    /// READ-ONLY: compute the bulk classify-inbound-self-transfer plan
827    /// (bulk-classify-inbound-self-transfer D1). A close MIRROR of `bulk_link_transfer_plan` applied to
828    /// Cycle A's inbound `SelfTransferMine` ($0 conservative basis, non-taxable). Appends/persists
829    /// NOTHING (clone-fold-discard recompute); KAT-G1-clean at the TUI call site.
830    ///
831    /// **Selection (structural false-classify safety) [R0-I1]:** candidates are `TransferIn` events
832    /// still flagged `UnknownBasisInbound` (blocker set joined to the raw event via the index, as
833    /// `self_transfer_match_plan` does) **MINUS** any already targeted by a NON-VOIDED `ClassifyInbound`
834    /// (mirror `open_classify_inbound_flow`'s filter 3 — appending a second fires a return-blocking Hard
835    /// `DecisionConflict`; `UnknownBasisInbound` is RE-EMITTED for gift-basis-unknown states, so
836    /// "flagged" ≠ "unclassified") **MINUS** wallet-less inbounds [R0-M2] (create no lot). The USD is
837    /// `fmv_of` [G4]; the total is the HONEST FLOOR (`total_usd_fmv_floor` + `missing_price_count`).
838    pub fn bulk_self_transfer_in_plan(
839        &self,
840        filter: BulkStiFilter,
841    ) -> Result<BulkStiPlan, CliError> {
842        let (events, state, _cfg) = self.load_events_and_project()?;
843        let prices = self.prices();
844        let index: std::collections::HashMap<EventId, &LedgerEvent> =
845            events.iter().map(|e| (e.id.clone(), e)).collect();
846
847        // [R0-I1] filter-3, mirroring `open_classify_inbound_flow`: the set of TransferIn event ids
848        // already targeted by a NON-VOIDED `ClassifyInbound`. Build the voided-decision-id set first,
849        // then keep only ClassifyInbounds whose OWN id is not voided [R0-M-r2-1: decision-id space and
850        // TransferIn-id space are disjoint; we intersect a decision's own id against `voided`, and map
851        // the survivor to its `transfer_in_event`].
852        let voided: std::collections::BTreeSet<EventId> = events
853            .iter()
854            .filter_map(|e| match &e.payload {
855                EventPayload::VoidDecisionEvent(v) => Some(v.target_event_id.clone()),
856                _ => None,
857            })
858            .collect();
859        let already_classified: std::collections::BTreeSet<EventId> = events
860            .iter()
861            .filter(|e| !voided.contains(&e.id))
862            .filter_map(|e| match &e.payload {
863                EventPayload::ClassifyInbound(ci) => Some(ci.transfer_in_event.clone()),
864                _ => None,
865            })
866            .collect();
867
868        let in_frame = |date: TaxDate| match &filter.frame {
869            Frame::All => true,
870            Frame::Year(y) => date.year() == *y,
871            Frame::Range { from, to } => *from <= date && date <= *to,
872        };
873
874        let mut included: Vec<BulkStiRow> = Vec::new();
875        for b in &state.blockers {
876            if b.kind != BlockerKind::UnknownBasisInbound {
877                continue;
878            }
879            let Some(id) = &b.event else { continue };
880            // [R0-I1] EXCLUDE any inbound that already carries a live ClassifyInbound (else the bulk
881            // append duplicates it → Hard DecisionConflict blocks compute_tax_year).
882            if already_classified.contains(id) {
883                continue;
884            }
885            let Some(ev) = index.get(id) else { continue };
886            let EventPayload::TransferIn(ti) = &ev.payload else {
887                continue;
888            };
889            // [R0-M2] EXCLUDE wallet-less inbounds — a self-transfer-in creates no lot and re-fires
890            // the blocker (matcher skips them too).
891            let Some(wallet) = ev.wallet.clone() else {
892                continue;
893            };
894            let date = tax_date(ev.utc_timestamp, ev.original_tz);
895            if !in_frame(date) {
896                continue;
897            }
898            if let Some(w) = &filter.wallet {
899                if &wallet != w {
900                    continue;
901                }
902            }
903            let sat = ti.sat;
904            let usd_fmv = btctax_core::price::fmv_of(prices, date, sat);
905            included.push(BulkStiRow {
906                in_event: id.clone(),
907                date,
908                wallet: Some(wallet),
909                sat,
910                usd_fmv,
911            });
912        }
913        included.sort_by_key(|r| r.date);
914
915        let total_sat: Sat = included.iter().map(|r| r.sat).sum();
916        let total_usd_fmv_floor: Usd = included.iter().filter_map(|r| r.usd_fmv).sum();
917        let missing_price_count = included.iter().filter(|r| r.usd_fmv.is_none()).count();
918
919        Ok(BulkStiPlan {
920            included,
921            total_sat,
922            total_usd_fmv_floor,
923            missing_price_count,
924        })
925    }
926
927    /// READ-ONLY: compute the bulk classify-inbound-income plan (bulk-classify-inbound-income, Cycle 4).
928    /// A NEAR-CLONE of `bulk_self_transfer_in_plan`: candidates are `TransferIn`s still flagged
929    /// `UnknownBasisInbound` MINUS any already targeted by a NON-VOIDED `ClassifyInbound` (filter-3;
930    /// a second `ClassifyInbound` fires a Hard `DecisionConflict`) MINUS wallet-less inbounds (create no
931    /// lot; also a Hard-`FmvMissing` vector). Then the **Cycle-4 tax-safety difference [#a]**: any
932    /// candidate whose `fmv_of(date, sat)` is `None` (missing daily-close price OR overflow) is EXCLUDED
933    /// from `included` and counted in `excluded_missing_price` — a persisted `Income{fmv:None}` projects
934    /// to a Hard `FmvMissing` year-gate (NOT clearable by `ManualFmv` on the inbound path). `included`
935    /// therefore carries a RESOLVED `fmv: Usd` (non-Option). Appends/persists NOTHING.
936    pub fn bulk_classify_income_plan(
937        &self,
938        filter: BulkIncomeFilter,
939    ) -> Result<BulkIncomePlan, CliError> {
940        let (events, state, _cfg) = self.load_events_and_project()?;
941        let prices = self.prices();
942        let index: std::collections::HashMap<EventId, &LedgerEvent> =
943            events.iter().map(|e| (e.id.clone(), e)).collect();
944
945        // filter-3, mirroring `bulk_self_transfer_in_plan`: the set of TransferIn ids already targeted
946        // by a NON-VOIDED `ClassifyInbound` (build the voided-decision-id set first, keep only
947        // ClassifyInbounds whose OWN id is not voided, map the survivor to its `transfer_in_event`).
948        let voided: std::collections::BTreeSet<EventId> = events
949            .iter()
950            .filter_map(|e| match &e.payload {
951                EventPayload::VoidDecisionEvent(v) => Some(v.target_event_id.clone()),
952                _ => None,
953            })
954            .collect();
955        let already_classified: std::collections::BTreeSet<EventId> = events
956            .iter()
957            .filter(|e| !voided.contains(&e.id))
958            .filter_map(|e| match &e.payload {
959                EventPayload::ClassifyInbound(ci) => Some(ci.transfer_in_event.clone()),
960                _ => None,
961            })
962            .collect();
963
964        let in_frame = |date: TaxDate| match &filter.frame {
965            Frame::All => true,
966            Frame::Year(y) => date.year() == *y,
967            Frame::Range { from, to } => *from <= date && date <= *to,
968        };
969
970        let mut included: Vec<BulkIncomeRow> = Vec::new();
971        let mut excluded_missing_price = 0usize;
972        for b in &state.blockers {
973            if b.kind != BlockerKind::UnknownBasisInbound {
974                continue;
975            }
976            let Some(id) = &b.event else { continue };
977            // filter-3: EXCLUDE any inbound already carrying a live ClassifyInbound (a second one →
978            // Hard DecisionConflict blocks compute_tax_year).
979            if already_classified.contains(id) {
980                continue;
981            }
982            let Some(ev) = index.get(id) else { continue };
983            let EventPayload::TransferIn(ti) = &ev.payload else {
984                continue;
985            };
986            // EXCLUDE wallet-less inbounds — an income inbound without a wallet creates no lot and
987            // itself raises a Hard FmvMissing (fold.rs); the matcher skips them too.
988            let Some(wallet) = ev.wallet.clone() else {
989                continue;
990            };
991            let date = tax_date(ev.utc_timestamp, ev.original_tz);
992            if !in_frame(date) {
993                continue;
994            }
995            if let Some(w) = &filter.wallet {
996                if &wallet != w {
997                    continue;
998                }
999            }
1000            let sat = ti.sat;
1001            // [#a tax-safety — the whole cycle] a candidate with no price is EXCLUDED (counted), NEVER
1002            // classified as income: an Income{fmv:None} would trade UnknownBasisInbound for a Hard
1003            // FmvMissing year-gate. bulk-sti INCLUDES these rows ($0-basis needs no FMV); bulk-income
1004            // must NOT. `included` carries the resolved non-Option fmv.
1005            match btctax_core::price::fmv_of(prices, date, sat) {
1006                Some(fmv) => included.push(BulkIncomeRow {
1007                    in_event: id.clone(),
1008                    date,
1009                    sat,
1010                    fmv,
1011                }),
1012                None => excluded_missing_price += 1,
1013            }
1014        }
1015        included.sort_by_key(|r| r.date);
1016
1017        let total_sat: Sat = included.iter().map(|r| r.sat).sum();
1018        let total_income_usd: Usd = included.iter().map(|r| r.fmv).sum();
1019
1020        Ok(BulkIncomePlan {
1021            included,
1022            excluded_missing_price,
1023            total_sat,
1024            total_income_usd,
1025        })
1026    }
1027
1028    /// READ-ONLY: compute the bulk reclassify-outflow plan (bulk-reclassify-outflow, Cycle 5). Selects
1029    /// over the PROJECTED `pending_reconciliation` (which already excludes already-reclassified / linked
1030    /// outs, and never contains wallet-less outflows), enriches each with date / source wallet /
1031    /// principal / RESOLVED auto-FMV / carried basis / estimated gain, and applies the frame +
1032    /// `from_wallet` filters. Appends/persists NOTHING (clone-fold-discard recompute); mirrors
1033    /// `bulk_link_transfer_plan` + the `bulk_classify_income_plan` `#a` missing-price exclusion.
1034    ///
1035    /// **[#a tax-safety — the whole cycle]** a candidate with no price is EXCLUDED (counted in
1036    /// `excluded_missing_price`), NEVER reclassified: `ReclassifyOutflow.principal_proceeds_or_fmv` is
1037    /// `Usd` (NOT Option), so the row could only be built by FABRICATING a `0`/bogus proceeds — a SILENT
1038    /// misreport (unlike bulk-income's LOUD `FmvMissing`). `included` therefore carries a RESOLVED
1039    /// `fmv: Usd` (non-Option), making a fabricated-proceeds Sell structurally unrepresentable here.
1040    ///
1041    /// **Estimated gain [Q3]:** `basis_usd = Σ pt.legs.usd_basis` — computed by the fold's SINGLE
1042    /// chronological pass with ALL candidate PendingOuts pending, so `Σ` over multiple rows is NEVER
1043    /// double-counted (an earlier-dated out drew the pool down before a later one folded). `estimated_gain
1044    /// = round_cents(fmv − basis_usd)` per row. The persisted Form-8949 numbers always run the ordinary
1045    /// fold (exact); only this preview carries the FIFO-vs-method / fee-treatment residual (label it).
1046    pub fn bulk_reclassify_outflow_plan(
1047        &self,
1048        filter: BulkFilter,
1049    ) -> Result<BulkReclassifyOutflowPlan, CliError> {
1050        let (events, state, _cfg) = self.load_events_and_project()?;
1051        let prices = self.prices();
1052        let index: std::collections::HashMap<EventId, &LedgerEvent> =
1053            events.iter().map(|e| (e.id.clone(), e)).collect();
1054
1055        let in_frame = |date: TaxDate| match &filter.frame {
1056            Frame::All => true,
1057            Frame::Year(y) => date.year() == *y,
1058            Frame::Range { from, to } => *from <= date && date <= *to,
1059        };
1060
1061        let mut included: Vec<BulkReclassifyOutflowRow> = Vec::new();
1062        let mut excluded_missing_price = 0usize;
1063        for pt in &state.pending_reconciliation {
1064            let ev = index.get(&pt.event).copied();
1065            let date = ev
1066                .map(|e| tax_date(e.utc_timestamp, e.original_tz))
1067                .unwrap_or_else(|| {
1068                    // Defensive: a pending out always has an indexed source event; fall back to the
1069                    // epoch date rather than panic (mirrors `bulk_link_transfer_plan`).
1070                    tax_date(
1071                        time::OffsetDateTime::from_unix_timestamp(0).unwrap(),
1072                        time::UtcOffset::UTC,
1073                    )
1074                });
1075            if !in_frame(date) {
1076                continue;
1077            }
1078            let wallet = ev.and_then(|e| e.wallet.clone());
1079            if let Some(w) = &filter.from_wallet {
1080                if wallet.as_ref() != Some(w) {
1081                    continue;
1082                }
1083            }
1084            // [#a] EXCLUDE (count) a missing-price row — a Sell with fabricated proceeds is a SILENT
1085            // misreport. `included` carries the resolved non-Option fmv.
1086            let fmv = match btctax_core::price::fmv_of(prices, date, pt.principal_sat) {
1087                Some(v) => v,
1088                None => {
1089                    excluded_missing_price += 1;
1090                    continue;
1091                }
1092            };
1093            let basis_usd: Usd = pt.legs.iter().map(|l| l.usd_basis).sum();
1094            let estimated_gain = round_cents(fmv - basis_usd);
1095            included.push(BulkReclassifyOutflowRow {
1096                out_event: pt.event.clone(),
1097                date,
1098                wallet,
1099                principal_sat: pt.principal_sat,
1100                fmv,
1101                basis_usd,
1102                estimated_gain,
1103            });
1104        }
1105        included.sort_by_key(|r| r.date);
1106
1107        let total_sat: Sat = included.iter().map(|r| r.principal_sat).sum();
1108        let total_proceeds_usd: Usd = included.iter().map(|r| r.fmv).sum();
1109        let total_basis_usd: Usd = included.iter().map(|r| r.basis_usd).sum();
1110        let total_estimated_gain: Usd = included.iter().map(|r| r.estimated_gain).sum();
1111
1112        Ok(BulkReclassifyOutflowPlan {
1113            included,
1114            excluded_missing_price,
1115            total_sat,
1116            total_proceeds_usd,
1117            total_basis_usd,
1118            total_estimated_gain,
1119        })
1120    }
1121
1122    /// READ-ONLY: compute the bulk resolve-conflict plan (bulk-resolve-conflict D1). Candidate set =
1123    /// live `ImportConflict` blockers only (engine post-filtered — an accepted/rejected conflict is no
1124    /// longer flagged, so re-running never double-resolves; structural idempotence). Joins each blocker
1125    /// (whose `.event` is the `ImportConflict` event id) to the event index to build a STRUCTURED row:
1126    /// the conflict's `target` + `new_payload` + `new_fingerprint`, plus the `current_payload` read from
1127    /// the TARGET event (a SEPARATE event — accept adopts `new_payload`, reject keeps `current_payload`).
1128    /// Appends/persists NOTHING; mirrors `bulk_self_transfer_in_plan`.
1129    pub fn bulk_resolve_conflict_plan(&self) -> Result<BulkResolvePlan, CliError> {
1130        let (events, state, _cfg) = self.load_events_and_project()?;
1131        let index: std::collections::HashMap<EventId, &LedgerEvent> =
1132            events.iter().map(|e| (e.id.clone(), e)).collect();
1133
1134        let mut rows: Vec<BulkResolveRow> = Vec::new();
1135        for b in &state.blockers {
1136            if b.kind != BlockerKind::ImportConflict {
1137                continue;
1138            }
1139            let Some(conflict_id) = &b.event else {
1140                continue;
1141            };
1142            let Some(conflict_ev) = index.get(conflict_id) else {
1143                continue;
1144            };
1145            let EventPayload::ImportConflict(c) = &conflict_ev.payload else {
1146                continue;
1147            };
1148            // CURRENT payload lives at the TARGET id (a separate event, conflict_event != target).
1149            let Some(target_ev) = index.get(&c.target) else {
1150                continue;
1151            };
1152            let date = tax_date(conflict_ev.utc_timestamp, conflict_ev.original_tz);
1153            rows.push(BulkResolveRow {
1154                conflict_event: conflict_id.clone(),
1155                date,
1156                target: c.target.clone(),
1157                current_payload: target_ev.payload.clone(),
1158                new_payload: (*c.new_payload).clone(),
1159                new_fingerprint: c.new_fingerprint.0.chars().take(8).collect::<String>(),
1160            });
1161        }
1162        rows.sort_by_key(|r| r.date);
1163        Ok(BulkResolvePlan { rows })
1164    }
1165
1166    /// READ-ONLY: compute the bulk-void plan (bulk-void D1). Candidate set = the SINGLE shared
1167    /// predicate `btctax_core::voidable_decisions` over the projected events + blockers (Decision-id ∧
1168    /// not-voided ∧ `is_revocable_payload` ∧ #7 `!effective_alloc`) — the ONLY defense against sweeping
1169    /// an EFFECTIVE `SafeHarborAllocation` into a Hard `DecisionConflict`. Each row precomputes its
1170    /// `disposal_to_clear` ONCE from the same event set (a `LotSelection` target → `ls.disposal_event`)
1171    /// so `apply_bulk_void`/`persist_bulk_void` never re-load the log per row. Appends/persists NOTHING;
1172    /// mirrors `bulk_resolve_conflict_plan`. Sorted by `seq` for deterministic display.
1173    pub fn bulk_void_plan(&self) -> Result<BulkVoidPlan, CliError> {
1174        let (events, state, _cfg) = self.load_events_and_project()?;
1175        let mut rows: Vec<BulkVoidRow> = btctax_core::voidable_decisions(&events, &state.blockers)
1176            .into_iter()
1177            .map(|e| {
1178                let seq = match &e.id {
1179                    EventId::Decision { seq } => *seq,
1180                    _ => 0,
1181                };
1182                let disposal_to_clear = match &e.payload {
1183                    EventPayload::LotSelection(ls) => Some(ls.disposal_event.clone()),
1184                    _ => None,
1185                };
1186                BulkVoidRow {
1187                    target_event_id: e.id.clone(),
1188                    seq,
1189                    date: tax_date(e.utc_timestamp, e.original_tz),
1190                    payload: e.payload.clone(),
1191                    disposal_to_clear,
1192                }
1193            })
1194            .collect();
1195        rows.sort_by_key(|r| r.seq);
1196        Ok(BulkVoidPlan { rows })
1197    }
1198
1199    /// READ-ONLY: propose self-transfer matches (self-transfer-passthrough C2). Appends/persists NOTHING
1200    /// (a clone-fold-discard recompute, like `bulk_link_transfer_plan`). Pairs ONLY unreconciled legs —
1201    /// candidate ins are `TransferIn`s flagged `UnknownBasisInbound` [R0-M2] (enumerated from the blocker
1202    /// set + joined to the raw event via the event index), candidate outs are `pending_reconciliation`.
1203    ///
1204    /// A pair is proposed iff ALL criteria pass: amount within `tol = max(out.fee_sat, ceil(0.005 ×
1205    /// out.principal))` (a `txid` EXACT match relaxes the amount check), a ±2-day window consistent with
1206    /// the direction (passthrough: in on/before out; relocate: in on/after out), and BOTH wallets present.
1207    /// The suggested `action` is wallet topology (same-wallet ⇒ Drop, cross-tracked-wallet ⇒ Relocate).
1208    /// A leg matching >1 counterpart is flagged `ambiguous` (surfaced, NEVER auto-picked — G-FALSE-MATCH).
1209    pub fn self_transfer_match_plan(&self) -> Result<Vec<MatchProposal>, CliError> {
1210        let (events, state, _cfg) = self.load_events_and_project()?;
1211        let prices = self.prices();
1212        let index: std::collections::HashMap<EventId, &LedgerEvent> =
1213            events.iter().map(|e| (e.id.clone(), e)).collect();
1214
1215        // Candidate ins: TransferIn events still flagged UnknownBasisInbound (unreconciled), joined to the
1216        // raw event via the index (the exact pattern `bulk_link_transfer_plan` uses for pending outs).
1217        struct CandIn {
1218            id: EventId,
1219            sat: Sat,
1220            txid: Option<String>,
1221            date: TaxDate,
1222            wallet: Option<WalletId>,
1223        }
1224        let mut ins: Vec<CandIn> = Vec::new();
1225        for b in &state.blockers {
1226            if b.kind != BlockerKind::UnknownBasisInbound {
1227                continue;
1228            }
1229            let Some(id) = &b.event else { continue };
1230            let Some(ev) = index.get(id) else { continue };
1231            let EventPayload::TransferIn(ti) = &ev.payload else {
1232                continue;
1233            };
1234            ins.push(CandIn {
1235                id: id.clone(),
1236                sat: ti.sat,
1237                txid: ti.txid.clone(),
1238                date: tax_date(ev.utc_timestamp, ev.original_tz),
1239                wallet: ev.wallet.clone(),
1240            });
1241        }
1242
1243        // Candidate outs: pending_reconciliation entries (already Op::PendingOut — unreconciled).
1244        struct CandOut {
1245            id: EventId,
1246            principal: Sat,
1247            fee: Option<Sat>,
1248            txid: Option<String>,
1249            date: TaxDate,
1250            wallet: Option<WalletId>,
1251        }
1252        let mut outs: Vec<CandOut> = Vec::new();
1253        for pt in &state.pending_reconciliation {
1254            let ev = index.get(&pt.event).copied();
1255            let date = ev
1256                .map(|e| tax_date(e.utc_timestamp, e.original_tz))
1257                .unwrap_or_else(|| {
1258                    tax_date(
1259                        time::OffsetDateTime::from_unix_timestamp(0).unwrap(),
1260                        time::UtcOffset::UTC,
1261                    )
1262                });
1263            let txid = ev.and_then(|e| match &e.payload {
1264                EventPayload::TransferOut(t) => t.txid.clone(),
1265                _ => None,
1266            });
1267            outs.push(CandOut {
1268                id: pt.event.clone(),
1269                principal: pt.principal_sat,
1270                fee: pt.fee_sat,
1271                txid,
1272                date,
1273                wallet: ev.and_then(|e| e.wallet.clone()),
1274            });
1275        }
1276
1277        // Passing (in_idx, out_idx, action, txid_match) tuples.
1278        let mut passing: Vec<(usize, usize, MatchAction, bool)> = Vec::new();
1279        for (i, ci) in ins.iter().enumerate() {
1280            // A wallet-less in can be neither a same-wallet DROP nor a RELOCATE destination.
1281            let Some(in_wallet) = ci.wallet.as_ref() else {
1282                continue;
1283            };
1284            for (j, co) in outs.iter().enumerate() {
1285                let Some(out_wallet) = co.wallet.as_ref() else {
1286                    continue;
1287                };
1288                let action = if in_wallet == out_wallet {
1289                    MatchAction::Drop
1290                } else {
1291                    MatchAction::Relocate
1292                };
1293                // Amount: tol = max(fee, ceil(0.005 × principal)). ceil(p/200) = (p + 199) / 200 (p ≥ 0).
1294                let slack = if co.principal > 0 {
1295                    (co.principal + 199) / 200
1296                } else {
1297                    0
1298                };
1299                let tol = co.fee.unwrap_or(0).max(slack);
1300                let txid_match = ci.txid.is_some() && ci.txid == co.txid;
1301                let amount_ok = txid_match || (ci.sat - co.principal).abs() <= tol;
1302                if !amount_ok {
1303                    continue;
1304                }
1305                // ±2-day window, direction keyed to the topology (exchange timestamp drift tolerated).
1306                let window_ok = match action {
1307                    // Passthrough: the deposit precedes the withdrawal (in on/before out).
1308                    MatchAction::Drop => {
1309                        let d = (co.date - ci.date).whole_days();
1310                        (0..=2).contains(&d)
1311                    }
1312                    // Relocate: the withdrawal precedes the arrival (in on/after out).
1313                    MatchAction::Relocate => {
1314                        let d = (ci.date - co.date).whole_days();
1315                        (0..=2).contains(&d)
1316                    }
1317                };
1318                if !window_ok {
1319                    continue;
1320                }
1321                passing.push((i, j, action, txid_match));
1322            }
1323        }
1324
1325        // Ambiguity: a leg (in OR out) appearing in >1 passing pair is flagged, never silently picked.
1326        let mut in_count: std::collections::HashMap<usize, usize> =
1327            std::collections::HashMap::new();
1328        let mut out_count: std::collections::HashMap<usize, usize> =
1329            std::collections::HashMap::new();
1330        for (i, j, _, _) in &passing {
1331            *in_count.entry(*i).or_insert(0) += 1;
1332            *out_count.entry(*j).or_insert(0) += 1;
1333        }
1334
1335        let mut proposals: Vec<MatchProposal> = passing
1336            .iter()
1337            .map(|(i, j, action, txid_match)| {
1338                let ci = &ins[*i];
1339                let co = &outs[*j];
1340                let ambiguous = in_count[i] > 1 || out_count[j] > 1;
1341                MatchProposal {
1342                    in_event: ci.id.clone(),
1343                    out_event: co.id.clone(),
1344                    in_date: ci.date,
1345                    out_date: co.date,
1346                    in_wallet: ci.wallet.clone(),
1347                    out_wallet: co.wallet.clone(),
1348                    in_sat: ci.sat,
1349                    out_principal_sat: co.principal,
1350                    usd_value: btctax_core::price::fmv_of(prices, co.date, co.principal),
1351                    action: *action,
1352                    ambiguous,
1353                    txid_match: *txid_match,
1354                }
1355            })
1356            .collect();
1357        // Deterministic order (NFR4): by out date, then the two ids.
1358        proposals.sort_by(|a, b| {
1359            a.out_date
1360                .cmp(&b.out_date)
1361                .then(a.out_event.cmp(&b.out_event))
1362                .then(a.in_event.cmp(&b.in_event))
1363        });
1364        Ok(proposals)
1365    }
1366}
1367
1368#[cfg(test)]
1369mod tests {
1370    use super::*;
1371    use btctax_store::Passphrase;
1372
1373    fn pp() -> Passphrase {
1374        Passphrase::new("test-pass".into())
1375    }
1376
1377    #[test]
1378    fn create_then_open_round_trips_over_a_temp_vault() {
1379        let dir = tempfile::tempdir().unwrap();
1380        let vault = dir.path().join("vault.pgp");
1381        {
1382            let _s = Session::create(&vault, &pp()).unwrap(); // schema + config table initialized + saved
1383        }
1384        // Re-open with the same passphrase: an empty ledger projects cleanly.
1385        let s = Session::open(&vault, &pp()).unwrap();
1386        let (state, _cfg) = s.project().unwrap();
1387        assert!(state.lots.is_empty());
1388        assert!(state.blockers.is_empty());
1389    }
1390
1391    /// `Session::snapshot`/`restore` delegate to the vault and revert an in-memory mutation
1392    /// without touching disk (the wrapper the persist layer uses for save-rollback).
1393    #[test]
1394    fn session_snapshot_restore_reverts_in_memory_mutation() {
1395        let dir = tempfile::tempdir().unwrap();
1396        let vault = dir.path().join("vault.pgp");
1397        let mut s = Session::create(&vault, &pp()).unwrap();
1398        s.conn().execute("CREATE TABLE t (x INTEGER)", []).unwrap();
1399        s.save().unwrap();
1400
1401        let snap = s.snapshot().unwrap();
1402        s.conn().execute("INSERT INTO t VALUES (7)", []).unwrap();
1403        let n: i64 = s
1404            .conn()
1405            .query_row("SELECT COUNT(*) FROM t", [], |r| r.get(0))
1406            .unwrap();
1407        assert_eq!(n, 1, "pre-restore: the inserted row is present in memory");
1408
1409        let before = std::fs::read(&vault).unwrap();
1410        s.restore(&snap).unwrap();
1411        let after = std::fs::read(&vault).unwrap();
1412        assert_eq!(before, after, "restore must not write the vault file");
1413
1414        let n: i64 = s
1415            .conn()
1416            .query_row("SELECT COUNT(*) FROM t", [], |r| r.get(0))
1417            .unwrap();
1418        assert_eq!(n, 0, "restore must revert the in-memory insert");
1419    }
1420
1421    #[test]
1422    fn wrong_passphrase_is_surfaced_not_a_panic() {
1423        let dir = tempfile::tempdir().unwrap();
1424        let vault = dir.path().join("vault.pgp");
1425        Session::create(&vault, &pp()).unwrap();
1426        let err = Session::open(&vault, &Passphrase::new("nope".into())).unwrap_err();
1427        assert!(matches!(
1428            err,
1429            CliError::Store(btctax_store::StoreError::WrongPassphrase)
1430        ));
1431    }
1432
1433    /// `load_events_and_project` must return the same (events, state, config) triple as calling
1434    /// `load_all` + `project` separately. Verifies the single-load contract (no double DB round-trip).
1435    #[test]
1436    fn load_events_and_project_matches_separate_calls() {
1437        let dir = tempfile::tempdir().unwrap();
1438        let vault = dir.path().join("vault.pgp");
1439        Session::create(&vault, &pp()).unwrap();
1440        let s = Session::open(&vault, &pp()).unwrap();
1441
1442        let (events, state, cfg) = s.load_events_and_project().unwrap();
1443
1444        // Reference path: separate load_all + project calls.
1445        let events2 = btctax_core::persistence::load_all(s.conn()).unwrap();
1446        let (state2, cfg2) = s.project().unwrap();
1447
1448        assert_eq!(events.len(), events2.len(), "event count must match");
1449        assert_eq!(state.lots.len(), state2.lots.len(), "lots count must match");
1450        assert_eq!(
1451            state.blockers.len(),
1452            state2.blockers.len(),
1453            "blocker count must match"
1454        );
1455        assert_eq!(cfg, cfg2, "ProjectionConfig must match");
1456    }
1457
1458    /// `Session::optimize_proposal` recomputes the Mode-1 proposal on the HELD session (READ-ONLY,
1459    /// no second open). For a 2025 year with two same-wallet lots and a 500k sale, the FIFO baseline
1460    /// consumes the cheaper lot A (higher gain); the optimizer prefers the dearer lot B → a
1461    /// per-disposal row whose proposed_selection differs from current_selection, with `delta ≤ 0`.
1462    #[test]
1463    fn optimize_proposal_recomputes_a_persistable_proposal_on_held_session() {
1464        use btctax_core::event::{
1465            Acquire, BasisSource, DisposeKind, EventPayload, LedgerEvent, MethodElection,
1466            OutflowClass, ReclassifyOutflow, TransferOut,
1467        };
1468        use btctax_core::identity::{Source, SourceRef};
1469        use btctax_core::persistence::{append_decision, append_import_batch};
1470        use btctax_core::{Carryforward, EventId, FilingStatus, LotMethod, TaxProfile, WalletId};
1471        use rust_decimal_macros::dec;
1472        use time::{OffsetDateTime, UtcOffset};
1473
1474        let dir = tempfile::tempdir().unwrap();
1475        let vault = dir.path().join("vault.pgp");
1476        Session::create(&vault, &pp()).unwrap();
1477        let mut s = Session::open(&vault, &pp()).unwrap();
1478
1479        let wallet = Some(WalletId::Exchange {
1480            provider: "River".to_string(),
1481            account: "main".to_string(),
1482        });
1483        let lot_a = EventId::import(Source::River, SourceRef::new("op-lot-a"));
1484        let lot_b = EventId::import(Source::River, SourceRef::new("op-lot-b"));
1485        let to_id = EventId::import(Source::River, SourceRef::new("op-sell"));
1486        let ta = OffsetDateTime::from_unix_timestamp(1_739_000_000).unwrap();
1487        let tb = OffsetDateTime::from_unix_timestamp(1_741_000_000).unwrap();
1488        let tc = OffsetDateTime::from_unix_timestamp(1_748_000_000).unwrap();
1489        let td = OffsetDateTime::from_unix_timestamp(1_748_100_000).unwrap();
1490        let batch = vec![
1491            LedgerEvent {
1492                id: lot_a.clone(),
1493                utc_timestamp: ta,
1494                original_tz: UtcOffset::UTC,
1495                wallet: wallet.clone(),
1496                payload: EventPayload::Acquire(Acquire {
1497                    sat: 1_000_000,
1498                    usd_cost: dec!(30000),
1499                    fee_usd: dec!(0),
1500                    basis_source: BasisSource::ExchangeProvided,
1501                }),
1502            },
1503            LedgerEvent {
1504                id: lot_b.clone(),
1505                utc_timestamp: tb,
1506                original_tz: UtcOffset::UTC,
1507                wallet: wallet.clone(),
1508                payload: EventPayload::Acquire(Acquire {
1509                    sat: 1_000_000,
1510                    usd_cost: dec!(50000),
1511                    fee_usd: dec!(0),
1512                    basis_source: BasisSource::ExchangeProvided,
1513                }),
1514            },
1515            LedgerEvent {
1516                id: to_id.clone(),
1517                utc_timestamp: tc,
1518                original_tz: UtcOffset::UTC,
1519                wallet: wallet.clone(),
1520                payload: EventPayload::TransferOut(TransferOut {
1521                    sat: 500_000,
1522                    fee_sat: None,
1523                    dest_addr: None,
1524                    txid: None,
1525                }),
1526            },
1527        ];
1528        append_import_batch(s.conn(), &batch).unwrap();
1529        let ro = EventPayload::ReclassifyOutflow(ReclassifyOutflow {
1530            transfer_out_event: to_id.clone(),
1531            as_: OutflowClass::Dispose {
1532                kind: DisposeKind::Sell,
1533            },
1534            principal_proceeds_or_fmv: dec!(30000),
1535            fee_usd: None,
1536            donee: None,
1537        });
1538        append_decision(s.conn(), ro, td, UtcOffset::UTC, None).unwrap();
1539        // [reconcile-defaults] pin a global FIFO standing order so the BASELINE picks the older lot_a
1540        // (the app default is now HIFO, which would already pick the dearer lot_b → nothing to propose).
1541        // Made-date 2024-12-24 ≤ effective 2025-01-01 → not backdated.
1542        append_decision(
1543            s.conn(),
1544            EventPayload::MethodElection(MethodElection {
1545                effective_from: time::macros::date!(2025 - 01 - 01),
1546                method: LotMethod::Fifo,
1547                wallet: None,
1548            }),
1549            OffsetDateTime::from_unix_timestamp(1_735_000_000).unwrap(),
1550            UtcOffset::UTC,
1551            None,
1552        )
1553        .unwrap();
1554        let profile = TaxProfile {
1555            filing_status: FilingStatus::Single,
1556            ordinary_taxable_income: dec!(100000),
1557            magi_excluding_crypto: dec!(100000),
1558            qualified_dividends_and_other_pref_income: dec!(0),
1559            other_net_capital_gain: dec!(0),
1560            capital_loss_carryforward_in: Carryforward::default(),
1561            w2_ss_wages: dec!(0),
1562            w2_medicare_wages: dec!(0),
1563            schedule_c_expenses: dec!(0),
1564        };
1565        crate::tax_profile::set(s.conn(), 2025, &profile).unwrap();
1566        s.save().unwrap();
1567
1568        let now = OffsetDateTime::from_unix_timestamp(1_752_000_000).unwrap();
1569        let proposal = s.optimize_proposal(2025, now).unwrap();
1570        assert!(
1571            proposal.delta <= dec!(0),
1572            "delta must be ≤ 0 (baseline-seeded)"
1573        );
1574        let row = proposal
1575            .per_disposal
1576            .iter()
1577            .find(|d| d.disposal == to_id)
1578            .expect("the 2025 sale must be in the proposal");
1579        assert_ne!(
1580            row.proposed_selection, row.current_selection,
1581            "the optimizer must propose the dearer lot (a change from FIFO)"
1582        );
1583    }
1584}