btctax_cli/cli.rs
1//! The clap-4 command surface for `btctax`, extracted into the library so tooling
2//! (the `xtask` man-page generator) can obtain the `Command` via `Cli::command()`
3//! (`clap::CommandFactory`). The binary (`main.rs`) is a thin dispatch over these types.
4//!
5//! FILE-FORMAT DOCS — SINGLE SOURCE OF TRUTH: the long-help (`///` doc-comments with
6//! `#[arg(verbatim_doc_comment)]`) on the file/format-taking args below is rendered BOTH
7//! into `--help` (clap) AND into the per-subcommand man page (clap_mangen), zero drift.
8//! Formats were read from the writers, never from stale comments: export CSVs from
9//! `render.rs`, the classify-raw serde shape from `btctax-core::EventPayload`, the key
10//! armor from `btctax-store::Vault::backup_key`, the selections header from
11//! `cmd::reconcile::import_selections`, the lot pick from `eventref::parse_lot_pick`.
12use btctax_core::{FilingStatus, LotMethod};
13use clap::{Parser, Subcommand, ValueEnum};
14use std::path::PathBuf;
15
16#[derive(Parser)]
17#[command(name = "btctax", about = "Offline US Bitcoin tax ledger (Phase 1)")]
18pub struct Cli {
19 /// Path to the encrypted vault (vault.pgp).
20 #[arg(long, global = true, default_value = "vault.pgp")]
21 pub vault: PathBuf,
22 #[command(subcommand)]
23 pub command: Command,
24}
25
26#[derive(Subcommand)]
27pub enum Command {
28 /// Create the encrypted vault + force a key backup.
29 Init {
30 /// File to write the forced key backup to: an ASCII-armored, passphrase(S2K)-encrypted
31 /// private key, owner-only (mode 0600). Identical format to `backup-key --out`. Store it
32 /// offline — it is the only way to recover the vault if you lose `vault.key`.
33 ///
34 /// FORMAT (structure — NOT a real key):
35 /// -----BEGIN PGP PRIVATE KEY BLOCK-----
36 /// ... base64 armor of the S2K-encrypted secret key ...
37 /// -----END PGP PRIVATE KEY BLOCK-----
38 #[arg(long, verbatim_doc_comment)]
39 key_backup: PathBuf,
40 /// Clear an interrupted/half-created init (orphan `vault.key`, no encrypted store) and start fresh.
41 #[arg(long, default_value_t = false)]
42 repair: bool,
43 },
44 /// Import one or more export files (auto-groups Swan).
45 Import { files: Vec<PathBuf> },
46 /// FR9 integrity check (non-zero exit on hard blockers).
47 Verify,
48 /// Show holdings + realized disposals/removals/income. With --tax-year: standalone TaxResult.
49 ///
50 /// Exit code with --tax-year (UX-P4-10): 0 = a filing-ready number was rendered; 1 = ran but the
51 /// year is NOT COMPUTABLE (no filing-ready number — a missing tax profile/table or a hard blocker;
52 /// mirrors `verify`); 2 = the command failed (any error). Scripts should key on NON-ZERO. A
53 /// pseudo-active report still exits 0 — the on-screen banner is the signal, not the exit code.
54 #[command(alias = "show")]
55 Report {
56 /// Filter realized disposals/removals/income to a specific calendar year (display path).
57 #[arg(long)]
58 year: Option<i32>,
59 /// Compute the crypto-attributable federal tax for the given tax year (B.5 / Task 9).
60 /// Requires a stored tax profile (`tax-profile --year Y ...`) and the bundled TY table.
61 /// Independent of --year; the two flags are not aliased.
62 #[arg(long)]
63 tax_year: Option<i32>,
64 /// Cumulative prior-year TAXABLE gifts (post-annual-exclusion Form 709 amounts), not
65 /// gross gifts. Used for the §2505 lifetime-exclusion consumption advisory. Defaults to
66 /// $0 when omitted (the advisory discloses this assumption). Must not be negative.
67 #[arg(long)]
68 prior_taxable_gifts: Option<String>,
69 /// §4 R3-M6: persist this year's computed charitable + QBI carryover-OUT as next year's
70 /// carryover-IN (a full-return `--tax-year` ReturnInputs year only). `report` is otherwise
71 /// read-only; this flag opts into the vault write.
72 #[arg(long, default_value_t = false)]
73 write_carryover: bool,
74 /// With `--write-carryover`: overwrite a next-year carryover-in that was user-entered
75 /// (`income import`). Without it, a user-entered value is left untouched and the write refuses.
76 #[arg(long, default_value_t = false)]
77 force: bool,
78 },
79 /// Discover the reconciliation event references (`ref`s) you pass to the `reconcile` verbs.
80 #[command(subcommand)]
81 Events(Events),
82 /// Print the LIMITATIONS & supported-forms document: what a v1 full return covers, the credits it
83 /// omits conservatively (your tax is overstated, never understated), what it refuses outright, and
84 /// what it cannot represent. Read this before you file.
85 Limitations,
86 /// Emit a reconciliation decision event.
87 #[command(subcommand)]
88 Reconcile(Reconcile),
89 /// Show or set projection config (TP8 fee treatment / pre-2025 lot method / forward method).
90 Config {
91 #[arg(long, value_enum)]
92 set_fee_treatment: Option<FeeArg>,
93 #[arg(long, value_enum)]
94 set_pre2025_method: Option<MethodLotArg>,
95 #[arg(long, default_value_t = false)]
96 attest_pre2025_method: bool,
97 /// §A.5(a): append a MethodElection decision (the forward standing order). Not a flag
98 /// mutation — this is an event in the ledger. Use --effective-from to set the date
99 /// (default: today / the decision's made-date).
100 #[arg(long, value_enum)]
101 set_forward_method: Option<MethodLotArg>,
102 /// §A.5(a) per-ACCOUNT scope for --set-forward-method (IRS 2025+ per-account rule):
103 /// exchange:PROVIDER:ACCOUNT (the canonical wallet grammar). Omit for a GLOBAL election
104 /// (the existing behavior). Only exchange accounts are electable (a method election is a
105 /// brokerage-account concept; self:LABEL is rejected). The account MUST already exist in the
106 /// vault — an unknown/typo'd account is rejected LOUDLY so it can't create a dead election.
107 #[arg(long)]
108 exchange: Option<String>,
109 /// Effective-from date for --set-forward-method (YYYY-MM-DD). Defaults to made-date.
110 #[arg(long)]
111 effective_from: Option<String>,
112 },
113 /// FR10: export decrypted SQLite + CSV (the NFR2 plaintext exception).
114 ///
115 /// WARNS (does not refuse) on unresolved Hard blockers: any Hard blocker makes every affected
116 /// tax year NOT COMPUTABLE, so the exported Form 8949 / Schedule D / figures are INFORMATIONAL,
117 /// not final. A warning is printed to stderr and the export still succeeds (exit 0). Automation
118 /// that must GATE on unresolved blockers should check `btctax verify` (which exits non-zero),
119 /// since export-snapshot itself stays exit 0.
120 ExportSnapshot {
121 /// Output DIRECTORY receiving the decrypted SQLite DB (snapshot.sqlite) + projection CSVs
122 /// (the NFR2 plaintext exception; created owner-only). ALWAYS writes: lots.csv,
123 /// disposals.csv, removals.csv, income.csv. With --tax-year it ALSO writes form8949.csv,
124 /// schedule_d.csv, form8283.csv, and schedule_se.csv (schedule_se only when there is
125 /// business self-employment income). The `event` column in disposals.csv / removals.csv /
126 /// income.csv is the event-ref that reconcile commands consume (select-lots,
127 /// set-donation-details, reclassify-income, …).
128 ///
129 /// FORMAT (removals.csv header + one sample donation row):
130 /// event,kind,removed_at,lot,sat,basis,fmv_at_transfer,term,acquired_at,claimed_deduction,donee
131 /// import|coinbase|X,donation,2025-03-01,import|coinbase|X#0,25000,120.00,150.00,long,2023-01-05,150.00,Charity Y
132 #[arg(long, verbatim_doc_comment)]
133 out: PathBuf,
134 /// Also emit the per-tax-year Form 8949 + Schedule D CSVs (form8949.csv / schedule_d.csv),
135 /// scoped to this calendar year. Omit to write only the all-years projection CSVs.
136 #[arg(long)]
137 tax_year: Option<i32>,
138 /// Attestation phrase required to export while the ledger is PSEUDO-RECONCILED (a synthetic
139 /// default contributes to the projection). Pass the exact phrase `I attest this is true`
140 /// (trimmed, case-sensitive) to export the fictional draft ON PURPOSE. Omit on a fully-real
141 /// ledger (never gated). Omit on an interactive terminal to be prompted; omit when piped
142 /// (non-TTY) while pseudo-active and the export is refused.
143 #[arg(long)]
144 attest: Option<String>,
145 },
146 /// Fill the OFFICIAL IRS fillable PDFs for a tax year (a whole packet).
147 ///
148 /// Writes (owner-only) into --out, populated from btctax's already-computed projection — no
149 /// capital-gains figure is recomputed:
150 /// - f8949.pdf + schedule_d.pdf — ALWAYS. On the 2025 (1099-DA) revision Bitcoin is filed under
151 /// Box I (short-term) / Box L (long-term) — the digital-asset boxes; on the pre-1099-DA 2024
152 /// and 2017 revisions it is Box C / Box F ("not reported on a 1099-B"). Never the wrong pair
153 /// for the year. More rows than a part's grid holds (11 in 2025, 14 in 2024/2017) paginate
154 /// onto multiple copies, each with its own totals.
155 /// - schedule_se.pdf — when there is business self-employment income and net earnings are ≥ the
156 /// $400 floor. Line 12 (SE tax) = Social Security + regular Medicare ONLY; the 0.9% Additional
157 /// Medicare Tax is a Form 8959 item (flagged on stderr, not put on Schedule SE). Requires a
158 /// stored `tax-profile` for the year (filing status); missing profile ⇒ a NOTE, not a form.
159 /// - form_8283.pdf — when there are BTC donations. Fills the donee/appraiser IDENTITY + per-
160 /// donation property rows (Section A ≤ $5,000 or Section B > $5,000). The property-type box is
161 /// "k Digital assets" on the Rev. 12-2023/2025 forms (2024/2025); the 2017 Rev. 12-2014 form
162 /// has no such box, so BTC uses "j Other" + a printed note. Leaves every OTHER party's
163 /// declaration/signature BLANK — a Section B 8283 is NOT filing-ready without those signed.
164 /// Overflows onto additional copies.
165 /// - form_1040_capgains.pdf — when there is reportable capital/digital-asset activity. Fills the
166 /// capital-gain line (line 7a in 2025 / line 7 in 2024 / line 13 in 2017, when Schedule D is
167 /// active and line 16 ≥ 0; active-and-zero → "-0-"; a net loss leaves it blank — the §1211
168 /// line-21 cap is yours) and, on 2024/2025, the Digital-Asset question (YES iff any disposal,
169 /// income, gift, or donation; never a "No"). The 2017 form has no Digital-Asset question, so an
170 /// income-only 2017 year produces no 1040. 7b checkboxes are untouched.
171 ///
172 /// Every written value is read back GEOMETRICALLY against the blank PDF's own field coordinates and
173 /// the fill FAILS CLOSED on any mis-placement — a wrong tax form is never written. The engine drops
174 /// the forms' XFA layer (else Acrobat opens them blank) and sets NeedAppearances so a viewer
175 /// regenerates the visible values. Schedule D lines 17-22 (28%-rate / unrecaptured-§1250 / QDI
176 /// worksheet, incl. the line-21 loss limit) are OUT OF SCOPE. Rows on an exchange that MAY carry
177 /// broker reporting (a 1099-DA from TY2025; a 1099-B before) are flagged on stderr — btctax files
178 /// every row under the year's not-reported box (I/L from TY2025, C/F before) and says so.
179 ///
180 /// A tax year that has FULL-RETURN inputs (`income import`) DISPATCHES to the complete return packet —
181 /// the 1040 and every schedule/attachment it cites, in Attachment-Sequence order, plus a manifest
182 /// (`--forms` is ignored on that path). A crypto-only year (no `income import`) instead fills the
183 /// crypto SLICE: Schedule D carries only the ledger's crypto totals — it has no line 13 (1099-DIV
184 /// box-2a capital-gain distributions) and no lines 6/14 (capital-loss carryovers), and the 1040 fill
185 /// covers only the capital-gain cluster. For a crypto-only year those slice forms are complete and
186 /// correct; a full-return year needs the full packet, which is why the two paths are dispatched
187 /// separately (and write non-overlapping filenames). See `btctax limitations`.
188 ///
189 /// PSEUDO-RECONCILED ledgers: the same attestation gate as export-snapshot applies, AND every
190 /// page is stamped with a diagonal `DRAFT — ESTIMATE, NOT FOR FILING` watermark.
191 ExportIrsPdf {
192 /// Output DIRECTORY receiving the filled official PDFs (created owner-only): f8949.pdf,
193 /// schedule_d.pdf, and — when applicable — schedule_se.pdf, form_8283.pdf,
194 /// form_1040_capgains.pdf. These contain your unencrypted tax data — write --out OUTSIDE any
195 /// git repo.
196 #[arg(long, verbatim_doc_comment)]
197 out: PathBuf,
198 /// The tax year to fill (this build bundles TY2017, TY2024 and TY2025; other years are
199 /// refused). TY2024/TY2017 are pre-1099-DA revisions: Bitcoin is filed under Box C/F (not Box
200 /// I/L). TY2017 additionally uses the OLD forms — the §B long Schedule SE, Form 8283 Rev.
201 /// 12-2014 ("j Other", no digital-asset box), the 1040 capital gain on line 13, and NO
202 /// Digital-Asset question.
203 #[arg(long)]
204 tax_year: i32,
205 /// Restrict the crypto-slice packet to specific forms (repeat or comma-separate). Values:
206 /// `f8949`, `schedule-d`, `schedule-se`, `form8283`, `form1040`, `form8275`. Default = every
207 /// applicable form (f8949 + schedule-d always; schedule-se when SE income ≥ the $400 floor;
208 /// form8283 when there are donations; form1040 when there is reportable digital-asset activity;
209 /// form8275 when a promoted-basis disposal leg files in the year — Approach-B's Cohan-estimate
210 /// disclosure). A named form is still skipped when it does not apply. Ignored on a full-return
211 /// year (that path fills the whole packet).
212 #[arg(long, value_enum, value_delimiter = ',')]
213 forms: Vec<FormArg>,
214 /// Attestation phrase required to export while the ledger is PSEUDO-RECONCILED (a synthetic
215 /// default contributes to the projection). Pass the exact phrase `I attest this is true`
216 /// (trimmed, case-sensitive) to fill the DRAFT-watermarked forms ON PURPOSE. Omit on a
217 /// fully-real ledger (never gated). Omit on an interactive terminal to be prompted; omit when
218 /// piped (non-TTY) while pseudo-active and the export is refused.
219 #[arg(long)]
220 attest: Option<String>,
221 },
222 /// Export the passphrase-protected key.
223 BackupKey {
224 /// File to write the exported key to: an ASCII-armored, passphrase(S2K)-encrypted private
225 /// key, owner-only (mode 0600). Identical format to `init --key-backup`.
226 ///
227 /// FORMAT (structure — NOT a real key):
228 /// -----BEGIN PGP PRIVATE KEY BLOCK-----
229 /// ... base64 armor of the S2K-encrypted secret key ...
230 /// -----END PGP PRIVATE KEY BLOCK-----
231 #[arg(long, verbatim_doc_comment)]
232 out: PathBuf,
233 },
234 /// Lot-specific-identification optimizer (§C — read-only proposal or gated persistence).
235 #[command(subcommand)]
236 Optimize(Optimize),
237 /// Read-only what-if tax planning (task #43): posit a HYPOTHETICAL, NON-persisted transaction and
238 /// see its MARGINAL federal-tax effect on the current-year position. Routes through the same audited
239 /// tax engine as `report --tax-year`; invents no tax authority. Writes NOTHING — no event, no
240 /// side-table row, no vault mutation. Tax decision-support (consequences), not buy/sell/hold advice.
241 #[command(subcommand)]
242 WhatIf(WhatIf),
243 /// Full-return (v1) input surface: import, show, or clear the per-year full-return inputs (W-2s,
244 /// 1099s, deductions, household). Offline; stored in the encrypted vault.
245 #[command(subcommand)]
246 Income(IncomeCmd),
247 /// Set or show the per-tax-year tax profile (filing status, income, MAGI, etc.).
248 TaxProfile {
249 /// The tax year (e.g. 2025).
250 #[arg(long)]
251 year: i32,
252 /// IRS filing status.
253 #[arg(long, value_enum)]
254 filing_status: Option<FilingStatusArg>,
255 /// Ordinary taxable income EXCLUDING all app-computed crypto items (net ST gains,
256 /// mining/staking ordinary income). The engine adds the crypto items on top (B.1 / I5).
257 #[arg(long)]
258 ordinary_taxable_income: Option<String>,
259 /// Modified AGI excluding crypto items, for the §1411 NIIT threshold comparison.
260 ///
261 /// IMPORTANT (§1411 contract): this value MUST already include the taxpayer's qualified
262 /// dividends and non-crypto net capital gains (and any other MAGI add-backs from
263 /// §1411(d)). The engine adds ONLY the crypto AGI delta on top (ambiguity #5 in the
264 /// design). Omitting QD or non-crypto cap gains from this figure understates NIIT.
265 #[arg(
266 long,
267 long_help = "Modified AGI excluding crypto items, for the §1411 NIIT \
268 threshold comparison.\n\nIMPORTANT (§1411 contract): this value MUST already \
269 include the taxpayer's qualified dividends and non-crypto net capital gains (and \
270 any other MAGI add-backs from §1411(d)). The engine adds ONLY the crypto AGI \
271 delta on top (ambiguity #5 in the design). Omitting QD or non-crypto cap gains \
272 from this figure understates NIIT."
273 )]
274 magi_excluding_crypto: Option<String>,
275 /// Qualified dividends + other preferential-rate income sharing the §1(h) 0/15/20 LTCG
276 /// rate stack. Required when setting a profile.
277 #[arg(long)]
278 qualified_dividends: Option<String>,
279 /// Non-crypto net LT-character capital gain already in the profile (optional; defaults
280 /// to 0 when omitted).
281 #[arg(long)]
282 other_net_capital_gain: Option<String>,
283 /// §1212(b) short-term capital loss carryforward into this year (optional; defaults to 0).
284 #[arg(long)]
285 carryforward_short: Option<String>,
286 /// §1212(b) long-term capital loss carryforward into this year (optional; defaults to 0).
287 #[arg(long)]
288 carryforward_long: Option<String>,
289 /// Form W-2 Social Security wages (Box 3 + Box 7 tips; Schedule SE line 8a).
290 /// Reduces the §1401(a) SS cap: ss_cap = max(0, wage_base − w2_ss_wages). Optional;
291 /// defaults to $0. Must not be negative.
292 #[arg(long)]
293 w2_ss_wages: Option<String>,
294 /// Medicare wages (Box 5; Form 8959 line 1).
295 /// Reduces the Additional-Medicare threshold: addl_threshold = max(0, threshold − w2_medicare_wages)
296 /// (§1401(b)(2)(B)/Form 8959 Part II). Optional; defaults to $0. Must not be negative.
297 #[arg(long)]
298 w2_medicare_wages: Option<String>,
299 /// Schedule C deductible business expenses for the year — reduces net SE earnings;
300 /// the income-tax stack above is NOT adjusted (see the advisory).
301 /// Optional; defaults to $0. Must not be negative.
302 #[arg(long)]
303 schedule_c_expenses: Option<String>,
304 /// Show the stored profile for `--year` instead of setting it.
305 #[arg(long, default_value_t = false)]
306 show: bool,
307 /// Store the raw profile even when full-return inputs (`income import`) already exist for the year
308 /// (they take precedence, so the raw profile would otherwise be ignored — D-4 guard).
309 #[arg(long, default_value_t = false)]
310 force: bool,
311 },
312}
313
314/// `optimize` subcommand tree. Task 9 adds `Run`; Task 10 adds `Accept`; Task 11 adds `Consult`.
315#[derive(Subcommand)]
316pub enum Optimize {
317 /// Mode-1 what-if: print the tax-saving lot-selection proposal. NOTHING is filed or bound.
318 Run {
319 /// The tax year to optimize (must be 2025 or later).
320 #[arg(long)]
321 tax_year: i32,
322 },
323 /// Mode-1 gated persistence: recompute the optimum and persist the proposed LotSelection(s),
324 /// gated per disposal (§1.1012-1(j)). A genuinely-contemporaneous pick (made ≤ sale) persists
325 /// freely; an already-executed disposal persists ONLY with a narrow per-disposal `--attest`
326 /// scoped to one `--disposal`; a 2027+ broker-held pick is refused. Revoke via `reconcile void`.
327 Accept {
328 /// The tax year to accept (must be 2025 or later).
329 #[arg(long)]
330 tax_year: i32,
331 /// Restrict to ONE disposal (required to carry `--attest`).
332 #[arg(long)]
333 disposal: Option<String>,
334 /// Narrow contemporaneous-ID attestation for an already-executed disposal. Requires
335 /// `--disposal` (no blanket attestation across all disposals).
336 #[arg(long)]
337 attest: Option<String>,
338 },
339 /// Mode-2 read-only pre-trade what-if (§C.3): tax-min lots + ST/LT split + federal tax + ST→LT
340 /// timing. NOTHING is written — no event, no side-table row. Tax decision-support only;
341 /// not buy/sell/hold advice.
342 Consult {
343 /// Hypothetical sale amount (required). Accepts a satoshi integer OR a BTC decimal, e.g.
344 /// `0.05` or `5000000` (a value with a `.` is BTC; a bare integer is satoshis).
345 #[arg(long)]
346 sell: String,
347 /// Wallet to sell from, e.g. `self:cold` or `exchange:coinbase:default` (required; per-wallet
348 /// pool is mandatory post-2025).
349 #[arg(long)]
350 wallet: Option<String>,
351 /// Sale date for the what-if (YYYY-MM-DD; defaults to today UTC if omitted).
352 #[arg(long)]
353 at: Option<String>,
354 /// Explicit USD proceeds for the hypothetical sale. Required when `--at` is a future date
355 /// with no bundled dataset price and `--fmv` is not used. Mutually exclusive with `--fmv`.
356 #[arg(long, conflicts_with = "fmv")]
357 proceeds: Option<String>,
358 /// Use the bundled daily-close FMV for `--at` instead of an explicit proceeds amount.
359 /// A future date with no dataset price will return a ProceedsRequired error. Mutually
360 /// exclusive with `--proceeds`.
361 #[arg(long, conflicts_with = "proceeds")]
362 fmv: bool,
363 },
364}
365
366/// Full-return (v1) input subcommands (SPEC §4 / recon-04 §6). v1 ships the TOML bulk-import path +
367/// a JSON show; incremental per-field subcommands (`add-w2`, …) are a follow-on.
368#[derive(Subcommand)]
369pub enum IncomeCmd {
370 /// Import full-return inputs from an offline TOML file into the vault for a tax year.
371 Import {
372 /// The tax year (e.g. 2024).
373 #[arg(long)]
374 year: i32,
375 /// Path to the TOML file describing the full-return inputs.
376 #[arg(long)]
377 file: std::path::PathBuf,
378 },
379 /// Show the stored full-return inputs for a tax year (JSON, PII redacted), or nothing if none set.
380 Show {
381 /// The tax year (e.g. 2024).
382 #[arg(long)]
383 year: i32,
384 },
385 /// Remove the stored full-return inputs for a tax year (fall back to a raw `tax-profile`).
386 Clear {
387 /// The tax year (e.g. 2024).
388 #[arg(long)]
389 year: i32,
390 },
391 /// Answer the return's fail-loud questions interactively — the yes/no boxes that have no safe
392 /// default (can someone claim you as a dependent? Schedule B's foreign-account and foreign-trust
393 /// lines) plus the optional dates of birth.
394 ///
395 /// These questions REFUSE the return until they are answered: guessing "no" on your behalf would
396 /// understate your tax and print an unchecked box you never affirmed. This is the only way to answer
397 /// them without editing a TOML file. It never asks for a secret — SSNs and the IP PIN belong to
398 /// `set-pii`, which does not echo what you type.
399 ///
400 /// Requires an existing return for the year (create one with `income import`).
401 Answer {
402 /// The tax year (e.g. 2024).
403 #[arg(long)]
404 year: i32,
405 },
406}
407
408/// `what-if` subcommand tree (task #43). READ-ONLY hypothetical-transaction tax planning: NOTHING is
409/// filed, appended, or persisted. Mirrors the `optimize consult` shape, plus an ad-hoc `TaxProfile`
410/// (so you can plan without `tax-profile set`).
411#[derive(Subcommand)]
412pub enum WhatIf {
413 /// Posit a hypothetical, NON-persisted SALE and see its MARGINAL federal tax: the lots it would
414 /// consume, the ST/LT split, which §1(h) LTCG bracket (0/15/20) it lands in + room to the next
415 /// breakpoint, the exact marginal tax (with-hypothetical minus baseline — the sale's OWN effect,
416 /// not the whole-year figure), the effective rate, the §1212(b) carryforward carried to next year,
417 /// this year's ordinary offset, and the §1411 NIIT delta. A net loss surfaces the carryforward
418 /// disclosure (its value is NOT this-year tax). Writes NOTHING.
419 Sell {
420 /// Hypothetical sale amount (required). Accepts a satoshi integer OR a BTC decimal, e.g.
421 /// `0.05` or `5000000` (a value with a `.` is BTC; a bare integer is satoshis).
422 #[arg(long)]
423 sell: String,
424 /// Wallet to sell from, e.g. `self:cold` or `exchange:coinbase:default` (required; the
425 /// per-wallet pool is mandatory post-2025).
426 #[arg(long)]
427 wallet: Option<String>,
428 /// Sale date for the what-if (YYYY-MM-DD; defaults to today UTC if omitted).
429 #[arg(long)]
430 at: Option<String>,
431 /// USD price per WHOLE BTC for the hypothetical sale (proceeds = price × sat / 1e8). Omit to
432 /// use the bundled daily-close FMV for `--at`; REQUIRED for a future/off-dataset `--at` with no
433 /// bundled price (else the what-if returns a ProceedsRequired error).
434 #[arg(long)]
435 price: Option<String>,
436 /// Lot-selection method for the hypothetical sale: fifo|lifo|hifo. Omit to consume by the
437 /// STANDING method (the account's in-force election / the default), exactly as a real disposal
438 /// on that date would.
439 #[arg(long, value_enum)]
440 method: Option<MethodLotArg>,
441 /// AD-HOC filing status (single|mfj|mfs|hoh|qss). Supplying this (with `--income`) builds a
442 /// NON-persisted profile for the plan instead of the stored `tax-profile`. Omit ALL ad-hoc
443 /// flags to use the stored profile for the sale year.
444 #[arg(long, value_enum)]
445 filing_status: Option<FilingStatusArg>,
446 /// AD-HOC ordinary taxable income EXCLUDING crypto (the base the crypto stacks on). Required
447 /// when building an ad-hoc profile.
448 #[arg(long)]
449 income: Option<String>,
450 /// AD-HOC modified AGI excluding crypto, for the §1411 NIIT threshold. DEFAULTS TO `--income`
451 /// when omitted (never $0 — a $0 MAGI would silently suppress every NIIT disclosure); a printed
452 /// caveat notes the assumption. Supply the true MAGI (incl. QD + non-crypto cap gains) to avoid
453 /// understating NIIT.
454 #[arg(long)]
455 magi: Option<String>,
456 /// AD-HOC §1212(b) LONG-TERM capital-loss carryforward INTO the sale year (optional; defaults
457 /// to $0). The dominant BTC case; short-term carryforward-in is out of scope for the ad-hoc
458 /// profile (set a stored `tax-profile` for that).
459 #[arg(long)]
460 carryforward_in: Option<String>,
461 },
462 /// Posit a hypothetical, NON-persisted HARVEST and find the MAX BTC to sell such that a target holds
463 /// on the ENTIRE prefix [0, N]: `--target zero-ltcg` (sell all that fits in the §1(h) 0% bracket),
464 /// `fifteen-ltcg` (stay at/under 15%), `gain=$X` (realize at most $X of gain WITH this sale), or
465 /// `tax=$X` (add at most $X of marginal federal tax; `tax=$0` is the flagship "zero-tax harvest").
466 /// Uses the STANDING lot method's consumption order (never re-optimized). Discloses the §1212(b)
467 /// carryforward burn, the §1411 NIIT kink (a 0%/15% answer can still cost +3.8%), and the plateau
468 /// notes. The answer is ALWAYS engine-verified. Writes NOTHING.
469 Harvest {
470 /// The harvest target: `zero-ltcg` | `fifteen-ltcg` | `gain=$X` | `tax=$X` (X >= 0). `$` and
471 /// commas are optional (e.g. `gain=25000`, `tax=$0`, `gain=$1,000`).
472 #[arg(long)]
473 target: String,
474 /// Wallet to harvest from, e.g. `self:cold` or `exchange:coinbase:default` (required; the
475 /// per-wallet pool is mandatory post-2025).
476 #[arg(long)]
477 wallet: Option<String>,
478 /// Harvest date for the what-if (YYYY-MM-DD; defaults to today UTC if omitted).
479 #[arg(long)]
480 at: Option<String>,
481 /// USD price per WHOLE BTC. Omit to use the bundled daily-close FMV for `--at`; REQUIRED for a
482 /// future/off-dataset `--at` with no bundled price.
483 #[arg(long)]
484 price: Option<String>,
485 /// AD-HOC filing status (single|mfj|mfs|hoh|qss). Supplying this (with `--income`) builds a
486 /// NON-persisted profile for the plan instead of the stored `tax-profile`. Omit ALL ad-hoc
487 /// flags to use the stored profile for the harvest year.
488 #[arg(long, value_enum)]
489 filing_status: Option<FilingStatusArg>,
490 /// AD-HOC ordinary taxable income EXCLUDING crypto (the base the crypto stacks on). Required
491 /// when building an ad-hoc profile.
492 #[arg(long)]
493 income: Option<String>,
494 /// AD-HOC modified AGI excluding crypto, for the §1411 NIIT threshold. DEFAULTS TO `--income`
495 /// when omitted (never $0 — a $0 MAGI would silently suppress every NIIT disclosure); a printed
496 /// caveat notes the assumption.
497 #[arg(long)]
498 magi: Option<String>,
499 /// AD-HOC §1212(b) LONG-TERM capital-loss carryforward INTO the harvest year (optional; defaults
500 /// to $0) — expands the harvestable-gain room (gains are absorbed before touching the pref stack).
501 #[arg(long)]
502 carryforward_in: Option<String>,
503 },
504}
505
506/// `events` subcommand tree (UX-P4-11): read-only ref discoverability.
507#[derive(Subcommand)]
508pub enum Events {
509 /// List every DECIDABLE event — the imported rows a `reconcile` verb can act on
510 /// (transfer-in, transfer-out, unclassified, import-conflict, income) — with its
511 /// reference, kind, date, amount, and decision status. Rows are in ledger (import)
512 /// order, which is not necessarily by date. Read-only; writes nothing.
513 ///
514 /// Copy a listed `ref` verbatim into a reconcile verb, e.g.
515 /// `btctax reconcile classify-inbound-self-transfer <ref>` or
516 /// `btctax reconcile reclassify-outflow <ref> --as-kind sell --amount <usd>`.
517 /// A row shown as `decided: decision|N` already carries a decision; to change it,
518 /// `btctax reconcile void decision|N` first, then re-decide.
519 List,
520}
521
522#[derive(Subcommand)]
523pub enum Reconcile {
524 /// Confirm a self-transfer (TransferLink).
525 LinkTransfer {
526 out: String,
527 #[arg(long, conflicts_with = "to_wallet")]
528 to_event: Option<String>,
529 #[arg(long)]
530 to_wallet: Option<String>,
531 },
532 /// Classify an inbound TransferIn as income.
533 ClassifyInboundIncome {
534 /// The inbound TransferIn event reference to classify (see `btctax events list`).
535 in_ref: String,
536 /// Income kind: one of `mining`, `staking`, `interest`, `airdrop`, `reward`.
537 #[arg(long)]
538 kind: String,
539 /// Fair-market value of the received BTC at receipt — USD dollars, NOT sats. On this
540 /// single-event command there is NO auto-valuation: omitting `--fmv` records a Hard
541 /// "FMV missing" blocker. To supply it, `reconcile void <decision-ref>` then re-classify with
542 /// `--fmv` (classify-inbound is first-wins — re-running without voiding first is refused). To
543 /// value automatically from the bundled daily close, use `reconcile bulk-classify-inbound-income`.
544 #[arg(long)]
545 fmv: Option<String>,
546 /// Mark this income as earned in a trade or business (routes to Schedule C / SE tax).
547 #[arg(long)]
548 business: bool,
549 },
550 /// Classify an inbound TransferIn as a received gift.
551 ClassifyInboundGift {
552 in_ref: String,
553 #[arg(long)]
554 fmv_at_gift: String,
555 #[arg(long)]
556 donor_basis: Option<String>,
557 #[arg(long)]
558 donor_acquired: Option<String>,
559 },
560 /// Classify an inbound TransferIn as an inbound self-transfer ("my own coins" returning) —
561 /// non-taxable, creates a fresh lot. `--basis` defaults to $0 (conservative; fires the honest
562 /// zero-basis advisory when omitted); `--acquired` defaults to 1 year + 1 day before receipt
563 /// (assumed long-term for a cold-storage deposit; discloses an advisory so you can correct it).
564 ClassifyInboundSelfTransfer {
565 in_ref: String,
566 #[arg(long)]
567 basis: Option<String>,
568 #[arg(long)]
569 acquired: Option<String>,
570 },
571 /// Reclassify a pending TransferOut.
572 ReclassifyOutflow {
573 out: String,
574 #[arg(long, value_enum)]
575 as_kind: OutKindArg,
576 /// USD fair-market value of the disposed BTC at the transfer date — dollars, NOT sats.
577 /// For a sell/spend this is the gross proceeds; for a gift/donation it is the FMV at the
578 /// contribution date (26 CFR 1.170A-1(c)(1)). Entering the sats amount here is a common
579 /// error and draws a non-fatal warning when it exceeds 100x the market value.
580 #[arg(long)]
581 amount: String,
582 #[arg(long)]
583 fee: Option<String>,
584 #[arg(long)]
585 appraisal: bool,
586 /// Free-form donee identifier (e.g. "Alice", "Charity X"). Carried through to
587 /// removals.csv and Form 8283; does not affect tax math.
588 #[arg(long)]
589 donee: Option<String>,
590 },
591 /// Set a manual FMV on an event.
592 SetFmv {
593 /// The event reference to set the FMV on (see `btctax events list`).
594 event: String,
595 /// Fair-market value of the BTC at the event date — USD dollars, NOT sats.
596 #[arg(long)]
597 fmv: String,
598 },
599 /// Void a revocable decision.
600 Void { target: String },
601 /// Resolve an Unclassified row from a JSON imported payload.
602 ClassifyRaw {
603 target: String,
604 /// A JSON-encoded imported EventPayload (serde externally-tagged: `{"Variant":{...}}`) to
605 /// resolve the Unclassified target as. Must be an IMPORTED variant — Acquire, Income,
606 /// Dispose, TransferOut, TransferIn, or Unclassified. USD fields (usd_cost, fee_usd, …) are
607 /// decimal STRINGS; `sat` is an integer.
608 ///
609 /// FORMAT (Acquire example):
610 /// {"Acquire":{"sat":2000000,"usd_cost":"1680.00","fee_usd":"5.00","basis_source":"ExchangeProvided"}}
611 #[arg(long, verbatim_doc_comment)]
612 payload_json: String,
613 },
614 /// Accept an import conflict.
615 AcceptConflict { conflict: String },
616 /// Reject an import conflict.
617 RejectConflict { conflict: String },
618 /// Path-B safe-harbor allocate (from the actual pre-2025 position).
619 SafeHarborAllocate {
620 #[arg(long, value_enum, default_value_t = MethodArg::Actual)]
621 method: MethodArg,
622 #[arg(long)]
623 attest: bool,
624 },
625 /// Attest an existing allocation as timely.
626 SafeHarborAttest,
627 /// §A.4 Specific-ID: pick the exact lots a disposal consumes.
628 SelectLots {
629 disposal: String,
630 /// One lot pick per --from flag (repeatable). Each PICK is
631 /// `<origin_event_id>#<split_sequence>:<sat>`. The origin_event_id + split come from the
632 /// `lot` column of disposals.csv or the `origin_event`/`split` columns of lots.csv
633 /// (export-snapshot). The total sat across the picks must equal the disposal's principal
634 /// (validated in the fold).
635 ///
636 /// FORMAT (two picks):
637 /// --from import|coinbase|X#0:25000 --from import|river|Y#1:5000
638 #[arg(long = "from", required = true, verbatim_doc_comment)]
639 from: Vec<String>,
640 },
641 /// §A.4 Batch import LotSelections from a CSV (disposal_ref,origin_event_id,split_sequence,sat).
642 ImportSelections {
643 /// CSV of lot picks imported as LotSelection decisions (§A.4). The header is REQUIRED and
644 /// validated loudly; rows sharing a disposal_ref are grouped into a single decision.
645 /// disposal_ref is the disposal event's ref (disposals.csv `event` column); origin_event_id
646 /// is the lot's origin (lots.csv `origin_event` column).
647 ///
648 /// FORMAT (header + one sample row):
649 /// disposal_ref,origin_event_id,split_sequence,sat
650 /// import|gemini|trade|T-2.O-2,import|coinbase|X,0,1000000
651 #[arg(verbatim_doc_comment)]
652 csv: PathBuf,
653 },
654 /// SE-completion Chunk C: flip `business` (and optionally `kind`) on an already-imported Income event.
655 ///
656 /// Corrects the `business: false` hard-code that River (and other adapters) emit at ingest time,
657 /// enabling SE-tax treatment for professional miners / stakers. The target is validated at RECORD
658 /// TIME (UX-P4-3): a missing or non-Income event ref is REFUSED — nothing is recorded — and a
659 /// duplicate re-decide is refused too; `void` the prior decision first, then re-issue. For TransferIn
660 /// rows use `classify-inbound-income` instead.
661 ReclassifyIncome {
662 /// The Income event reference (from `report` or `income_recognized.csv` 'event' column).
663 income_event: String,
664 /// Whether this income is from a trade or business (true → SE-tax eligible).
665 /// Must be supplied explicitly: `--business true` or `--business false`.
666 #[arg(long, required = true, action = clap::ArgAction::Set)]
667 business: bool,
668 /// Optional income kind correction: mining|staking|interest|airdrop|reward.
669 /// Omit to keep the original kind (only flip `business`).
670 #[arg(long)]
671 kind: Option<String>,
672 },
673 /// Store Form 8283 Section-B donation + appraiser details for a donation event.
674 /// The event ref is the TransferOut EventId from the removals.csv 'event' column.
675 SetDonationDetails {
676 /// TransferOut event reference for the donation (from removals.csv 'event' column).
677 out_event_ref: String,
678 /// Donee organization name (Part IV; required).
679 #[arg(long, required = true)]
680 donee_name: String,
681 /// Donee mailing address (Part IV; optional).
682 #[arg(long)]
683 donee_address: Option<String>,
684 /// Donee EIN (Part IV; required for Section-B completeness).
685 #[arg(long)]
686 donee_ein: Option<String>,
687 /// Qualified appraiser name (Part III; required).
688 #[arg(long, required = true)]
689 appraiser_name: String,
690 /// Appraiser mailing address (Part III; optional).
691 #[arg(long)]
692 appraiser_address: Option<String>,
693 /// Appraiser TIN/SSN/EIN (Part III §6695A; satisfies the TIN-or-PTIN requirement).
694 #[arg(long)]
695 appraiser_tin: Option<String>,
696 /// Appraiser PTIN (Part III §6695A; satisfies the TIN-or-PTIN requirement).
697 #[arg(long)]
698 appraiser_ptin: Option<String>,
699 /// Appraiser qualifications declaration (§170(f)(11)(E)).
700 #[arg(long)]
701 appraiser_qualifications: Option<String>,
702 /// Date the qualified appraisal was made (YYYY-MM-DD).
703 #[arg(long)]
704 appraisal_date: Option<String>,
705 /// FMV determination method override (overrides the section-derived default on the
706 /// Form 8283 carrier row; resolves the Section-A fmv_method deferral when supplied).
707 #[arg(long)]
708 fmv_method: Option<String>,
709 },
710 /// Show stored Form 8283 donation details for a donation event.
711 ShowDonationDetails {
712 /// TransferOut event reference for the donation (from removals.csv 'event' column).
713 out_event_ref: String,
714 },
715 /// Bulk-confirm self-transfers: link every PENDING outbound transfer in a time frame to one
716 /// destination wallet (non-taxable). Shows a preview + requires --yes (or interactive y/N).
717 BulkLinkTransfer {
718 /// Destination wallet every selected outflow links to.
719 #[arg(long)]
720 to_wallet: String,
721 /// Restrict to a single tax year (mutually exclusive with --from/--to).
722 #[arg(long, conflicts_with_all = ["from", "to"])]
723 year: Option<i32>,
724 /// Range start (YYYY-MM-DD; requires --to).
725 #[arg(long, requires = "to")]
726 from: Option<String>,
727 /// Range end (YYYY-MM-DD, inclusive; requires --from).
728 #[arg(long, requires = "from")]
729 to: Option<String>,
730 /// Only outflows FROM this source wallet.
731 #[arg(long)]
732 from_wallet: Option<String>,
733 /// Print the preview and exit without writing.
734 #[arg(long)]
735 dry_run: bool,
736 /// Skip the interactive confirmation (non-interactive apply).
737 #[arg(long)]
738 yes: bool,
739 },
740 /// Bulk-classify unknown-basis inbound deposits as self-transfer-ins ("my own coins"): apply
741 /// Cycle A's `SelfTransferMine` ($0 conservative basis, non-taxable) to MANY pending inbounds in a
742 /// time frame at once. Shows a preview surfacing the total USD given $0 basis (the over-tax
743 /// exposure) + requires --yes (or interactive y/N). Each is a voidable decision; for a deposit
744 /// whose real cost you can substantiate, classify it single-item with `classify-inbound-self-transfer --basis`.
745 BulkClassifyInboundSelfTransfer {
746 /// Restrict to a single tax year (mutually exclusive with --from/--to).
747 #[arg(long, conflicts_with_all = ["from", "to"])]
748 year: Option<i32>,
749 /// Range start (YYYY-MM-DD; requires --to).
750 #[arg(long, requires = "to")]
751 from: Option<String>,
752 /// Range end (YYYY-MM-DD, inclusive; requires --from).
753 #[arg(long, requires = "from")]
754 to: Option<String>,
755 /// Only inbounds received INTO this wallet.
756 #[arg(long)]
757 wallet: Option<String>,
758 /// Print the preview and exit without writing.
759 #[arg(long)]
760 dry_run: bool,
761 /// Skip the interactive confirmation (non-interactive apply).
762 #[arg(long)]
763 yes: bool,
764 },
765 /// Bulk-classify unknown-basis inbound deposits as INCOME (mining|staking|interest|airdrop|reward):
766 /// recognize MANY pending inbounds as ordinary income at their auto-FMV (the daily-close market
767 /// value at receipt) in one confirmed batch, with a UNIFORM `--kind` + `--business` flag. Shows a
768 /// preview surfacing the total income recognized + the count of inbounds EXCLUDED because no price
769 /// was available for their date (those stay pending — an income row with no FMV would year-gate).
770 /// Each is a voidable decision; for a single deposit use `classify-inbound-income`.
771 BulkClassifyInboundIncome {
772 /// Income kind for the whole batch: mining|staking|interest|airdrop|reward.
773 #[arg(long)]
774 kind: String,
775 /// Whether this income is from a trade or business (true → SE-tax eligible).
776 #[arg(long)]
777 business: bool,
778 /// Restrict to a single tax year (mutually exclusive with --from/--to).
779 #[arg(long, conflicts_with_all = ["from", "to"])]
780 year: Option<i32>,
781 /// Range start (YYYY-MM-DD; requires --to).
782 #[arg(long, requires = "to")]
783 from: Option<String>,
784 /// Range end (YYYY-MM-DD, inclusive; requires --from).
785 #[arg(long, requires = "from")]
786 to: Option<String>,
787 /// Only inbounds received INTO this wallet.
788 #[arg(long)]
789 wallet: Option<String>,
790 /// Print the preview and exit without writing.
791 #[arg(long)]
792 dry_run: bool,
793 /// Skip the interactive confirmation (non-interactive apply).
794 #[arg(long)]
795 yes: bool,
796 },
797 /// Bulk-reclassify unknown pending OUTFLOWS as dispositions (Sell|Spend): reclassify MANY pending
798 /// `TransferOut`s as a `Dispose` in one confirmed batch, with the daily-close market value at the
799 /// outflow date as the ESTIMATED proceeds. Shows a preview surfacing the total ESTIMATED proceeds
800 /// AND the total ESTIMATED gain (sum(fmv) - sum(basis)) + the count of outflows EXCLUDED because no price
801 /// was available for their date (those stay pending — a Sell with fabricated proceeds would be a
802 /// SILENT misreport). `--kind` is UNIFORM and accepts ONLY sell|spend (gift/donate are out of
803 /// scope). Each is a voidable decision; for a single outflow use `reclassify-outflow`.
804 BulkReclassifyOutflow {
805 /// Disposition kind for the whole batch: sell|spend (gift/donate rejected — out of scope).
806 #[arg(long)]
807 kind: String,
808 /// Restrict to a single tax year (mutually exclusive with --from/--to).
809 #[arg(long, conflicts_with_all = ["from", "to"])]
810 year: Option<i32>,
811 /// Range start (YYYY-MM-DD; requires --to).
812 #[arg(long, requires = "to")]
813 from: Option<String>,
814 /// Range end (YYYY-MM-DD, inclusive; requires --from).
815 #[arg(long, requires = "from")]
816 to: Option<String>,
817 /// Only outflows from this SOURCE wallet.
818 #[arg(long)]
819 wallet: Option<String>,
820 /// Print the preview and exit without writing.
821 #[arg(long)]
822 dry_run: bool,
823 /// Skip the interactive confirmation (non-interactive apply).
824 #[arg(long)]
825 yes: bool,
826 },
827 /// Bulk-resolve import conflicts: ACCEPT (adopt each new payload) or REJECT (keep each current
828 /// payload) MANY flagged `ImportConflict`s in one confirmed batch. Shows a `current → new` preview,
829 /// then requires --yes (or interactive y/N). Exactly one of --accept / --reject is required. Each
830 /// resolution is NON-REVOCABLE (`SupersedeImport`/`RejectImport` cannot be voided); to resolve a
831 /// conflict differently, exclude it and use single-item `accept-conflict`/`reject-conflict`.
832 #[command(group(clap::ArgGroup::new("resolve_action").required(true).args(["accept", "reject"])))]
833 BulkResolveConflict {
834 /// Accept every listed conflict (adopt each new payload onto its target).
835 #[arg(long)]
836 accept: bool,
837 /// Reject every listed conflict (keep each target's current payload).
838 #[arg(long)]
839 reject: bool,
840 /// Print the preview and exit without writing.
841 #[arg(long)]
842 dry_run: bool,
843 /// Skip the interactive confirmation (non-interactive apply).
844 #[arg(long)]
845 yes: bool,
846 },
847 /// Bulk-void MANY revocable reconcile decisions in one confirmed batch (bulk-void). Shows a preview
848 /// of every voidable decision (the SHARED `voidable_decisions` predicate — effective safe-harbor
849 /// allocations are OMITTED, #7), then requires --yes (or interactive y/N). Each void is
850 /// NON-REVOCABLE (a `VoidDecisionEvent` cannot itself be voided — re-apply the original decision to
851 /// restore). Voiding a `LotSelection` also re-exposes its disposal to the default method and clears
852 /// its optimizer attestation.
853 BulkVoid {
854 /// Print the preview and exit without writing.
855 #[arg(long)]
856 dry_run: bool,
857 /// Skip the interactive confirmation (non-interactive apply).
858 #[arg(long)]
859 yes: bool,
860 },
861 /// Match unreconciled inbound + outbound legs as self-transfers (self-transfer-passthrough C3).
862 /// With no --in/--out: PREVIEW the proposed pairs (read-only). With --in and --out: confirm ONE
863 /// pair (DROP for a same-wallet passthrough, RELOCATE for a cross-wallet transfer). NEVER automatic.
864 MatchSelfTransfers {
865 /// Confirm this in-leg (TransferIn eventref); requires --out.
866 #[arg(long = "in", requires = "out_ref")]
867 in_ref: Option<String>,
868 /// Confirm this out-leg (TransferOut eventref); requires --in.
869 #[arg(long = "out", requires = "in_ref")]
870 out_ref: Option<String>,
871 /// Override the suggested action (else the proposal's topology-derived action is used).
872 #[arg(long, value_enum)]
873 action: Option<SelfTransferActionArg>,
874 /// Print the preview and exit without writing (conflicts with --in/--out).
875 #[arg(long, conflicts_with_all = ["in_ref", "out_ref"])]
876 dry_run: bool,
877 },
878 /// Pseudo-reconcile MODE (sub-project 2): fill deliberately-fictional default decisions at
879 /// projection time (NEVER persisted) to clear the Hard classification blockers — a loudly-flagged
880 /// `[PSEUDO]` on-screen estimate you correct toward truth. `on`/`off` toggle the mode; `approve`
881 /// promotes chosen defaults to real (attested) decisions.
882 #[command(subcommand)]
883 Pseudo(Pseudo),
884 /// Conservative-filing (D-8): declare undocumented BTC at $0 basis — the IRS fallback for
885 /// unprovable basis. Folds to a single `EstimatedConservative` lot homed at `--window-end`
886 /// (the latest plausible acquisition → conservative holding period). Filing-ready, NOT pseudo.
887 /// v1 makes a pre-2025 tranche and a safe-harbor allocation mutually exclusive.
888 DeclareTranche {
889 /// Amount of undocumented BTC (required). A satoshi integer OR a BTC decimal, e.g. `0.5`
890 /// or `50000000` (a value with a `.` is BTC; a bare integer is satoshis). Must be > 0.
891 #[arg(long)]
892 amount: String,
893 /// Wallet holding the coins, e.g. `self:cold` or `exchange:coinbase:default`.
894 #[arg(long)]
895 wallet: String,
896 /// Earliest plausible acquisition date (YYYY-MM-DD).
897 #[arg(long)]
898 window_start: String,
899 /// Latest plausible acquisition date (YYYY-MM-DD) — the lot is homed here.
900 #[arg(long)]
901 window_end: String,
902 },
903 /// Approach-B: promote an already-declared `DeclareTranche` (D-8's $0 IRS fallback) to a filed `>$0`
904 /// basis floor (the minimum daily closing price over the attested acquisition window), behind a
905 /// mandatory purchase-provenance attestation (BG-D5), a two-sided informed-consent screen (BG-D6),
906 /// and a Form 8275 Part II narrative (BG-D7). Mitigates penalty exposure; does not eliminate it or
907 /// guarantee immunity — read the consent screen this verb prints before acknowledging.
908 PromoteTranche {
909 /// The `DeclareTranche` decision to promote (see `btctax events list` for the ref).
910 target: String,
911 /// The units' real acquisition provenance. Promotion requires `purchase`; every other value is
912 /// refused and pointed at modeling the real acquisition instead (BG-D5).
913 #[arg(long, value_enum)]
914 provenance: crate::cmd::promote::ProvenanceKind,
915 /// Path to a text file holding the Form 8275 Part II narrative (filer facts, Reg. §1.6662-4(f),
916 /// "in sufficient detail"). An empty or whitespace-only file is refused at record time (BG-D7).
917 #[arg(long)]
918 part_ii_file: PathBuf,
919 /// Non-interactive consent: the exact acknowledgment phrase shown on the consent screen. On an
920 /// interactive terminal, omitting this shows the screen and prompts for the phrase.
921 #[arg(long)]
922 i_acknowledge: Option<String>,
923 },
924}
925
926/// `reconcile pseudo <action>` — the pseudo-reconcile mode sub-verbs (sub-project 2).
927#[derive(Subcommand)]
928pub enum Pseudo {
929 /// Turn pseudo-reconcile mode ON. Projection now synthesizes non-persisted default decisions for
930 /// unresolved unknown-basis inbounds (self-transfer $0), unclassified rows, and import conflicts
931 /// (accept-first); every synthetic contribution is flagged `[PSEUDO]` on screen and BLOCKS export.
932 On,
933 /// Turn pseudo-reconcile mode OFF. Projection reverts to real-only instantly and totally (no
934 /// fictional events were ever written). Already-approved decisions REMAIN (they are real now).
935 Off,
936 /// Promote pseudo default decisions to REAL (attested) decisions in bulk. Shows a preview + requires
937 /// `--yes` (or `--dry-run` to preview only). Optional filters restrict which defaults are approved.
938 Approve {
939 /// Only approve defaults of this TYPE: `self-transfer` (unknown-basis inbound → $0 self-transfer),
940 /// `raw` (unclassified row placeholder), `conflict` (import conflict accept-first), or `fmv`
941 /// (native income FMV synthesized from the daily close). Omit = all.
942 #[arg(long, value_enum)]
943 kind: Option<PseudoKindArg>,
944 /// Only approve defaults whose target event is in this wallet (e.g. `exchange:coinbase:main`).
945 #[arg(long)]
946 wallet: Option<String>,
947 /// Only approve defaults whose target event falls in this tax year.
948 #[arg(long)]
949 year: Option<i32>,
950 /// Print the preview and exit without writing.
951 #[arg(long)]
952 dry_run: bool,
953 /// Skip the interactive confirmation (non-interactive apply).
954 #[arg(long)]
955 yes: bool,
956 },
957}
958
959/// The pseudo-default TYPE filter for `reconcile pseudo approve --kind`.
960#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
961pub enum PseudoKindArg {
962 /// Unknown-basis inbound defaulted to a $0-basis self-transfer-in.
963 SelfTransfer,
964 /// Unclassified row defaulted to a zero-value placeholder (ClassifyRaw).
965 Raw,
966 /// Import conflict defaulted to accept-first (SupersedeImport).
967 Conflict,
968 /// Native income with a missing FMV defaulted to the daily-close value (ManualFmv).
969 Fmv,
970}
971
972#[derive(Copy, Clone, ValueEnum)]
973pub enum SelfTransferActionArg {
974 /// Same-wallet passthrough → SelfTransferPassthrough (both legs skipped, non-taxable).
975 Drop,
976 /// Cross-wallet transfer → TransferLink (relocate the lots to the destination wallet).
977 Relocate,
978}
979
980/// One official form in the `export-irs-pdf` packet (the `--forms` opt-in filter).
981#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
982pub enum FormArg {
983 /// Form 8949 (per-disposition capital-gains rows).
984 F8949,
985 /// Schedule D (aggregated capital-gains totals).
986 ScheduleD,
987 /// Schedule SE (self-employment tax).
988 ScheduleSe,
989 /// Form 8283 (noncash charitable contributions).
990 Form8283,
991 /// Form 1040 (capital-gains cells + the digital-asset question).
992 Form1040,
993 /// Form 8275 (Disclosure Statement — Approach-B's Cohan-estimate promoted-basis disclosure).
994 Form8275,
995}
996
997#[derive(Copy, Clone, ValueEnum)]
998pub enum FilingStatusArg {
999 Single,
1000 Mfj,
1001 Mfs,
1002 Hoh,
1003 Qss,
1004}
1005
1006impl From<FilingStatusArg> for FilingStatus {
1007 fn from(a: FilingStatusArg) -> Self {
1008 match a {
1009 FilingStatusArg::Single => FilingStatus::Single,
1010 FilingStatusArg::Mfj => FilingStatus::Mfj,
1011 FilingStatusArg::Mfs => FilingStatus::Mfs,
1012 FilingStatusArg::Hoh => FilingStatus::HoH,
1013 FilingStatusArg::Qss => FilingStatus::Qss,
1014 }
1015 }
1016}
1017
1018#[derive(Copy, Clone, ValueEnum)]
1019pub enum FeeArg {
1020 C,
1021 B,
1022}
1023
1024#[derive(Copy, Clone, ValueEnum)]
1025pub enum MethodLotArg {
1026 Fifo,
1027 Lifo,
1028 Hifo,
1029}
1030
1031#[derive(Copy, Clone, ValueEnum)]
1032pub enum OutKindArg {
1033 Sell,
1034 Spend,
1035 Gift,
1036 Donate,
1037}
1038
1039impl From<MethodLotArg> for LotMethod {
1040 fn from(a: MethodLotArg) -> Self {
1041 match a {
1042 MethodLotArg::Fifo => LotMethod::Fifo,
1043 MethodLotArg::Lifo => LotMethod::Lifo,
1044 MethodLotArg::Hifo => LotMethod::Hifo,
1045 }
1046 }
1047}
1048
1049#[derive(Copy, Clone, ValueEnum)]
1050pub enum MethodArg {
1051 Actual,
1052 ProRata,
1053}
1054
1055#[cfg(test)]
1056mod tests {
1057 use super::*;
1058 use clap::CommandFactory;
1059
1060 /// Render the LONG help (`--help`) of a subcommand identified by its path, recursing into
1061 /// nested subcommands (e.g. `["reconcile", "import-selections"]`). Mirrors what a user sees at
1062 /// `btctax <path...> --help`, which includes each argument's verbatim long-help.
1063 fn long_help_of(path: &[&str]) -> String {
1064 let mut cmd = Cli::command();
1065 for name in path {
1066 cmd = cmd
1067 .find_subcommand(name)
1068 .unwrap_or_else(|| panic!("subcommand {name:?} exists"))
1069 .clone();
1070 }
1071 cmd.render_long_help().to_string()
1072 }
1073
1074 // Requirement 3, `--help` half: each file/format-taking arg's long-help carries its FORMAT +
1075 // a text EXAMPLE. Tokens are comma/brace-joined (no spaces) so help-wrapping can never break
1076 // them (verified against the real binary output). This is the single source of truth that
1077 // clap_mangen also renders into the per-subcommand man page (Task 2).
1078
1079 #[test]
1080 fn help_documents_key_backup_format() {
1081 let h = long_help_of(&["init"]);
1082 assert!(
1083 h.contains("-----BEGIN PGP PRIVATE KEY BLOCK-----"),
1084 "init --key-backup help must document the ASCII-armored key format:\n{h}"
1085 );
1086 }
1087
1088 #[test]
1089 fn help_documents_backup_key_format() {
1090 let h = long_help_of(&["backup-key"]);
1091 assert!(
1092 h.contains("-----BEGIN PGP PRIVATE KEY BLOCK-----"),
1093 "backup-key --out help must document the ASCII-armored key format:\n{h}"
1094 );
1095 }
1096
1097 #[test]
1098 fn help_documents_export_snapshot_format() {
1099 let h = long_help_of(&["export-snapshot"]);
1100 // The exact removals.csv header read from the render.rs writer.
1101 assert!(
1102 h.contains("event,kind,removed_at,lot,sat,basis,fmv_at_transfer"),
1103 "export-snapshot --out help must document the projection CSV headers:\n{h}"
1104 );
1105 }
1106
1107 #[test]
1108 fn help_documents_import_selections_format() {
1109 let h = long_help_of(&["reconcile", "import-selections"]);
1110 assert!(
1111 h.contains("disposal_ref,origin_event_id,split_sequence,sat"),
1112 "import-selections help must document the required CSV header:\n{h}"
1113 );
1114 }
1115
1116 #[test]
1117 fn help_documents_classify_raw_format() {
1118 let h = long_help_of(&["reconcile", "classify-raw"]);
1119 // The exact externally-tagged serde shape (Usd = decimal string, sat = integer).
1120 assert!(
1121 h.contains(r#"{"Acquire":{"sat":2000000,"usd_cost":"1680.00","fee_usd":"5.00","basis_source":"ExchangeProvided"}}"#),
1122 "classify-raw --payload-json help must document the JSON payload shape:\n{h}"
1123 );
1124 }
1125
1126 #[test]
1127 fn help_documents_select_lots_format() {
1128 let h = long_help_of(&["reconcile", "select-lots"]);
1129 assert!(
1130 h.contains("import|coinbase|X#0:25000"),
1131 "select-lots --from help must document the <event>#<split>:<sat> pick format:\n{h}"
1132 );
1133 }
1134}