diff --git a/crates/ledger-import/src/bank_csv.rs b/crates/ledger-import/src/bank_csv.rs index f3f77245..c3cb202b 100644 --- a/crates/ledger-import/src/bank_csv.rs +++ b/crates/ledger-import/src/bank_csv.rs @@ -84,6 +84,78 @@ pub enum BankCsvError { Csv(String), } +/// A bank's description cell that held a number reading as a tax id (a +/// nine-digit reference, say), kept masked to its last four digits. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MaskedCell { + /// The file's line the transaction is on (the first line is 1). + pub line: u64, + /// The column: always "Description". + pub column: &'static str, + /// How many numbers in the cell were masked. + pub numbers: usize, +} + +/// A parsed bank CSV whose descriptions are safe to keep. +#[derive(Clone, Debug, PartialEq)] +pub struct MaskedBankImport { + /// The transactions in file order, a description that held a number + /// reading as a tax id masked to its last four digits. + pub transactions: Vec, + /// Which cells were masked, in file order. + pub masked: Vec, +} + +/// [`parse_bank_csv_with`] for a file that is to be kept: a description a +/// bank wrote is not typed by a person and commonly carries a nine-digit +/// reference, so the file is not refused for one. A number in it that +/// reads as a tax id (`ledger_core::settings::holds_printed_tin`: nine +/// digits standing alone, an SSN's 3-2-4, an EIN's 2-7) is masked to its +/// last four digits (`•••-••-1234`) in the description, and the cell is +/// named in [`MaskedBankImport::masked`] (BS-partner-2; the owner's choice, +/// 2026-11-21). +/// +/// ```text +/// GOAL: a bank file is journaled whole, and no full tax id is. +/// SOURCE: BS-partner-2; docs/spec/claims/partner.md (the CHOICE: masking +/// on bank imports). +/// INVARIANTS: +/// 1. No kept description holds a number the detector finds. +/// 2. Every cell that was masked is named with its line; every other +/// cell is as the bank wrote it, and the transactions are +/// parse_bank_csv_with's, amounts and dates unchanged. +/// SCENARIOS: +/// 1. IF a description says `ACH 000-00-0000 payroll`: SHOULD keep +/// `ACH •••-••-0000 payroll` and name its line. +/// 2. IF it says `CHECK 1234567890`: SHOULD keep it as written. +/// ``` +pub fn parse_bank_csv_masked( + text: &str, + order: Option, +) -> Result { + let mut masked = Vec::new(); + let transactions = parse_rows(text, order)? + .into_iter() + .map(|(line, mut txn)| { + let numbers = ledger_core::settings::count_printed_tins(&txn.description); + if numbers > 0 { + txn.description = + ledger_core::settings::mask_printed_tins(&txn.description).into_owned(); + masked.push(MaskedCell { + line, + column: "Description", + numbers, + }); + } + txn + }) + .collect(); + Ok(MaskedBankImport { + transactions, + masked, + }) +} + /// Parse a QBO bank CSV, reading slash dates in the order the file itself /// settles. Returns transactions in file order. pub fn parse_bank_csv(text: &str) -> Result, BankCsvError> { @@ -96,11 +168,22 @@ pub fn parse_bank_csv_with( text: &str, order: Option, ) -> Result, BankCsvError> { + Ok(parse_rows(text, order)? + .into_iter() + .map(|(_, txn)| txn) + .collect()) +} + +/// The transactions with the file line each came from. +fn parse_rows( + text: &str, + order: Option, +) -> Result, BankCsvError> { let mut reader = csv::ReaderBuilder::new() .has_headers(false) .trim(csv::Trim::All) .from_reader(text.as_bytes()); - let mut rows: Vec<(String, String, Decimal)> = Vec::new(); + let mut rows: Vec<(u64, String, String, Decimal)> = Vec::new(); let mut seen_row = false; for (idx, record) in reader.records().enumerate() { let record = record.map_err(|e| BankCsvError::Csv(e.to_string()))?; @@ -134,16 +217,20 @@ pub fn parse_bank_csv_with( if amount.is_zero() { continue; // zero-amount rows carry no money } - rows.push((fields[0].to_string(), fields[1].to_string(), amount)); + let line = record.position().map_or(idx as u64 + 1, |p| p.line()); + rows.push((line, fields[0].to_string(), fields[1].to_string(), amount)); } - let order = date_order(rows.iter().map(|r| r.0.as_str()), order)?; + let order = date_order(rows.iter().map(|r| r.1.as_str()), order)?; rows.into_iter() - .map(|(date, description, amount)| { - Ok(BankTransaction { - date: parse_date(&date, order)?, - description, - amount, - }) + .map(|(line, date, description, amount)| { + Ok(( + line, + BankTransaction { + date: parse_date(&date, order)?, + description, + amount, + }, + )) }) .collect() } diff --git a/crates/ledger-import/src/chart_csv.rs b/crates/ledger-import/src/chart_csv.rs index 47d1d89c..eb421b4b 100644 --- a/crates/ledger-import/src/chart_csv.rs +++ b/crates/ledger-import/src/chart_csv.rs @@ -49,6 +49,10 @@ pub enum ChartCsvError { /// "code" or "name". field: &'static str, }, + /// A cell that looks like it holds a tax id: the words name the row + /// and column and never the number (BS-partner-2). + #[error("{0}")] + LooksLikeTin(String), /// Malformed CSV. #[error("csv error: {0}")] Csv(String), @@ -70,6 +74,10 @@ pub enum ChartCsvError { /// (BadType), and a non-blank code and name (Blank, with its row). /// 3. A blank parent or tax category is None; blank lines are skipped; /// an empty file is no rows. +/// 4. A cell that looks like a tax id (a name with any run of nine +/// digits, any other cell with an SSN's or EIN's shape or nine +/// digits alone) refuses the file, naming its row (the file's line) +/// and column and never the number (LooksLikeTin; BS-partner-2). /// ``` pub fn parse_chart_csv(text: &str) -> Result, ChartCsvError> { let mut reader = csv::ReaderBuilder::new() @@ -109,6 +117,27 @@ pub fn parse_chart_csv(text: &str) -> Result, ChartCsvError> { }); } } + // A chart is typed by a person, so a number that reads as a tax id + // in any cell is refused, naming the row and the column; the name + // is read as strictly as an account name is (any run of nine + // digits). + let line = record.position().map_or(idx as u64 + 1, |p| p.line()); + let columns = ["code", "name", "type", "parent_code", "tax_category"]; + for (n, value) in fields.iter().enumerate() { + let looks = if n == 1 { + ledger_core::parties::has_full_tin(value) + } else { + ledger_core::settings::holds_printed_tin(value) + }; + if looks { + return Err(ChartCsvError::LooksLikeTin( + ledger_core::settings::tin_refusal(&format!( + "the {} cell of row {line}", + columns[n] + )), + )); + } + } let account_type = fields[2].to_lowercase(); match account_type.as_str() { "asset" | "liability" | "equity" | "revenue" | "expense" => {} diff --git a/crates/ledger-import/src/lib.rs b/crates/ledger-import/src/lib.rs index 49822aff..6d193832 100644 --- a/crates/ledger-import/src/lib.rs +++ b/crates/ledger-import/src/lib.rs @@ -30,7 +30,10 @@ pub mod workpaper; pub mod xlsx; pub use asset_register::{asset_register_pdf, asset_register_xlsx}; -pub use bank_csv::{BankCsvError, BankTransaction, DateOrder, parse_bank_csv, parse_bank_csv_with}; +pub use bank_csv::{ + BankCsvError, BankTransaction, DateOrder, MaskedBankImport, MaskedCell, parse_bank_csv, + parse_bank_csv_masked, parse_bank_csv_with, +}; pub use chart_csv::{ChartRow, parse_chart_csv}; pub use extract::{ExtractError, page_count, page_png, pdf_lines, pdf_text, text_of, xlsx_text}; pub use format::round_display; diff --git a/crates/ledger-mcp/src/tools/entries.rs b/crates/ledger-mcp/src/tools/entries.rs index 1d41d459..89f2c681 100644 --- a/crates/ledger-mcp/src/tools/entries.rs +++ b/crates/ledger-mcp/src/tools/entries.rs @@ -732,7 +732,13 @@ impl BooksServer { } }; let (csv, claim) = self.csv_given(&p.upload_id)?; - let txns = ledger_import::parse_bank_csv_with(&csv, order).map_err(|e| e.to_string())?; + // A description a bank wrote is not typed by a person: a number in + // it that reads as a tax id is kept masked to its last four digits + // and named in the answer, never a reason to refuse the file. + let ledger_import::MaskedBankImport { + transactions: txns, + masked, + } = ledger_import::parse_bank_csv_masked(&csv, order).map_err(|e| e.to_string())?; let mut store = self.lock()?; let bank = store .ledger() @@ -838,11 +844,32 @@ impl BooksServer { .map_err(|e| e.to_string())?; } let count = imported.len(); + let masked_count: usize = masked.iter().map(|m| m.numbers).sum(); + let masked_note = (masked_count > 0).then(|| { + let lines: Vec = masked.iter().map(|m| m.line.to_string()).collect(); + format!( + "{masked_count} value{} in the Description column read as a tax id (nine digits standing alone, or an SSN's or an EIN's shape) and {} kept masked to the last four digits, on line{} {}. A bank's description is not typed by a person and often carries a nine-digit reference, so the file was not refused; a tax id is stored only with books.set_tin or a W-9 (books.set_w9)", + if masked_count == 1 { "" } else { "s" }, + if masked_count == 1 { "was" } else { "were" }, + if lines.len() == 1 { "" } else { "s" }, + lines.join(", ") + ) + }); Ok(Json(ImportBankCsvOut { imported, count, source_attachment_id: p.source_attachment_id, source_linked: link_source, + masked_count, + masked: masked + .into_iter() + .map(|m| MaskedCellOut { + row: m.line, + column: m.column.to_string(), + numbers: m.numbers, + }) + .collect(), + masked_note, })) } } diff --git a/crates/ledger-mcp/src/types.rs b/crates/ledger-mcp/src/types.rs index 867199bc..64c5d3ec 100644 --- a/crates/ledger-mcp/src/types.rs +++ b/crates/ledger-mcp/src/types.rs @@ -1368,6 +1368,29 @@ pub struct ImportBankCsvOut { /// True when this call linked it to the account (false when it already /// was, or none was given). pub source_linked: bool, + /// How many descriptions held a number that reads as a tax id (nine + /// digits standing alone, an SSN's or an EIN's shape) and were kept + /// masked to its last four digits: a bank's description is not typed by + /// a person and often carries a nine-digit reference, so the file is + /// not refused for one (BS-partner-2). + pub masked_count: usize, + /// Which descriptions were masked, by the file's line. + pub masked: Vec, + /// What masking did, in words; present when `masked_count` is above + /// zero. + #[serde(skip_serializing_if = "Option::is_none")] + pub masked_note: Option, +} + +/// One description of a bank file that was kept masked. +#[derive(Debug, Serialize, JsonSchema)] +pub struct MaskedCellOut { + /// The file's line (the first line is 1). + pub row: u64, + /// The column: "Description". + pub column: String, + /// How many numbers in the cell were masked. + pub numbers: usize, } /// Parameters for `books.import_chart_csv`. No other argument is taken: a diff --git a/crates/ledger-store/src/audit.rs b/crates/ledger-store/src/audit.rs index 90f6757b..26270a11 100644 --- a/crates/ledger-store/src/audit.rs +++ b/crates/ledger-store/src/audit.rs @@ -119,6 +119,11 @@ pub const CODES: &[ledger_core::audit::CodeRow] = &[ severity: Severity::Warning, predicate: "two filed attachments, neither withdrawn, hold the same bytes", }, + ledger_core::audit::CodeRow { + code: "tax_id_in_journal", + severity: Severity::Warning, + predicate: "a journal line's text field holds a number that looks like a tax id (nine digits standing alone, an SSN's 3-2-4 or an EIN's 2-7)", + }, ledger_core::audit::CodeRow { code: "backup_stale", severity: Severity::Warning, @@ -144,6 +149,69 @@ fn found(code: &'static str, subject: Subject, message: String) -> Finding { } } +/// The journal fields that hold words someone wrote (never an id, a digest +/// or an amount): what [`Store::integrity_findings`] reads for a tax id. +const TEXT_KEYS: &[&str] = &[ + "description", + "memo", + "note", + "notes", + "reason", + "name", + "label", + "title", + "citation", + "decided_by", + "detail", + "detail_md", + "resolution", + "decision_md", + "body_md", + "subject", + "reference", + "customer_ref", + "vendor_ref", + "duplicate_reason", + "no_party_reason", + "payee", + "source", + "reimbursable_to", + "file_name", + "serial", + "tag", + "employee_name", + "display_name", + "address", + "contact", + "kept_at", + "approver", +]; + +/// Every text field of `v` named by [`TEXT_KEYS`], as (its key, its text), +/// at any depth; a list of texts under such a key counts each. +fn text_fields_in(v: &Value, out: &mut Vec<(String, String)>) { + match v { + Value::Object(m) => { + for (k, x) in m { + if TEXT_KEYS.contains(&k.as_str()) { + match x { + Value::String(s) => out.push((k.clone(), s.clone())), + Value::Array(a) => out.extend( + a.iter() + .filter_map(Value::as_str) + .map(|s| (k.clone(), s.to_string())), + ), + _ => {} + } + } + text_fields_in(x, out); + } + } + Value::Array(a) => a.iter().for_each(|x| text_fields_in(x, out)), + _ => {} + } +} + /// What the backups' standing says, one target at a time, for the audit /// (the server reads the standing; the store does not know the backups). #[derive(Clone, Debug)] @@ -436,6 +504,45 @@ impl Store { format!("attachments {ids} hold the same bytes ({sha})"), )); } + out.extend(self.tax_id_findings()); + out + } + + /// The journal lines whose text fields hold what looks like a tax id + /// (BS-partner-2): a line an earlier version took, or one a caller + /// other than the tools wrote. The books open and replay as they are + /// and the journal is never rewritten; the audit says where each one + /// is, by line and field, and never what the number is. + fn tax_id_findings(&self) -> Vec { + let rows: Vec<(u64, String, String)> = self + .conn + .prepare("SELECT seq, type, payload FROM events ORDER BY seq") + .and_then(|mut s| { + s.query_map([], |r| { + Ok((r.get::<_, i64>(0)? as u64, r.get(1)?, r.get(2)?)) + })? + .collect::, _>>() + }) + .unwrap_or_default(); + let mut out = Vec::new(); + for (seq, kind, payload) in rows { + let Ok(v) = serde_json::from_str::(&payload) else { + continue; + }; + let mut fields = Vec::new(); + text_fields_in(&v, &mut fields); + for (field, text) in fields { + if ledger_core::settings::holds_printed_tin(&text) { + out.push(found( + "tax_id_in_journal", + Subject::Named(format!("journal line {seq}")), + format!( + "journal line {seq} ({kind}) holds, in its `{field}`, a number that looks like a tax id. The journal is never rewritten and the books open as they are: correct what it describes going forward (reverse the entry and enter it again without the number), and keep the tax id only in the vault (books.set_tin or a W-9, books.set_w9)" + ), + )); + } + } + } out } diff --git a/crates/ledger-store/src/store.rs b/crates/ledger-store/src/store.rs index 0f7b1161..a2f20504 100644 --- a/crates/ledger-store/src/store.rs +++ b/crates/ledger-store/src/store.rs @@ -4755,6 +4755,10 @@ impl Store { bytes: &[u8], description: Option<&str>, ) -> Result<(u64, String, bool), StoreError> { + LedgerError::free_text("the file name", file_name)?; + if let Some(d) = description { + LedgerError::free_text("the description", d)?; + } self.attach(AttachRequest { line_type: "receipt.attached", category: "receipts", @@ -4795,6 +4799,10 @@ impl Store { bytes: &[u8], description: Option<&str>, ) -> Result<(u64, String, bool), StoreError> { + LedgerError::free_text("the file name", file_name)?; + if let Some(d) = description { + LedgerError::free_text("the description", d)?; + } self.attach(AttachRequest { line_type: "document.filed", category, @@ -5692,6 +5700,7 @@ impl Store { if reason.is_empty() { return Err(StoreError::ReasonRequired); } + LedgerError::free_text("the reason", reason)?; let (entry_id, withdrawn) = self.attachment_state(attachment_id)?; if withdrawn { return Err(StoreError::AttachmentWithdrawn(attachment_id)); @@ -5760,6 +5769,7 @@ impl Store { if reason.is_empty() { return Err(StoreError::ReasonRequired); } + LedgerError::free_text("the reason", reason)?; self.check_linkable(attachment_id)?; if let Some(sub) = self.attachment_links(attachment_id)?.first() { return Err(StoreError::AlreadyLinked(attachment_id, sub.describe())); @@ -5936,6 +5946,7 @@ impl Store { if reason.is_empty() { return Err(StoreError::ReasonRequired); } + LedgerError::free_text("the reason", reason)?; self.attachment_state(attachment_id)?; let linked = self .conn @@ -6065,6 +6076,7 @@ impl Store { if reason.is_empty() { return Err(StoreError::ReasonRequired); } + LedgerError::free_text("the reason", reason)?; if self.statement(attachment_id)?.is_none() { return Err(StoreError::InvalidStatement(format!( "attachment {attachment_id} records no statement" @@ -6215,6 +6227,7 @@ impl Store { if reason.is_empty() { return Err(StoreError::ReasonRequired); } + LedgerError::free_text("the reason", reason)?; let r = self .reconciliations(None)? .into_iter() diff --git a/crates/ledger-store/tests/audit.rs b/crates/ledger-store/tests/audit.rs index fb97f36b..23891d40 100644 --- a/crates/ledger-store/tests/audit.rs +++ b/crates/ledger-store/tests/audit.rs @@ -362,6 +362,43 @@ fn integrity_detects_each_seeded_defect() { drop(w); Store::open(&dir).unwrap().integrity_findings() } + "tax_id_in_journal" => { + // A line an earlier version took: its description holds an + // SSN's shape. The books open on it all the same, and the + // audit says where it is, never what. + let next = s.ledger().next_entry_id(); + drop(s); + let mut w = JournalWriter::open(&dir.join(JOURNAL_FILE)).unwrap(); + w.append( + "entry.created", + json!({"id": next, "date": "2026-03-01", "description": "paid 000-00-0000 in cash"}), + ) + .unwrap(); + drop(w); + let s = Store::open(&dir).expect("books holding such a line still open"); + s.verify().expect("and still verify"); + let found = s.integrity_findings(); + let f = found + .iter() + .find(|f| f.code == "tax_id_in_journal") + .expect("found"); + assert!(f.message.contains("`description`"), "{}", f.message); + assert!( + f.message.contains(&format!( + "journal line {}", + f.subject.describe().rsplit(' ').next().unwrap() + )), + "{}", + f.message + ); + assert!( + !f.message.contains("0000"), + "never the number: {}", + f.message + ); + assert!(f.message.contains("books.set_tin"), "{}", f.message); + found + } "access_log_damaged" => { std::fs::write( dir.join("access.jsonl"),