btctax_cli/cmd/tranche.rs
1//! Conservative-filing `DeclareTranche` record path + the tranche⇄allocation mutual-exclusion guard
2//! (D-8 UX layer). A tranche is undocumented BTC declared at $0 basis (the IRS fallback), folded to an
3//! `EstimatedConservative` lot homed at `window_end`. See `design/conservative-filing/SPEC.md` D-8.
4//!
5//! The engine backstop (Task 5 — `SafeHarborUnconservable` denies a `SafeHarborAllocation` effectiveness
6//! over a live tranche residue) is the GUARANTEE; these record-time guards are the early, friendly error.
7//! They are the single source of the mutual-exclusion predicate for ALL FOUR allocation append sites
8//! (CLI `safe_harbor_allocate` + `safe_harbor_attest`; TUI `persist_safe_harbor_allocate` +
9//! `persist_safe_harbor_attest`) and the tranche record path here.
10
11use crate::{CliError, Session};
12use btctax_core::conventions::TRANSITION_DATE;
13use btctax_core::event::DeclareTranche;
14use btctax_core::persistence::{append_decision, load_all};
15use btctax_core::{EventId, EventPayload, LedgerEvent, Sat, TaxDate, WalletId};
16use btctax_store::Passphrase;
17use std::collections::BTreeSet;
18use std::path::Path;
19use time::{OffsetDateTime, UtcOffset};
20
21/// Tranche-side hedge (tax r2 N-3): the user is recording a tranche and is blocked by an allocation, so
22/// the finality caveat is about that ALLOCATION. A filed safe-harbor allocation cannot be silently unwound.
23const ALLOCATION_IS_FINAL_HINT: &str = "revisit the in-app safe-harbor allocation; if your filed \
24 allocation is already final, unallocated pre-2025 units are a facts-and-circumstances matter for a \
25 professional";
26
27/// Allocation-side hedge (tax review r1 Nit): the user is recording an allocation and is blocked by a
28/// tranche, so the finality caveat is about that TRANCHE (a filed $0 basis), not the allocation.
29const TRANCHE_IS_FINAL_HINT: &str = "Void the tranche first (`reconcile void <decision-ref>`); if you \
30 have already filed the tranche's $0 basis, unallocated pre-2025 units are a facts-and-circumstances \
31 matter for a professional";
32
33/// The set of event ids targeted by any `VoidDecisionEvent` in the log — the record-time "voided" view.
34///
35/// Mirrors `resolve.rs` pass-1 step 1a and the attest site's own `voided` set: a decision is not-in-force
36/// once a `VoidDecisionEvent` names it. (A void of a `SafeHarborAllocation` is resolver-deferred to Task 12
37/// for its EFFECTIVE-vs-inert semantics, but for THIS friendly record-time layer the presence of the void
38/// is enough — the engine backstop is the guarantee behind it.)
39fn void_targets(events: &[LedgerEvent]) -> BTreeSet<EventId> {
40 events
41 .iter()
42 .filter_map(|e| match &e.payload {
43 EventPayload::VoidDecisionEvent(v) => Some(v.target_event_id.clone()),
44 _ => None,
45 })
46 .collect()
47}
48
49/// True iff an IN-FORCE (non-voided) `SafeHarborAllocation` exists — **effective OR inert** (arch r2
50/// New-3: an inert allocation can be flipped effective, so it too collides with a new pre-2025 tranche).
51/// Deliberately NOT scoped to effective allocations (that would let a pre-2025 tranche slip in beside an
52/// inert one and silently discard it once the allocation later goes effective).
53pub fn in_force_allocation_exists(events: &[LedgerEvent]) -> bool {
54 // In force = a NON-voided `SafeHarborAllocation` (present, effective OR inert — an inert one can be
55 // flipped effective, arch r2 New-3). A voided allocation is NOT in force here: the ENGINE resolves the
56 // void (T16 review r2 / I-1) — a void of an inert allocation retires it (§7.4 retirement pass), and a
57 // void of an effective allocation raises a Hard `DecisionConflict` there; either way the record-time
58 // predicate correctly ADMITS the tranche and the engine backstop is the guarantee. (This replaces the
59 // r1 blocker-absence "effective" mirror, which coupled badly with the backstop's blocker retraction.)
60 let voided = void_targets(events);
61 events.iter().any(|e| {
62 matches!(e.payload, EventPayload::SafeHarborAllocation(_)) && !voided.contains(&e.id)
63 })
64}
65
66/// True iff a non-voided PRE-2025 (`window_end < TRANSITION_DATE`) `DeclareTranche` exists — the only
67/// tranche that collides with the pre-2025 Universal residue a `SafeHarborAllocation` reconstructs
68/// (tax r1 I-2). A `window_end ≥ 2025` tranche folds into a post-transition per-wallet pool and never
69/// touches Rev-Proc-2024-28, so it does NOT block an allocation.
70pub fn pre2025_tranche_exists(events: &[LedgerEvent]) -> bool {
71 let voided = void_targets(events);
72 events.iter().any(|e| {
73 matches!(&e.payload, EventPayload::DeclareTranche(t) if t.window_end < TRANSITION_DATE)
74 && !voided.contains(&e.id)
75 })
76}
77
78/// P8 Nit: is `wallet` referenced by any prior event — an import's `wallet`, or a prior tranche
79/// declaration's target wallet? A `false` result means `--wallet` likely has a TYPO. This drives a WARN
80/// only, NEVER a refusal: a `$0` tranche lot in any wallet still files at `$0` (tax-neutral), so a typo
81/// merely strands the lot in a phantom wallet rather than mis-stating tax. Pure over the event log.
82pub fn wallet_is_known(events: &[LedgerEvent], wallet: &WalletId) -> bool {
83 events.iter().any(|e| {
84 e.wallet.as_ref() == Some(wallet)
85 || matches!(&e.payload, EventPayload::DeclareTranche(t) if &t.wallet == wallet)
86 })
87}
88
89/// ALLOCATION-side guard (the chokepoint for all four allocation append sites): refuse recording a
90/// `SafeHarborAllocation` while a pre-2025 tranche is on file. v1 makes them mutually exclusive (D-8).
91pub fn guard_allocation_vs_tranche(events: &[LedgerEvent]) -> Result<(), CliError> {
92 if pre2025_tranche_exists(events) {
93 return Err(CliError::Usage(format!(
94 "refusing to record a safe-harbor allocation while a pre-2025 conservative-filing tranche \
95 ($0 EstimatedConservative) is on file — v1 makes the two mutually exclusive. \
96 {TRANCHE_IS_FINAL_HINT}."
97 )));
98 }
99 Ok(())
100}
101
102/// TRANSITION-side guard for the tranche record path: refuse recording a PRE-2025 tranche while an
103/// in-force allocation exists. A `window_end ≥ 2025` tranche is NOT blocked (records cleanly beside an
104/// effective allocation — else P7's mandatory disclosure is foreclosed for the mixed-records filer).
105fn guard_tranche_vs_allocation(
106 events: &[LedgerEvent],
107 window_end: TaxDate,
108) -> Result<(), CliError> {
109 if window_end < TRANSITION_DATE && in_force_allocation_exists(events) {
110 return Err(CliError::Usage(format!(
111 "refusing to record a pre-2025 conservative-filing tranche while a safe-harbor allocation \
112 is on file — v1 makes the two mutually exclusive; {ALLOCATION_IS_FINAL_HINT}."
113 )));
114 }
115 Ok(())
116}
117
118/// Append a `DeclareTranche` decision (a $0-basis `EstimatedConservative` lot) and persist.
119///
120/// `now` is the injected decision creation-time (deterministic in tests). The tranche folds via the
121/// shared `Op::Acquire` path to a lot homed at `window_end`, $0 basis, tagged `EstimatedConservative`.
122/// Record-time guard (D-8): a PRE-2025 tranche is refused while an in-force allocation exists.
123pub fn declare_tranche(
124 vault_path: &Path,
125 pp: &Passphrase,
126 sat: Sat,
127 wallet: WalletId,
128 window_start: TaxDate,
129 window_end: TaxDate,
130 now: OffsetDateTime,
131) -> Result<EventId, CliError> {
132 // Input validation (record-time refuse — no vault access needed).
133 if sat <= 0 {
134 // A `sat <= 0` tranche would bump `stats.sigma_in` by a non-positive amount (fold.rs),
135 // corrupting Σ-conservation; there is no such thing as declaring zero/negative undocumented BTC.
136 return Err(CliError::Usage(format!(
137 "tranche amount must be > 0 sat (got {sat})"
138 )));
139 }
140 if window_start > window_end {
141 return Err(CliError::Usage(format!(
142 "tranche window_start ({window_start}) must be <= window_end ({window_end})"
143 )));
144 }
145
146 let mut session = Session::open(vault_path, pp)?;
147 let events = load_all(session.conn())?;
148 // Guard FIRST (arch N-1), before the phantom-wallet warning, so a REFUSED declaration never emits the
149 // misleading "stranded lot" note. A pre-2025 tranche is refused while a NON-voided allocation is on
150 // file; a voided allocation is resolved by the engine (T16 review r2 / I-1), so no projection is needed
151 // here.
152 guard_tranche_vs_allocation(&events, window_end)?;
153 // The declaration WILL be recorded now — warn (never refuse) on a `--wallet` that no prior event
154 // references (a likely typo that strands the $0 lot in a phantom wallet; it still files at $0).
155 if !wallet_is_known(&events, &wallet) {
156 eprintln!(
157 "warning: --wallet {} has no prior events in this vault; if this is a typo the $0 tranche \
158 lot is stranded in a phantom wallet (it still files at $0). Re-run with the intended \
159 --wallet if this was unintended.",
160 crate::render::wallet_label(&wallet)
161 );
162 }
163 let payload = EventPayload::DeclareTranche(DeclareTranche {
164 sat,
165 wallet,
166 window_start,
167 window_end,
168 });
169 let id = append_decision(session.conn(), payload, now, UtcOffset::UTC, None)?;
170 session.save()?;
171 Ok(id)
172}