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