btctax_cli/lib.rs
1//! btctax-cli: the CLI + reconciliation library that wires the encrypted vault (btctax-store),
2//! ingest (btctax-adapters), and the pure projection (btctax-core) into the Phase-1 command surface
3//! (spec §11). The library is I/O-explicit and deterministic; the binary (`main.rs`) is a thin clap
4//! dispatch. PRIVACY: tests use only temp vaults + synthetic fixtures; no real user file is ever read.
5pub mod bulk_estimated;
6pub mod cli;
7pub mod cmd;
8pub mod config;
9pub mod donation_details;
10pub mod eventref;
11pub mod input_form_store;
12pub mod optimize_attest;
13pub mod price_cache;
14pub mod render;
15pub mod resolve;
16pub mod return_inputs;
17pub mod session;
18pub mod tax_profile;
19pub mod testonly;
20
21pub use cli::Cli;
22// Re-exported at the crate root so the TUI editor (`btctax-tui-edit`) can call it WITHOUT the `cmd::`
23// token its KAT-G1 source gate forbids in non-test code. That gate exists to keep session-lifecycle /
24// lock-holding `cmd::` fns out of the held-session editor; `guard_allocation_vs_tranche` is a PURE
25// `&[LedgerEvent] -> Result` predicate — no `Session`, no lock, no I/O — so the gate's intent is honored,
26// not evaded. Any FUTURE addition here must be equally pure (do NOT re-export a session-opening fn).
27pub use cmd::tranche::guard_allocation_vs_tranche;
28// Re-exported at the crate root mirroring `ATTEST_PHRASE` (below): a plain, distinct consent-phrase
29// constant, not a `cmd::`-scoped session/lock fn, so it belongs beside the other top-level phrase gates.
30pub use cmd::promote::PROMOTE_ACK_PHRASE;
31// Re-exported at the crate root so the TUI export path (`btctax-tui::export::do_export`) can call the
32// BG-D8 completeness gate WITHOUT the `cmd::` token its KAT-E10 source gate forbids in non-test code
33// (Approach-B Task 17). Like `guard_allocation_vs_tranche` above, this is a PURE
34// `(&LedgerState, &[LedgerEvent], Option<i32>) -> Result` predicate — no `Session`, no lock, no I/O — so
35// the gate's intent (keep session-lifecycle `cmd::` fns out of the held-session viewer) is honored, not
36// evaded. Any FUTURE addition here must be equally pure (do NOT re-export a session-opening fn).
37pub use cmd::admin::promote_export_gate;
38pub use config::CliConfig;
39pub use session::{
40 BulkFilter, BulkIncomeFilter, BulkIncomePlan, BulkIncomeRow, BulkLinkPlan, BulkLinkRow,
41 BulkReclassifyOutflowPlan, BulkReclassifyOutflowRow, BulkResolvePlan, BulkResolveRow,
42 BulkStiFilter, BulkStiPlan, BulkStiRow, BulkVoidPlan, BulkVoidRow, Frame, MatchAction,
43 MatchProposal, Session,
44};
45
46#[derive(Debug, thiserror::Error)]
47pub enum CliError {
48 #[error(transparent)]
49 Store(#[from] btctax_store::StoreError),
50 #[error(transparent)]
51 Core(#[from] btctax_core::CoreError),
52 #[error(transparent)]
53 Adapter(#[from] btctax_adapters::AdapterError),
54 #[error("sqlite: {0}")]
55 Sqlite(#[from] rusqlite::Error),
56 /// C1: `write_csv_exports` (Task 15) uses `?` on `csv::Writer` ops (→ `csv::Error`); `csv::Error`
57 /// is its own type (NOT covered by `Io(#[from] io::Error)`, whose `From` goes the other way), so it
58 /// needs its own variant or Task 15 will not compile.
59 #[error("csv: {0}")]
60 Csv(#[from] csv::Error),
61 #[error("io: {0}")]
62 Io(#[from] std::io::Error),
63 /// `export-irs-pdf`: an official IRS PDF fill failed — most importantly the geometric read-back
64 /// FAILING CLOSED on a mis-mapped cell, so no wrong tax form is ever written.
65 #[error("IRS form fill: {0}")]
66 FormFill(#[from] btctax_forms::FormsError),
67 /// A user-supplied event reference did not parse as a canonical `EventId` (eventref.rs).
68 #[error("not a valid event reference: {0:?}")]
69 BadEventRef(String),
70 /// A CLI argument was malformed (bad USD/date/enum/wallet spec, or a contradictory flag set).
71 #[error("usage: {0}")]
72 Usage(String),
73 /// M1: a `cli_config` row held an unrecognized value (corrupt DB, future-written value, or manual
74 /// edit gone wrong). Returning an error is safer than silently misreading the stored intent.
75 #[error("unrecognized stored config value: key={key:?} value={value:?}")]
76 BadConfigValue { key: String, value: String },
77 /// P9 §2.6: a stored `return_inputs` row predates the form-question registry (or was written by a newer
78 /// build) and this build does not migrate it. There is no user data yet, so the policy is refuse-and-
79 /// reimport rather than a per-key migration (a version check cannot forget a key). The remedy names all
80 /// THREE commands, in order — `clear` DISCARDS any computed carryover this row's prior reports wrote onto
81 /// it, so the rebuild step is not optional. (Retire this the moment real data exists — FOLLOWUPS, release
82 /// gate.)
83 #[error(
84 "the stored inputs for {year} predate the form-question registry (schema v{found}; this build reads \
85 v{expected}). Run `btctax income clear {year}` — which DISCARDS any carryover this row's prior \
86 reports computed onto it — then `btctax income import` for {year}; then, if this row carried a \
87 computed carryover, `btctax report --tax-year {prior} --write-carryover` to rebuild it.",
88 prior = year - 1
89 )]
90 StaleReturnInputs {
91 year: i32,
92 found: i64,
93 expected: i64,
94 },
95 /// §6.3 / C-1: a PARKED input-form draft is at a schema version this build does not read, and this
96 /// build does not migrate it. Unlike a stale WIP draft (regenerable → discarded), a parked draft may
97 /// hold irreplaceable carryover that exists ONLY in the draft — there is no committed row to re-import
98 /// from — so we REFUSE (fail closed) rather than discard. The remedy therefore is NOT `income import`
99 /// (that recovers a WIP row from committed state, which a parked draft has none of): the message must
100 /// tell the filer the data lives in the draft, must not be discarded, and to re-run on / export from the
101 /// app version that wrote it. (Retire alongside `StaleReturnInputs` the moment migrations exist.)
102 #[error(
103 "year {year}'s parked full return is schema v{found} but this build expects v{expected}; \
104 an upgrade changed the input format. Its data lives only in the draft — do not discard it. \
105 Re-run on the app version that wrote it, or export it there first."
106 )]
107 StaleParkedDraft {
108 year: i32,
109 found: i64,
110 expected: i64,
111 },
112 /// §6.2 draft-coherence: an authoritative committed-row write (`income import` / `income answer` /
113 /// carryover write-back / `income clear`) was attempted for a year whose input-form draft is PARKED.
114 /// A parked draft is the SOLE copy of a screened return (C-1) — clobbering it via the committed row
115 /// would silently destroy irreplaceable data — so the write is REFUSED (fail closed). The message
116 /// names BOTH in-form exits (M-d): re-commit it (`use full return`) or drop it (`discard parked
117 /// draft`, a confirmed delete); a WIP draft, by contrast, is regenerable and is cleared silently.
118 #[error(
119 "year {year} holds a parked full return — in the form, 'use full return' to re-commit it, or \
120 'discard parked draft' (a confirmed delete) to drop it; then re-run this command."
121 )]
122 ParkedDraftBlocksWrite { year: i32 },
123 /// Sub-project 3 attestation gate: an export was attempted while the ledger is pseudo-reconciled
124 /// (a synthetic, non-persisted default contributes to the projection) and NO attestation phrase was
125 /// supplied. Producing a form/data file from a fictional draft requires typing the exact phrase.
126 /// (Supersedes sub-2's interim [I3] blanket refusal.)
127 #[error(
128 "export refused: the ledger is pseudo-reconciled (a synthetic default contributes to the \
129 projection). To export this draft ON PURPOSE, attest the exact phrase {:?} (pass --attest, or \
130 type it at the prompt). Otherwise run `reconcile pseudo off` (or approve + attest the defaults).",
131 ATTEST_PHRASE
132 )]
133 AttestationRequired,
134 /// Sub-project 3 attestation gate: an export was attempted while the ledger is pseudo-reconciled and
135 /// the supplied attestation phrase did NOT match (trimmed, case-sensitive, exact). A wrong phrase is
136 /// FAILED regardless of environment [R0-I1] — no fictional form leaves the machine.
137 #[error(
138 "export refused: the attestation phrase did not match. The ledger is pseudo-reconciled; type the \
139 phrase EXACTLY (trimmed, case-sensitive): {:?}.",
140 ATTEST_PHRASE
141 )]
142 AttestationFailed,
143 /// UX-P4-8: an I/O failure at a user-named path — a `--vault` that is missing/unreadable, or an
144 /// `--out` that collides / cannot be created. Carries the offending PATH and a one-clause remedy
145 /// hint that the bare `io::Error` (surfaced pathlessly through `Store::Io` / `Io`) lacks. Mirrors
146 /// the adapters' `AdapterError::Io { path, source }` so every path-bearing io error reads alike.
147 #[error("io {path}: {source} ({hint})")]
148 PathIo {
149 path: String,
150 hint: String,
151 #[source]
152 source: std::io::Error,
153 },
154}
155
156/// UX-P4-8 hint: shown when a `--vault` cannot be opened (missing/unreadable path).
157pub const VAULT_OPEN_HINT: &str =
158 "check the --vault path, or run `btctax init` to create a new vault";
159
160/// UX-P4-8 hint: shown when an export `--out` directory cannot be created (a colliding file, a
161/// missing parent, or a permission problem).
162pub const EXPORT_OUT_HINT: &str =
163 "choose an --out path that does not already exist as a file and whose parent is writable";
164
165/// Re-wrap a `StoreError` I/O failure with the offending PATH + a one-clause hint (UX-P4-8). ONLY the
166/// pathless `StoreError::Io` is enriched; every other variant (`WrongPassphrase`, `Locked`,
167/// `HalfCreatedVault`, …) passes through unchanged — each already carries its own precise meaning and
168/// must NOT be masked behind a generic path/hint.
169pub fn store_io_with_path(
170 e: btctax_store::StoreError,
171 path: &std::path::Path,
172 hint: &str,
173) -> CliError {
174 match e {
175 btctax_store::StoreError::Io(source) => CliError::PathIo {
176 path: path.display().to_string(),
177 hint: hint.to_string(),
178 source,
179 },
180 other => CliError::Store(other),
181 }
182}
183
184/// Re-wrap a pathless I/O failure with the offending PATH + a one-clause hint (UX-P4-8). Enriches
185/// BOTH shapes an export write can produce: a raw `CliError::Io` (a `write`/`flush` mid-write) AND a
186/// `CliError::Store(StoreError::Io)` (a `mkdir_owner_only`/`open_owner_only` under `out_dir` — e.g. a
187/// SUBPATH collision like `out_dir/lots.csv` already existing as a directory, which `?`-converts
188/// through `From<StoreError>`). A `CliError::Csv` (a serialization error, not a path problem) and
189/// every other variant pass through unchanged.
190pub fn cli_io_with_path(e: CliError, path: &std::path::Path, hint: &str) -> CliError {
191 match e {
192 CliError::Io(source) | CliError::Store(btctax_store::StoreError::Io(source)) => {
193 CliError::PathIo {
194 path: path.display().to_string(),
195 hint: hint.to_string(),
196 source,
197 }
198 }
199 other => other,
200 }
201}
202
203/// The exact phrase a user must affirm to export a form/data file while the ledger is pseudo-reconciled
204/// (sub-project 3). Compared TRIMMED, case-SENSITIVE, exact. The prompt + both error strings are BUILT
205/// from this constant [R0-M1] so there is no drift (a KAT asserts they contain it). `pub` so btctax-tui
206/// shares it [R0-r2-N2].
207pub const ATTEST_PHRASE: &str = "I attest this is true";
208
209/// PURE exact-compare attestation gate — NO I/O, NO TTY read [R0-I2]. The interactive prompt lives in
210/// the caller (the `export-snapshot` main.rs arm / the btctax-tui export modal); this helper only
211/// compares, keeping the library I/O-explicit and the KATs deterministic (no env-dependent branch).
212///
213/// - `attest.map(str::trim) == Some(ATTEST_PHRASE)` → `Ok(())`.
214/// - `Some(_)` non-matching → `Err(AttestationFailed)` (a wrong phrase FAILS regardless of env) [R0-I1].
215/// - `None` → `Err(AttestationRequired)`.
216///
217/// `pub` so btctax-tui shares the exact-compare [R0-r2-N2].
218pub fn require_attestation(attest: Option<&str>) -> Result<(), CliError> {
219 match attest.map(str::trim) {
220 Some(p) if p == ATTEST_PHRASE => Ok(()),
221 Some(_) => Err(CliError::AttestationFailed),
222 None => Err(CliError::AttestationRequired),
223 }
224}