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