Skip to main content

btctax_cli/cmd/
admin.rs

1//! `config`, `export-snapshot` (FR10), `backup-key` — administrative commands. Config surfaces the TP8
2//! (c)/(b) treatment + the pre-2025 lot method; export/backup arrive in Task 15.
3use crate::cli::FormArg;
4use crate::config::{set_fee_treatment, set_pre2025_method as config_set_pre2025_method};
5use crate::render::write_csv_exports;
6use crate::{require_attestation, CliConfig, CliError, Session};
7use btctax_adapters::BundledTaxTables;
8use btctax_core::{
9    compute_se_tax, se_net_income, FeeTreatment, LedgerEvent, LotMethod, ScheduleDPart, Severity,
10    TaxTables, Usd, DIGITAL_ASSET_8949_FIRST_YEAR,
11};
12use btctax_forms::Form1040Inputs;
13use btctax_store::{fsperms, Passphrase};
14use std::path::{Path, PathBuf};
15
16/// Outcome of the CLI `export_snapshot` wrapper: the written snapshot path plus the count of
17/// UNRESOLVED Hard blockers (`severity() == Hard`) in the projection. Any Hard blocker gates EVERY
18/// tax year (`compute_tax_year` short-circuits on the projection-wide first Hard blocker), so
19/// `unresolved_hard > 0` means every exported Form 8949 / Schedule D / projection CSV is
20/// INFORMATIONAL, not final — the `ExportSnapshot` main.rs arm warns on stderr accordingly. A
21/// fully-resolved ledger yields `0` and no warning. Advisory blockers (incl. `PseudoReconcileActive`,
22/// `SelfTransferInboundZeroBasis`) never count.
23#[derive(Debug, Clone)]
24pub struct ExportReport {
25    pub path: PathBuf,
26    pub unresolved_hard: usize,
27}
28
29pub fn show_config(vault_path: &Path, pp: &Passphrase) -> Result<CliConfig, CliError> {
30    Session::open(vault_path, pp)?.config()
31}
32
33/// Persist a new TP8 fee treatment (None = leave unchanged), then return the resulting config.
34pub fn set_config(
35    vault_path: &Path,
36    pp: &Passphrase,
37    fee_treatment: Option<FeeTreatment>,
38) -> Result<CliConfig, CliError> {
39    let mut session = Session::open(vault_path, pp)?;
40    if let Some(t) = fee_treatment {
41        set_fee_treatment(session.conn(), t)?;
42        session.save()?;
43    }
44    session.config()
45}
46
47/// Persist the pre-2025 lot identification method and attestation flag, then return the resulting config.
48pub fn set_pre2025_method(
49    vault_path: &Path,
50    pp: &Passphrase,
51    m: LotMethod,
52    attested: bool,
53) -> Result<CliConfig, CliError> {
54    let mut session = Session::open(vault_path, pp)?;
55    config_set_pre2025_method(session.conn(), m, attested)?;
56    session.save()?;
57    session.config()
58}
59
60/// **BG-D8 (Task 14) — the export COMPLETENESS gate.** REFUSES the export (writing ZERO bytes: called
61/// FIRST in each export fn, before any `mkdir_out`/file write) when a promoted-basis DISPOSAL leg is filed
62/// in the exported range but its Form 8275 disclosure is absent or INCOMPLETE (an empty/scaffold-only Part
63/// II). Reg §1.6662-4(f) makes a disclosure adequate only on a COMPLETED Form 8275; a promoted leg filed
64/// without one is inadequate disclosure — a HARD refusal, never a warning.
65///
66/// Mirrors the pseudo-active attestation slot (`if state.pseudo_active() { require_attestation(...)? }`):
67/// a real refuse-before-bytes gate. It is deliberately NOT the always-written `basis_methodology.txt`
68/// pattern (which unconditionally writes and can never refuse) — a refused export leaves `out_dir`
69/// untouched.
70///
71/// `year: Some(y)` scopes the check to `y` (the per-year PDF packets). `year: None` — the non-year-scoped
72/// CSV/snapshot export — means "ANY year with a promoted filed disposal leg in the exported range" (N-3),
73/// so an all-years dump can never smuggle out an inadequately-disclosed promoted position either.
74///
75/// The refusing state is only reachable via a hand-crafted raw-vault write (an empty `part_ii_narrative`):
76/// the T10 `promote-tranche` verb refuses an empty narrative at record time (BG-D7), so a CLI-recorded
77/// promote is complete by construction — this gate is the type-level backstop for the corner it cannot.
78pub fn promote_export_gate(
79    state: &btctax_core::state::LedgerState,
80    events: &[LedgerEvent],
81    year: Option<i32>,
82) -> Result<(), CliError> {
83    // The year(s) to check: the requested one, or — for the whole-range CSV/snapshot dump — every year in
84    // which a promoted disposal leg files.
85    let years: Vec<i32> = match year {
86        Some(y) => vec![y],
87        None => {
88            let mut ys = std::collections::BTreeSet::new();
89            for d in &state.disposals {
90                if d.legs
91                    .iter()
92                    .any(|l| state.promoted_origins.contains(&l.lot_id.origin_event_id))
93                {
94                    ys.insert(d.disposed_at.year());
95                }
96            }
97            ys.into_iter().collect()
98        }
99    };
100    for y in years {
101        // `disclosure_8275` is `Some` iff a promoted DISPOSAL leg files in `y`; refuse when its Part II is
102        // empty/incomplete (the `incomplete` flag T13 exposes for exactly this gate).
103        if let Some(disc) = btctax_core::tax::form8275::disclosure_8275(events, state, y) {
104            if disc.incomplete {
105                return Err(CliError::Usage(format!(
106                    "refusing to export a packet with a promoted-basis leg but no complete Form 8275 \
107                     disclosure for {y}: Reg \u{00a7}1.6662-4(f) makes disclosure adequate only on a \
108                     COMPLETED Form 8275, and this promoted disposal has an empty Part II narrative. \
109                     Record the Part II explanation (re-run `btctax reconcile promote-tranche … \
110                     --part-ii-file <path>`) before exporting."
111                )));
112            }
113        }
114    }
115    Ok(())
116}
117
118/// FR10 / NFR2 exception: decrypted SQLite image (via the store) + the projected ledger as CSV.
119/// When `tax_year` is `Some(y)`, the per-tax-year Form 8949 + Schedule D CSVs are also written,
120/// year-scoped to `y` (P2-B); when `None`, only the all-years CSVs are written.
121///
122/// Sub-project 3 attestation gate: when the projection is pseudo-active (a synthetic default
123/// contributes), producing any form/data file requires the exact `ATTEST_PHRASE` in `attest`
124/// (trimmed, case-sensitive). Checked FIRST — before any bytes are written — so a refused export
125/// leaves `out_dir` untouched. A fully-real (not-pseudo-active) ledger ignores `attest` entirely.
126pub fn export_snapshot(
127    vault_path: &Path,
128    pp: &Passphrase,
129    out_dir: &Path,
130    tax_year: Option<i32>,
131    attest: Option<&str>,
132) -> Result<ExportReport, CliError> {
133    let session = Session::open(vault_path, pp)?;
134    // Two refuse-before-bytes gates, checked FIRST (before the vault snapshot / CSV writes) so a refused
135    // export leaves out_dir untouched:
136    //  1. BG-D8 completeness gate — a promoted-basis leg filed without its complete Form 8275 is a HARD
137    //     refusal (Reg §1.6662-4(f)). `year: None` (a whole-range dump) means "ANY year with a promoted
138    //     filed leg" (N-3), so the all-years CSV cannot smuggle an inadequately-disclosed position either.
139    //  2. Attestation gate — no fictional snapshot/8949/Schedule D leaves the machine unguarded when a
140    //     synthetic default contributes and the attestation is missing/wrong.
141    let (events, state, _cfg) = session.load_events_and_project()?;
142    promote_export_gate(&state, &events, tax_year)?;
143    if state.pseudo_active() {
144        require_attestation(attest)?;
145    }
146    // UX-P4-8: name the --out path (and hint) when the export directory cannot be created (a
147    // colliding file / missing parent / permission problem), instead of a bare `io: File exists`.
148    let sqlite = session
149        .vault()
150        .export_snapshot(out_dir)
151        .map_err(|e| crate::store_io_with_path(e, out_dir, crate::EXPORT_OUT_HINT))?; // writes out_dir/snapshot.sqlite
152                                                                                      // P2-D: standalone Schedule SE §1401 figure for the year-scoped export. Needs the year's filing
153                                                                                      // status (profile) + the year's ss_wage_base (bundled table); `None` when either is absent or
154                                                                                      // there is no business SE income. The "present but no table" note is a text-report concern
155                                                                                      // (render_schedule_se) — the CSV carries the computed figure only.
156    let se_result = match tax_year {
157        Some(y) => {
158            let tables = BundledTaxTables::load();
159            // Resolve (ReturnInputs-derived → stored → …); an uncomputable/refused profile just omits the
160            // SE figure — the export (a data snapshot) still proceeds, never emitting a wrong number.
161            let profile = match session.resolve_screened(&state, y, &tables)? {
162                crate::resolve::ProfileOutcome::Ready { profile, .. } => profile,
163                crate::resolve::ProfileOutcome::Uncomputable { .. } => None,
164            };
165            profile.and_then(|p| {
166                tables.table_for(y).and_then(|t| {
167                    compute_se_tax(
168                        &state,
169                        y,
170                        p.filing_status,
171                        t,
172                        p.w2_ss_wages,
173                        p.w2_medicare_wages,
174                        p.schedule_c_expenses,
175                    )
176                })
177            })
178        }
179        None => None,
180    };
181    let donation_details = session.donation_details()?;
182    // UX-P4-8: name the --out path for any I/O failure writing under out_dir — a `mkdir_owner_only`/
183    // `open_owner_only` failure (a SUBPATH collision such as `out_dir/lots.csv` being a directory)
184    // arrives as `CliError::Store(StoreError::Io)`, a mid-write `flush`/`writeln` as `CliError::Io`;
185    // `cli_io_with_path` enriches BOTH. A `csv::Error` (serialization, not a path problem) passes
186    // through.
187    write_csv_exports(
188        out_dir,
189        &state,
190        tax_year,
191        se_result.as_ref(),
192        &donation_details,
193    )
194    .map_err(|e| crate::cli_io_with_path(e, out_dir, crate::EXPORT_OUT_HINT))?;
195    // BG-D8: emit the Form 8275 disclosure by its OWN name alongside the year-scoped packet (mirrors the
196    // basis_methodology.txt emit inside write_csv_exports). The gate above already guaranteed every
197    // promoted leg in the exported range carries a complete Part II.
198    match tax_year {
199        Some(y) => {
200            crate::render::write_form_8275_txt(out_dir, &state, &events, y)
201                .map_err(|e| crate::cli_io_with_path(e, out_dir, crate::EXPORT_OUT_HINT))?;
202        }
203        None => {
204            // Task 16 / M2: the all-years dump emits promoted rows (lots/disposals.csv) for EVERY
205            // promoted year in range, so it must co-emit the 8275 for every one of them too — not just
206            // whichever year a `Some(y)` caller happened to name. Year-suffixed filenames (never the
207            // bare `form_8275.txt`): a real vault can have promoted disposal legs in more than one tax
208            // year, and the bare name would let a second year silently overwrite the first's disclosure.
209            let mut promoted_years: std::collections::BTreeSet<i32> =
210                std::collections::BTreeSet::new();
211            for d in &state.disposals {
212                if d.legs
213                    .iter()
214                    .any(|l| state.promoted_origins.contains(&l.lot_id.origin_event_id))
215                {
216                    promoted_years.insert(d.disposed_at.year());
217                }
218            }
219            for y in promoted_years {
220                crate::render::write_form_8275_txt_named(
221                    out_dir,
222                    &state,
223                    &events,
224                    y,
225                    &format!("form_8275_{y}.txt"),
226                )
227                .map_err(|e| crate::cli_io_with_path(e, out_dir, crate::EXPORT_OUT_HINT))?;
228            }
229        }
230    }
231    // [R0-I1] Count UNRESOLVED Hard blockers only. Any Hard blocker gates every year, so the count
232    // alone (no per-year `compute_tax_year` call, no profile/tables dependency) drives the main.rs
233    // stderr "INFORMATIONAL, not final" disclosure. Advisory blockers never count.
234    let unresolved_hard = state
235        .blockers
236        .iter()
237        .filter(|b| b.kind.severity() == Severity::Hard)
238        .count();
239    Ok(ExportReport {
240        path: sqlite,
241        unresolved_hard,
242    })
243}
244
245/// Probe: would an export be gated? `true` when the projection is pseudo-active (a synthetic default
246/// contributes). Used by the `export-snapshot` CLI arm to decide whether to PROMPT for the attestation
247/// phrase; the authoritative gate lives inside `export_snapshot` itself. Kept in the library so main.rs
248/// stays a thin dispatch (no session-open / projection business logic in the binary).
249pub fn export_pseudo_active(vault_path: &Path, pp: &Passphrase) -> Result<bool, CliError> {
250    let (state, _cfg) = Session::open(vault_path, pp)?.project()?;
251    Ok(state.pseudo_active())
252}
253
254/// Outcome of `export_irs_pdf`: the written PDF paths, the unresolved-Hard-blocker count (same
255/// INFORMATIONAL disclosure as `export-snapshot`), whether the fill was watermarked (pseudo-active),
256/// the count of rows that MIGHT belong on a separate broker-reported 8949 (the [I5] advisory — the
257/// separate boxes are year-aware: A/B/D/E from a 1099-B pre-TY2025, G/H/J/K from a 1099-DA from
258/// TY2025), and the SP2 packet (Schedule SE + Form 8283 + Form 1040 cap-gains) with the advisories
259/// each one drives.
260#[derive(Debug, Clone)]
261pub struct IrsPdfReport {
262    pub f8949_path: Option<PathBuf>,
263    pub schedule_d_path: Option<PathBuf>,
264    pub tax_year: i32,
265    pub unresolved_hard: usize,
266    pub broker_reported_rows: usize,
267    pub watermarked: bool,
268    /// Schedule SE — written only when SE income ≥ the $400 floor (and selected).
269    pub schedule_se_path: Option<PathBuf>,
270    /// SE tax was computed but net earnings were below the $400 floor → SE not owed, form skipped.
271    pub se_below_floor: bool,
272    /// `Some(addl)` when the §1401(b)(2) Additional Medicare Tax is nonzero — a Form 8959 item, NOT on
273    /// Schedule SE (a loud advisory).
274    pub se_addl_medicare: Option<Usd>,
275    /// SE-eligible business income exists but no profile/table was available (`compute_se_tax` → None
276    /// for a reason other than "no SE income") → a NOTE, not a silent skip (the `se_net_income`
277    /// discriminator).
278    pub se_income_without_profile: bool,
279    /// Form 8283 — written only when there are donations (and selected).
280    pub form_8283_path: Option<PathBuf>,
281    /// Any Form 8283 row needs manual review (incomplete appraiser/donee declaration) → escalate.
282    pub form_8283_needs_review: bool,
283    /// The Form 8283 section actually written (`Some(true)` = Section B, `Some(false)` = Section A).
284    pub form_8283_section_b: Option<bool>,
285    /// Form 1040 cap-gains — written only when there is reportable digital-asset activity (and selected).
286    pub form_1040_path: Option<PathBuf>,
287    /// Line 7a received a value on the written 1040.
288    pub form_1040_filled_7a: bool,
289    /// The 1040 was skipped for a NET LOSS on line 7a (the §1211 line-21 cap is the filer's).
290    pub form_1040_loss: bool,
291    /// Form 8275 (Disclosure Statement) — Task 16: written only on the crypto-slice path, only when a
292    /// promoted-basis disposal leg files in `tax_year` (and selected). Always `None` on the full-return
293    /// path — its 8275 is inside `full_return_paths` instead (sequence-prefixed, e.g. `92_f8275.pdf`).
294    pub form_8275_path: Option<PathBuf>,
295    /// ★ The FULL-RETURN packet's files, in Attachment Sequence order (empty on the crypto-slice path).
296    /// The two paths write NON-OVERLAPPING names, so no two runs can be collated into a chimera return.
297    pub full_return_paths: Vec<PathBuf>,
298    /// The full-return packet's manifest (the filer's stapling order).
299    pub full_return_manifest: Option<PathBuf>,
300    /// UX-P4-5: `true` when a `--forms` SLICE was passed on a full-return year and therefore IGNORED
301    /// (the whole jointly-computed packet writes; honoring a slice of it is tax-unsound). The caller
302    /// warns on stderr. Always `false` on the crypto-slice path (there `--forms` is honored).
303    pub forms_ignored_full_return: bool,
304}
305
306/// The **[I5]** broker-reporting advisory line, year-aware — or `None` when no disposition may have
307/// been broker-reported (`broker_reported_rows == 0`).
308///
309/// The "separate 8949 / not-reported box" pairing depends on the form revision, exactly as the box
310/// assignment does (mirrors [`btctax_core::DIGITAL_ASSET_8949_FIRST_YEAR`]): pre-TY2025 an exchange
311/// disposal may have been reported on a **1099-B**, belongs on a separate 8949 under **Box A/B (ST) /
312/// D/E (LT)**, and this export files every row under **Box C/F**; from TY2025 it is the **1099-DA**,
313/// **Box G/H/J/K**, and every row files under **Box I/L**. Emitting the 2025 pairing on a pre-2025
314/// export would steer the filer to boxes that do not exist on that revision — hence the year gate.
315pub fn broker_reporting_advisory(tax_year: i32, broker_reported_rows: usize) -> Option<String> {
316    if broker_reported_rows == 0 {
317        return None;
318    }
319    let (broker_form, separate_boxes, filed_boxes) = if tax_year >= DIGITAL_ASSET_8949_FIRST_YEAR {
320        ("1099-DA", "Box G/H/J/K", "Box I/L")
321    } else {
322        ("1099-B", "Box A/B (ST) / D/E (LT)", "Box C/F")
323    };
324    Some(format!(
325        "⚠ [I5] {broker_reported_rows} disposition(s) occurred on an exchange that MAY have issued \
326         {broker_form} broker basis reporting — those would belong on a SEPARATE Form 8949 under \
327         {separate_boxes}. This export files EVERY Bitcoin row under {filed_boxes} (not-reported \
328         default) and says so; reclassify by hand if you received a {broker_form}."
329    ))
330}
331
332/// Whether a form is included: the packet is every applicable form unless `--forms` opts in to a subset.
333fn wants(selected: &[FormArg], f: FormArg) -> bool {
334    selected.is_empty() || selected.contains(&f)
335}
336
337/// A Schedule D part is "active" (worth reporting) iff it has any proceeds/cost/gain.
338fn sd_part_active(p: &ScheduleDPart) -> bool {
339    !p.proceeds.is_zero() || !p.cost_basis.is_zero() || !p.gain.is_zero()
340}
341
342/// `export-irs-pdf`: fill the OFFICIAL IRS PDFs for `tax_year` and write them (owner-only) to
343/// `out_dir`. The packet is Form 8949 + Schedule D (always applicable) plus — when applicable and
344/// selected — Schedule SE (SE income ≥ $400), Form 8283 (donations), and Form 1040 cap-gains
345/// (reportable digital-asset activity). The form data is REUSED from the projection
346/// (`form_8949`/`schedule_d`/`form_8283`/`compute_se_tax`) — nothing capital-gains is recomputed; the
347/// SE §1401 figure is computed here from the year's stored `TaxProfile`. Same pseudo-active
348/// attestation gate as `export-snapshot`: checked FIRST, so a refused export leaves `out_dir`
349/// untouched; a pseudo fill is additionally DRAFT-watermarked.
350pub fn export_irs_pdf(
351    vault_path: &Path,
352    pp: &Passphrase,
353    out_dir: &Path,
354    tax_year: i32,
355    forms: &[FormArg],
356    attest: Option<&str>,
357) -> Result<IrsPdfReport, CliError> {
358    let session = Session::open(vault_path, pp)?;
359    let (events, state, _cfg) = session.load_events_and_project()?;
360
361    // ★ THE DISPATCH (P6.5). Exactly one function decides which pipeline runs, and the two write
362    // NON-OVERLAPPING filenames, so artifacts from two runs can never be collated into a chimera
363    // return: the full packet writes `f1040.pdf`, `f1040s1.pdf`, … + a manifest; the crypto slice
364    // writes `form_1040_capgains.pdf`, `schedule_d.pdf`, `f8949.pdf`, ….
365    //
366    // This REPLACES the P5-C1 refusal (`CryptoSliceExportForFullReturnYear`). That guard existed only
367    // because the slice's Schedule D carries the crypto totals alone — no line 13 for 1099-DIV box-2a
368    // capital-gain distributions, no lines 6/14 for capital-loss carryovers — so on a full-return year
369    // it was a complete-LOOKING form with income missing. The full pipeline fills all of them, plus
370    // every attachment the forms cite, so the reason for the refusal is gone. Deleting it downgrades a
371    // type-level impossibility to a branch, which is why the branch is HERE, alone, and pinned by KATs
372    // in BOTH directions.
373    if crate::return_inputs::exists(session.conn(), tax_year)? {
374        // The full-return pipeline runs the BG-D8 gate itself (checked first there too).
375        let mut report = export_full_return(&session, &state, &events, out_dir, tax_year, attest)?;
376        // UX-P4-5: a --forms slice cannot be honored on a full-return year (the 14-form packet is
377        // jointly computed; a slice of it is tax-unsound). The packet still writes in full; flag the
378        // ignored slice so the caller warns.
379        report.forms_ignored_full_return = !forms.is_empty();
380        return Ok(report);
381    }
382
383    // BG-D8 completeness gate (crypto-slice path) — a promoted-basis leg without its complete Form 8275
384    // is a HARD refusal, checked FIRST (before the pseudo watermark check and any byte written).
385    promote_export_gate(&state, &events, Some(tax_year))?;
386
387    // Attestation gate — no fictional tax form leaves the machine unguarded, and a refusal
388    // writes no bytes. (A fully-real ledger ignores `attest`.)
389    let watermarked = state.pseudo_active();
390    if watermarked {
391        require_attestation(attest)?;
392    }
393
394    // Reuse the projection's capital-gains data verbatim (no recompute).
395    let rows = btctax_core::form_8949(&state, tax_year);
396    let totals = btctax_core::schedule_d(&state, tax_year);
397
398    // Form 8275 (Disclosure Statement) — Task 16: `Some` iff a promoted-basis disposal leg files in
399    // `tax_year` (the same `disclosure_8275` scoping `promote_export_gate` above already used to confirm
400    // completeness).
401    let printed_8275 = btctax_core::tax::form8275::disclosure_8275(&events, &state, tax_year)
402        .map(|d| btctax_core::tax::printed::printed_8275(&d));
403    // Task 16 / ADD-2 (mirrors `export_full_return`'s pre-check below): v1 does not paginate Form 8275 —
404    // refuse HERE, before `mkdir_out`, so an overflowing year (> 6 promoted disposal legs) names the year
405    // + a concrete remedy and writes ZERO bytes, instead of a bare `FormsError::Overflow` display after
406    // other files (`basis_methodology.txt`, `form_8275.txt`) already exist on disk.
407    if let Some(p) = &printed_8275 {
408        let cap = btctax_forms::Form8275Map::for_year(tax_year)?.rows.len();
409        if p.part_i.len() > cap {
410            return Err(CliError::Usage(format!(
411                "cannot export {tax_year}: {n} promoted disposal leg(s) each need a Form 8275 Part I \
412                 row, but this revision holds only {cap} — Form 8275 cannot yet paginate beyond {cap} \
413                 rows. File the 8275 manually for {tax_year}, or reduce the number of promoted disposal \
414                 legs filed in {tax_year} (e.g. void one of the promotes) and re-export.",
415                n = p.part_i.len(),
416            )));
417        }
418    }
419
420    // A pseudo-active fill DRAFT-watermarks every page before it hits disk.
421    let stamp = |bytes: Vec<u8>| -> Result<Vec<u8>, CliError> {
422        Ok(if watermarked {
423            btctax_forms::stamp_draft_watermark(&bytes)?
424        } else {
425            bytes
426        })
427    };
428
429    mkdir_out(out_dir)?;
430
431    // I-3 (D-4): the MANDATORY conservative-filing methodology disclosure rides the PDF packet too, not
432    // just the CSV paths — a filer mailing the flagship filing-ready artifact must get the i8949-required
433    // basis explanation whenever a $0-basis tranche row is present. Writes nothing for a no-tranche year.
434    crate::render::write_basis_methodology_txt(out_dir, &state, tax_year)?;
435    // BG-D8: the Form 8275 disclosure rides the packet by its OWN name. The gate above guaranteed a
436    // promoted leg reaching here has a complete Part II. Writes nothing for a no-promoted-leg year.
437    crate::render::write_form_8275_txt(out_dir, &state, &events, tax_year)?;
438
439    // ── Form 8949 + Schedule D (always applicable). ──
440    let f8949_path = if wants(forms, FormArg::F8949) {
441        let bytes = stamp(btctax_forms::fill_form_8949(&rows, tax_year)?)?;
442        let path = out_dir.join("f8949.pdf");
443        write_bytes_owner_only(&path, &bytes)?;
444        Some(path)
445    } else {
446        None
447    };
448    let schedule_d_path = if wants(forms, FormArg::ScheduleD) {
449        let bytes = stamp(btctax_forms::fill_schedule_d(&totals, tax_year)?)?;
450        let path = out_dir.join("schedule_d.pdf");
451        write_bytes_owner_only(&path, &bytes)?;
452        Some(path)
453    } else {
454        None
455    };
456
457    // ── Schedule SE (self-employment tax). Compute the §1401 figure from the year's TaxProfile. ──
458    let se_computed = {
459        let tables = BundledTaxTables::load();
460        let profile = match session.resolve_screened(&state, tax_year, &tables)? {
461            crate::resolve::ProfileOutcome::Ready { profile, .. } => profile,
462            crate::resolve::ProfileOutcome::Uncomputable { .. } => None, // export proceeds; SE omitted
463        };
464        profile.and_then(|p| {
465            tables.table_for(tax_year).and_then(|t| {
466                compute_se_tax(
467                    &state,
468                    tax_year,
469                    p.filing_status,
470                    t,
471                    p.w2_ss_wages,
472                    p.w2_medicare_wages,
473                    p.schedule_c_expenses,
474                )
475                .map(|se| (se, p.w2_ss_wages, t.ss_wage_base))
476            })
477        })
478    };
479    // Discriminator: SE income present but `compute_se_tax` returned None (no profile / no table) → a
480    // NOTE, not a silent skip (mirrors the render layer; never a fabricated form).
481    let se_income_without_profile =
482        se_computed.is_none() && !se_net_income(&state, tax_year).is_zero();
483    let mut schedule_se_path = None;
484    let mut se_below_floor = false;
485    let mut se_addl_medicare = None;
486    if wants(forms, FormArg::ScheduleSe) {
487        if let Some((se, w2_ss_wages, ss_wage_base)) = se_computed {
488            if !se.addl.is_zero() {
489                se_addl_medicare = Some(se.addl);
490            }
491            match btctax_forms::fill_schedule_se(&se, w2_ss_wages, ss_wage_base, tax_year)? {
492                Some(bytes) => {
493                    let bytes = stamp(bytes)?;
494                    let path = out_dir.join("schedule_se.pdf");
495                    write_bytes_owner_only(&path, &bytes)?;
496                    schedule_se_path = Some(path);
497                }
498                None => se_below_floor = true, // below the $400 floor — SE not owed.
499            }
500        }
501    }
502
503    // ── Form 8283 (noncash charitable contributions). ──
504    let mut form_8283_path = None;
505    let mut form_8283_needs_review = false;
506    let mut form_8283_section_b = None;
507    if wants(forms, FormArg::Form8283) {
508        let details = session.donation_details()?;
509        let rows_8283 = btctax_core::form_8283(&state, tax_year, &details);
510        if let Some(bytes) = btctax_forms::fill_form_8283(&rows_8283, tax_year)? {
511            form_8283_needs_review = rows_8283.iter().any(|r| r.needs_review);
512            form_8283_section_b = rows_8283
513                .iter()
514                .find_map(|r| r.section)
515                .map(|s| s == btctax_core::Form8283Section::B);
516            let bytes = stamp(bytes)?;
517            let path = out_dir.join("form_8283.pdf");
518            write_bytes_owner_only(&path, &bytes)?;
519            form_8283_path = Some(path);
520        }
521    }
522
523    // ── Form 1040 cap-gains cells + the digital-asset question. ──
524    let mut form_1040_path = None;
525    let mut form_1040_filled_7a = false;
526    let mut form_1040_loss = false;
527    if wants(forms, FormArg::Form1040) {
528        let da_yes = !rows.is_empty()
529            || state
530                .income_recognized
531                .iter()
532                .any(|i| i.recognized_at.year() == tax_year)
533            || state
534                .removals
535                .iter()
536                .any(|r| r.removed_at.year() == tax_year);
537        let inputs = Form1040Inputs {
538            da_yes,
539            schedule_d_active: sd_part_active(&totals.st) || sd_part_active(&totals.lt),
540            schedule_d_line16: totals.st.gain + totals.lt.gain,
541        };
542        if let Some(fill) = btctax_forms::fill_form_1040_capgains(&inputs, tax_year)? {
543            form_1040_filled_7a = fill.filled_7a;
544            form_1040_loss = fill.loss;
545            let bytes = stamp(fill.pdf)?;
546            let path = out_dir.join("form_1040_capgains.pdf");
547            write_bytes_owner_only(&path, &bytes)?;
548            form_1040_path = Some(path);
549        }
550    }
551
552    // ── Form 8275 (Disclosure Statement) — the OFFICIAL PDF, crypto-slice fill (Task 16). Rides beside
553    // the `write_form_8275_txt` content emitted above; no filer identity (mirrors the Form 8283
554    // crypto-slice fill). `promote_export_gate` already guaranteed a complete Part II, and the overflow
555    // pre-check above already guaranteed the Part I rows fit this revision's capacity. ──
556    // BG-D8 (whole-branch tax M-1): the Form 8275 is the MANDATORY disclosure that must travel WITH the
557    // promoted 8949 position — so it rides UNCONDITIONALLY whenever a promoted disposal leg is filed,
558    // NOT behind `wants(forms, Form8275)`. Otherwise `--forms f8949` would export the estimate position
559    // without its official disclosure PDF (Reg §1.6662-4(f) makes disclosure adequate only on a COMPLETED
560    // Form 8275). This mirrors the always-emitted `form_8275.txt` and the unconditional overflow refusal:
561    // the disclosure is never a `--forms`-narrowable slice. (`printed_8275` is `Some` iff a promoted
562    // disposal leg files this year; a non-promoted export writes no 8275.)
563    let mut form_8275_path = None;
564    if let Some(p) = &printed_8275 {
565        if let Some(bytes) = btctax_forms::fill_form_8275_slice(p, tax_year)? {
566            let bytes = stamp(bytes)?;
567            let path = out_dir.join("form_8275.pdf");
568            write_bytes_owner_only(&path, &bytes)?;
569            form_8275_path = Some(path);
570        }
571    }
572
573    let unresolved_hard = state
574        .blockers
575        .iter()
576        .filter(|b| b.kind.severity() == Severity::Hard)
577        .count();
578    Ok(IrsPdfReport {
579        full_return_paths: Vec::new(),
580        full_return_manifest: None,
581        forms_ignored_full_return: false, // crypto-slice path honors --forms
582        f8949_path,
583        schedule_d_path,
584        tax_year,
585        unresolved_hard,
586        broker_reported_rows: btctax_forms::rows_possibly_broker_reported(&rows),
587        watermarked,
588        schedule_se_path,
589        se_below_floor,
590        se_addl_medicare,
591        se_income_without_profile,
592        form_8283_path,
593        form_8283_needs_review,
594        form_8283_section_b,
595        form_1040_path,
596        form_1040_filled_7a,
597        form_1040_loss,
598        form_8275_path,
599    })
600}
601
602/// Write `bytes` to `path` with owner-only (0o600) permissions, matching the CSV export path.
603fn write_bytes_owner_only(path: &Path, bytes: &[u8]) -> Result<(), CliError> {
604    use std::io::Write;
605    let mut f = fsperms::open_owner_only(path)?;
606    f.write_all(bytes)?;
607    f.flush()?;
608    Ok(())
609}
610
611/// UX-P4-8: create the export `--out` directory, NAMING the path + a one-clause hint when it cannot be
612/// created (a colliding file, a missing parent, a permission problem) — instead of the bare
613/// `io: File exists (os error 17)` the pathless `StoreError::Io` produces. The single choke point for
614/// every directory-producing export (`export-snapshot` via `write_csv_exports`, `export-irs-pdf`,
615/// `export-full-return`).
616fn mkdir_out(out_dir: &Path) -> Result<(), CliError> {
617    fsperms::mkdir_owner_only(out_dir)
618        .map_err(|e| crate::store_io_with_path(e, out_dir, crate::EXPORT_OUT_HINT))
619}
620
621/// §8: export the passphrase-protected key (escape hatch; HIGH-security write).
622pub fn backup_key(vault_path: &Path, pp: &Passphrase, out_path: &Path) -> Result<(), CliError> {
623    Session::open(vault_path, pp)?
624        .vault()
625        .backup_key(out_path)
626        // UX-P4-8: name the --out path (and hint) when the key file cannot be written (a colliding
627        // directory, a missing parent, a permission problem), not a bare `io: …`.
628        .map_err(|e| crate::store_io_with_path(e, out_path, crate::EXPORT_OUT_HINT))?;
629    Ok(())
630}
631
632/// ★ **The full-return export** (P6.3b / P6.5) — the whole filable packet, not the crypto slice.
633///
634/// Runs the same fail-closed screens the report runs (a return the report will not compute is a return
635/// the exporter must not print), assembles the printed packet in CORE, and fills it ALL-OR-NOTHING: if
636/// any member form refuses, zero bytes reach the disk. A 1040 whose line 2b cites a Schedule B that is
637/// not attached is a wrong return, so partial emission would be a fail-open.
638///
639/// **The packet exports CLEAN** (no DRAFT watermark, no attestation) — the user's §9 decision, folded
640/// into the SPEC. The one exception is PSEUDO-reconciled figures, which are FICTIONAL and can never be
641/// filed: those are watermarked regardless, and that gate composes with (and dominates) everything else.
642fn export_full_return(
643    session: &Session,
644    state: &btctax_core::state::LedgerState,
645    events: &[LedgerEvent],
646    out_dir: &Path,
647    tax_year: i32,
648    attest: Option<&str>,
649) -> Result<IrsPdfReport, CliError> {
650    use btctax_adapters::{BundledFullReturnTables, BundledTaxTables};
651    use btctax_core::tax::tables::{FullReturnTables, TaxTables};
652    use std::fmt::Write as _;
653
654    // BG-D8 completeness gate — checked FIRST (before the tables lookup, the fail-closed screens, and any
655    // byte written): a promoted-basis leg without its complete Form 8275 is a HARD refusal.
656    promote_export_gate(state, events, Some(tax_year))?;
657
658    let tables = BundledTaxTables::load();
659    let fr_tables = BundledFullReturnTables::load();
660    let (Some(params), Some(table)) = (
661        fr_tables.full_return_for(tax_year),
662        tables.table_for(tax_year),
663    ) else {
664        return Err(CliError::Usage(format!(
665            "no full-return tables for {tax_year} — the full-return packet needs a supported tax year \
666             (TY2024)"
667        )));
668    };
669
670    let ri = crate::return_inputs::get(session.conn(), tax_year)?
671        .ok_or_else(|| CliError::Usage(format!("no return_inputs stored for {tax_year}")))?;
672
673    // Fail-closed screens, in the same order the report runs them. A refusal writes NO bytes.
674    let refuse = |r: btctax_core::tax::return_refuse::Refusal| {
675        CliError::Usage(format!(
676            "the {tax_year} return is not computable [{:?}]: {} — no forms were written",
677            r.reason, r.detail
678        ))
679    };
680    if let Some(r) = btctax_core::tax::return_refuse::screen_inputs(&ri, table, params) {
681        return Err(refuse(r));
682    }
683    if let Some(r) =
684        btctax_core::tax::return_1040::screen_compute_dependent(&ri, state, tax_year, params)
685    {
686        return Err(refuse(r));
687    }
688    let ar = btctax_core::tax::return_1040::assemble_absolute(&ri, state, params, table, tax_year);
689    if let Some(r) = btctax_core::tax::return_1040::screen_absolute(&ri, &ar, params) {
690        return Err(refuse(r));
691    }
692
693    // Pseudo figures are FICTIONAL: they are watermarked no matter what, and the attestation gate for
694    // them is unchanged. A clean (real-ledger) packet needs no attestation — SPEC §9 as amended.
695    let watermarked = state.pseudo_active();
696    if watermarked {
697        require_attestation(attest)?;
698    }
699
700    let details = session.donation_details()?;
701    let printed = btctax_core::tax::packet::assemble_printed_return(
702        &ri, state, &details, &ar, table, tax_year, events,
703    )
704    .map_err(|e| {
705        // `HeaderError`'s Display carries the right remedy per variant (a malformed SSN, an unanswered
706        // declaration, or an MFJ return with no spouse) — no longer always "fix the identity" (P9 §3.2).
707        CliError::Usage(format!("the {tax_year} return cannot be printed: {e}"))
708    })?;
709
710    // Task 16 / ADD-2: Form 8275 v1 does not paginate (unlike Form 8283's `overflow::merge_copies`) — a
711    // promoted year with more than the revision's Part I row capacity (6 rows) cannot be filled at all.
712    // Refuse HERE, before the whole-packet fill, so the failure names the year + a concrete remedy
713    // instead of surfacing as a bare `FormsError::Overflow` display deep inside an all-or-nothing fill.
714    if let Some(f8275) = &printed.forms.f8275 {
715        let cap = btctax_forms::Form8275Map::for_year(tax_year)?.rows.len();
716        if f8275.part_i.len() > cap {
717            return Err(CliError::Usage(format!(
718                "cannot export {tax_year}: {n} promoted disposal leg(s) each need a Form 8275 Part I \
719                 row, but this revision holds only {cap} — Form 8275 cannot yet paginate beyond {cap} \
720                 rows. File the 8275 manually for {tax_year}, or reduce the number of promoted disposal \
721                 legs filed in {tax_year} (e.g. void one of the promotes) and re-export.",
722                n = f8275.part_i.len(),
723            )));
724        }
725    }
726
727    // ★ ALL-OR-NOTHING: every form fills BEFORE anything is written.
728    let packet = btctax_forms::fill_full_return(&printed, tax_year)?;
729
730    mkdir_out(out_dir)?;
731    // I-3 (D-4): the MANDATORY methodology disclosure rides the full-return packet too (see export_irs_pdf).
732    crate::render::write_basis_methodology_txt(out_dir, state, tax_year)?;
733    // BG-D8: the Form 8275 disclosure rides the full-return packet by its OWN name (gate above guaranteed
734    // a complete Part II). Writes nothing for a no-promoted-leg year.
735    crate::render::write_form_8275_txt(out_dir, state, events, tax_year)?;
736    let mut manifest = String::from("# btctax full-return packet — staple in this order\n");
737    let mut paths: Vec<PathBuf> = Vec::new();
738    for form in &packet {
739        let bytes = if watermarked {
740            btctax_forms::stamp_draft_watermark(&form.bytes)?
741        } else {
742            form.bytes.clone()
743        };
744        // ★ The packet's filenames are SEQUENCE-PREFIXED (`00_f1040.pdf`, `12A_f8949.pdf`, …). Two
745        // reasons, and the first is a correctness guarantee: the crypto slice writes bare stems
746        // (`f8949.pdf`, `schedule_d.pdf`, `schedule_se.pdf`) and THREE of them collided with the
747        // packet's — so a full-return run and a slice run into one directory could silently interleave
748        // a cents Schedule SE with a whole-dollar 1040: the chimera return the dispatch mitigation
749        // exists to prevent (Fable P6 r1 I7). Second, the prefix IS the stapling order.
750        let path = out_dir.join(format!(
751            "{}_{}.pdf",
752            form.attachment_sequence.unwrap_or("00"),
753            form.name
754        ));
755        write_bytes_owner_only(&path, &bytes)?;
756        let seq = form.attachment_sequence.unwrap_or("—");
757        let _ = writeln!(
758            manifest,
759            "{seq:>4}  {}",
760            path.file_name().unwrap_or_default().to_string_lossy()
761        );
762        paths.push(path);
763    }
764    let manifest_path = out_dir.join("manifest.txt");
765    write_bytes_owner_only(&manifest_path, manifest.as_bytes())?;
766
767    let unresolved_hard = state
768        .blockers
769        .iter()
770        .filter(|b| b.kind.severity() == Severity::Hard)
771        .count();
772    Ok(IrsPdfReport {
773        watermarked,
774        tax_year,
775        unresolved_hard,
776        broker_reported_rows: 0,
777        full_return_paths: paths,
778        full_return_manifest: Some(manifest_path),
779        forms_ignored_full_return: false, // set by the dispatch (which has `forms`), not here
780        // The crypto-slice PATHS are absent (the two pipelines are disjoint), but the 8283's loud
781        // escalations are NOT slice-specific: the packet can contain a Section-B 8283 whose appraiser
782        // declaration is unsigned, and silencing that guard on the one path that announces a "clean,
783        // filable" packet would be a fail-open (Fable P6 r1 I8b).
784        f8949_path: None,
785        schedule_d_path: None,
786        schedule_se_path: None,
787        se_below_floor: false,
788        se_addl_medicare: None,
789        se_income_without_profile: false,
790        form_8283_path: None,
791        form_8283_needs_review: printed
792            .forms
793            .f8283
794            .as_ref()
795            .is_some_and(|r| r.rows().iter().any(|row| row.needs_review)),
796        form_8283_section_b: printed.forms.f8283.as_ref().map(|r| {
797            r.rows()
798                .iter()
799                .any(|row| row.section == Some(btctax_core::Form8283Section::B))
800        }),
801        form_1040_path: None,
802        form_1040_filled_7a: false,
803        form_1040_loss: false,
804        // The full-return path's 8275 (when present) is inside `full_return_paths` — sequence-prefixed
805        // (`92_f8275.pdf`), not this crypto-slice-only bare-named field.
806        form_8275_path: None,
807    })
808}
809
810#[cfg(test)]
811mod tests {
812    use super::*;
813
814    /// [I5] r2/NEW-IMPORTANT-1: the broker-reporting advisory is YEAR-AWARE. On the TY2025+
815    /// digital-asset revision it must cite the 1099-DA and the digital-asset boxes (G/H/J/K separate,
816    /// I/L filed) — never the securities boxes.
817    #[test]
818    fn broker_advisory_ty2025_cites_1099da_and_digital_asset_boxes() {
819        let msg = broker_reporting_advisory(2025, 3).expect("3 broker rows → an advisory");
820        assert!(msg.contains("1099-DA"), "TY2025 cites the 1099-DA: {msg}");
821        assert!(msg.contains("Box G/H/J/K"), "separate 8949 boxes: {msg}");
822        assert!(msg.contains("Box I/L"), "filed-under boxes: {msg}");
823        assert!(msg.contains('3'), "the row count: {msg}");
824        // The securities-era pairing must NOT leak onto a 2025 export.
825        assert!(
826            !msg.contains("1099-B"),
827            "no pre-2025 1099-B on TY2025: {msg}"
828        );
829        assert!(
830            !msg.contains("Box C/F"),
831            "no securities C/F on TY2025: {msg}"
832        );
833    }
834
835    /// [I5] r2/NEW-IMPORTANT-1: pre-TY2025 (the securities-box revisions — TY2024/TY2017 are shipped
836    /// export years) the advisory must cite the 1099-B and the securities boxes (A/B, D/E separate,
837    /// C/F filed) — boxes G–L do not exist on those form revisions.
838    #[test]
839    fn broker_advisory_pre_2025_cites_1099b_and_securities_boxes() {
840        let msg = broker_reporting_advisory(2024, 1).expect("1 broker row → an advisory");
841        assert!(msg.contains("1099-B"), "pre-2025 cites the 1099-B: {msg}");
842        assert!(msg.contains("Box A/B"), "separate ST securities box: {msg}");
843        assert!(msg.contains("D/E"), "separate LT securities box: {msg}");
844        assert!(
845            msg.contains("Box C/F"),
846            "filed-under securities boxes: {msg}"
847        );
848        // The digital-asset-era pairing must NOT leak onto a pre-2025 export.
849        assert!(!msg.contains("1099-DA"), "no 1099-DA pre-2025: {msg}");
850        assert!(!msg.contains("G/H/J/K"), "no digital boxes pre-2025: {msg}");
851        assert!(
852            !msg.contains("Box I/L"),
853            "no digital filed-boxes pre-2025: {msg}"
854        );
855    }
856
857    /// [I5]: no exchange disposition → no advisory, in either era.
858    #[test]
859    fn broker_advisory_is_none_without_broker_rows() {
860        assert!(broker_reporting_advisory(2025, 0).is_none());
861        assert!(broker_reporting_advisory(2024, 0).is_none());
862    }
863
864    /// UX-P4-8 (fold I2): `mkdir_out` — the shared export-`--out` directory creator — names the
865    /// offending PATH and the remedy HINT when the directory cannot be created (here: an `--out`
866    /// that collides with a plain file), instead of a bare `io: File exists`.
867    #[test]
868    fn mkdir_out_collision_names_path_and_hint() {
869        let dir = tempfile::tempdir().unwrap();
870        let collide = dir.path().join("collide");
871        std::fs::write(&collide, b"i am a file, not a directory").unwrap();
872        let err = mkdir_out(&collide).expect_err("a file collision must error");
873        match &err {
874            CliError::PathIo { path, hint, .. } => {
875                assert!(path.contains("collide"), "names the path: {path}");
876                assert_eq!(hint, crate::EXPORT_OUT_HINT, "carries the export-out hint");
877            }
878            other => panic!("expected PathIo, got {other:?}"),
879        }
880        let msg = err.to_string();
881        assert!(msg.contains("collide"), "Display names the path: {msg}");
882        // Literal (not self-referential to the const, which `contains("")` would trivially satisfy if
883        // the const were emptied) — pins the hint's CONTENT (fold r2-N2).
884        assert!(
885            msg.contains("does not already exist as a file"),
886            "Display carries the hint content: {msg}"
887        );
888    }
889}