diff --git a/crates/ledger-cli/tests/documents.rs b/crates/ledger-cli/tests/documents.rs index dd733bf7..da024917 100644 --- a/crates/ledger-cli/tests/documents.rs +++ b/crates/ledger-cli/tests/documents.rs @@ -677,7 +677,7 @@ fn update_party_sets_and_clears_the_contact_block() { json!({"party": party.to_string(), "phone": "123-45-6789"}), ) .unwrap_err(); - assert!(why.contains("taxpayer"), "{why}"); + assert!(why.contains("tax id"), "{why}"); let why = m .try_call( "books.update_party", diff --git a/crates/ledger-cli/tests/spec_projects.rs b/crates/ledger-cli/tests/spec_projects.rs index a0b3f1cf..763f6c34 100644 --- a/crates/ledger-cli/tests/spec_projects.rs +++ b/crates/ledger-cli/tests/spec_projects.rs @@ -482,7 +482,7 @@ fn update_project_checks_every_field_before_writing() { ), ( json!({"project": "Harbor", "notes": "SSN 123-45-6789"}), - "TIN", + "tax id", ), ( json!({"project": "Nowhere", "status": "paused"}), diff --git a/crates/ledger-cli/tests/tin_in_text.rs b/crates/ledger-cli/tests/tin_in_text.rs new file mode 100644 index 00000000..bef43fd6 --- /dev/null +++ b/crates/ledger-cli/tests/tin_in_text.rs @@ -0,0 +1,279 @@ +//! No tax id in a tool's text, through the real server as an agent reaches it +//! (BS-partner-2, WB-partner-15; the owner's choice of 2026-11-21). +//! +//! The law: a string that looks like a tax id (nine digits standing alone, an +//! SSN's 3-2-4, an EIN's 2-7) is refused before any write tool runs, in words +//! that name the field and never the number, and the journal is byte for byte +//! what it was; an invoice number, a phone number and a reference of ten +//! digits or more are no tax id; a bank file's descriptions are kept with such +//! a number masked to its last four digits and the answer says so; a chart file +//! with one is refused, naming its row and column. The fake ids are +//! `000-00-0000` and `00-0000000`. + +use common::{Books, Wire, answer_of}; +use serde_json::json; + +mod common; + +const SSN: &str = "000-00-0000"; +const EIN: &str = "00-0000000"; + +fn setup(w: &mut Wire) { + for (code, name, kind) in [("1000", "Bank", "asset"), ("6000", "Supplies", "expense")] { + answer_of(&w.call( + "books.add_account", + json!({"code": code, "name": name, "account_type": kind}), + )) + .unwrap(); + } +} + +/// Free text with a tax id in it is refused by every tool that keeps text, +/// before it runs: the journal does not change by a byte. +#[test] +fn a_tax_id_in_a_tools_text_is_refused_and_nothing_is_written() { + let books = Books::new("tin-text-refused"); + let mut w = books.session("test"); + setup(&mut w); + let before = books.journal_raw(); + for (tool, args, field) in [ + ( + "books.add_class", + json!({"name": format!("Rondo {SSN}")}), + "the name of books.add_class", + ), + ( + "books.add_project", + json!({"name": "Harbor", "notes": format!("ein {EIN}")}), + "the notes of books.add_project", + ), + ( + "books.draft_entry", + json!({"date": "2026-03-01", "description": format!("paid {SSN}"), "no_party_reason": "test"}), + "the description of books.draft_entry", + ), + ( + "books.draft_entry", + json!({"date": "2026-03-01", "description": "ok", "no_party_reason": format!("own account {EIN}")}), + "the no_party_reason of books.draft_entry", + ), + // A party's own fields are strict: any run of nine digits. + ( + "books.add_customer", + json!({"name": "Acme 123456789"}), + "the name of books.add_customer", + ), + ( + "books.add_party", + json!({"name": format!("Pat {SSN}"), "roles": ["contractor"]}), + "the name of books.add_party", + ), + ( + "books.set_setting", + json!({"changes": [{"key": "company.name", "value": "Acme"}], "note": format!("see {SSN}")}), + "the note of books.set_setting", + ), + ] { + let why = answer_of(&w.call(tool, args)).unwrap_err(); + assert!( + why.starts_with(&format!("{field} looks like it holds a tax id")), + "{tool}: {why}" + ); + assert!( + why.contains("books.set_tin") && why.contains("W-9"), + "{why}" + ); + assert!( + !why.contains("0000") && !why.contains("123456789"), + "never the number: {why}" + ); + assert_eq!( + books.journal_raw(), + before, + "{tool}: a refusal writes nothing" + ); + } +} + +/// What is no tax id is kept: an invoice number, a phone number, a long +/// reference, an amount and a date. +#[test] +fn a_reference_is_no_tax_id() { + let books = Books::new("tin-text-kept"); + let mut w = books.session("test"); + setup(&mut w); + let out = answer_of(&w.call( + "books.draft_entry", + json!({"date": "2026-03-01", + "description": "inv 2026-11-0042, call 801-555-0142, ref 1234567890, $1,234,567.89", + "no_party_reason": "test"}), + )) + .unwrap(); + assert!(out["entry_id"].is_u64(), "{out}"); +} + +/// A reference field (an account code, an instrument's label) keeps a bare +/// nine digits and refuses a printed tax id; free text refuses both. +#[test] +fn a_reference_field_keeps_nine_digits_and_refuses_a_printed_tax_id() { + let books = Books::new("tin-reference-field"); + let mut w = books.session("test"); + setup(&mut w); + let ok = answer_of(&w.call( + "books.add_account", + json!({"code": "123456789", "name": "Nine", "account_type": "asset"}), + )) + .unwrap(); + assert!(ok["account_id"].is_u64(), "{ok}"); + answer_of(&w.call( + "books.add_instrument", + json!({"label": "Card 000000000", "kind": "business_card", "account": "1000"}), + )) + .unwrap(); + let before = books.journal_raw(); + for (tool, args, field) in [ + ( + "books.add_account", + json!({"code": SSN, "name": "Odd", "account_type": "asset"}), + "the code of books.add_account", + ), + ( + "books.add_instrument", + json!({"label": format!("Card {EIN}"), "kind": "business_card", "account": "1000"}), + "the label of books.add_instrument", + ), + ( + "books.add_class", + json!({"name": "123456789"}), + "the name of books.add_class", + ), + ] { + let why = answer_of(&w.call(tool, args)).unwrap_err(); + assert!( + why.starts_with(&format!("{field} looks like it holds a tax id")), + "{tool}: {why}" + ); + assert_eq!(books.journal_raw(), before, "{tool}: nothing was written"); + } +} + +/// A rule keyed on a bank's nine-digit reference matches the bank's own +/// words, and the description that is kept is the masked one. +#[test] +fn a_bank_rule_keyed_on_a_nine_digit_reference_still_matches() { + let books = Books::new("tin-bank-rule"); + let mut w = books.session("test"); + setup(&mut w); + answer_of(&w.call( + "books.add_account", + json!({"code": "6100", "name": "Payroll costs", "account_type": "expense"}), + )) + .unwrap(); + let csv = "Date,Description,Amount\n2026-01-02,ACH 000000000 PAYROLL,-12.50\n2026-01-03,CHECK 1234567890,-3.25\n"; + let up = w.upload(csv.as_bytes(), "bank.csv", "text/csv", "import"); + let out = answer_of(&w.call( + "books.import_bank_csv", + json!({"upload_id": up, "bank_account_code": "1000", "default_offset_code": "6000", + "rules": {"000000000": "6100"}}), + )) + .unwrap(); + let imported = out["imported"].as_array().unwrap(); + assert_eq!(imported[0]["offset_account"], "6100", "{out}"); + assert_eq!(imported[1]["offset_account"], "6000", "{out}"); + assert_eq!( + imported[0]["description"], + "ACH \u{2022}\u{2022}\u{2022}\u{2022}\u{2022}0000 PAYROLL" + ); + let journal = String::from_utf8(books.journal_raw()).unwrap(); + assert!( + !journal.contains("ACH 000000000"), + "the journal holds the masked description only" + ); +} + +/// A bank file is kept whole with a nine-digit reference masked to its last +/// four digits; the answer says how many and where; the journal never holds +/// the number. +#[test] +fn a_bank_file_is_masked_not_refused() { + let books = Books::new("tin-bank-masked"); + let mut w = books.session("test"); + setup(&mut w); + let csv = format!( + "Date,Description,Amount\n2026-01-02,ACH {SSN} payroll,-12.50\n2026-01-03,CHECK 1234567890,-3.25\n2026-01-04,\"WIRE 000000000 and {EIN}\",-40.00\n" + ); + let up = w.upload(csv.as_bytes(), "bank.csv", "text/csv", "import"); + let out = answer_of(&w.call( + "books.import_bank_csv", + json!({"upload_id": up, "bank_account_code": "1000", "default_offset_code": "6000"}), + )) + .unwrap(); + assert_eq!(out["count"], 3, "{out}"); + assert_eq!(out["masked_count"], 3, "{out}"); + assert_eq!( + out["masked"], + json!([ + {"row": 2, "column": "Description", "numbers": 1}, + {"row": 4, "column": "Description", "numbers": 2}, + ]) + ); + let note = out["masked_note"].as_str().unwrap(); + assert!( + note.starts_with("3 values in the Description column read as a tax id"), + "{note}" + ); + assert!( + note.contains("lines 2, 4") && note.contains("books.set_tin"), + "{note}" + ); + let descriptions: Vec<&str> = out["imported"] + .as_array() + .unwrap() + .iter() + .map(|t| t["description"].as_str().unwrap()) + .collect(); + assert_eq!( + descriptions, + [ + "ACH \u{2022}\u{2022}\u{2022}-\u{2022}\u{2022}-0000 payroll", + "CHECK 1234567890", + "WIRE \u{2022}\u{2022}\u{2022}\u{2022}\u{2022}0000 and \u{2022}\u{2022}-\u{2022}\u{2022}\u{2022}0000", + ] + ); + let journal = String::from_utf8(books.journal_raw()).unwrap(); + for needle in [SSN, EIN, "000000000"] { + for line in journal.lines().filter(|l| l.contains(needle)) { + let kind = serde_json::from_str::(line).unwrap()["type"].clone(); + // The line that makes the books holds zeros of its own (a hash). + assert_eq!( + kind, "store.created", + "the journal holds a tax id in a {kind} line" + ); + } + } + assert!( + journal.contains("Bank import \u{2014} ACH \u{2022}"), + "the drafts are kept masked" + ); +} + +/// A chart file is typed by a person: a cell that looks like a tax id +/// refuses it whole, naming its row and column, and nothing is imported. +#[test] +fn a_chart_file_with_a_tax_id_is_refused_naming_its_row_and_column() { + let books = Books::new("tin-chart-refused"); + let mut w = books.session("test"); + let csv = + format!("code,name,type,parent_code\n1000,Cash,asset,\n1010,Payroll {SSN},asset,1000\n"); + let up = w.upload(csv.as_bytes(), "chart.csv", "text/csv", "import"); + let before = books.journal_raw(); + let why = answer_of(&w.call("books.import_chart_csv", json!({"upload_id": up}))).unwrap_err(); + assert!( + why.starts_with("the name cell of row 3 looks like it holds a tax id"), + "{why}" + ); + assert!(!why.contains("0000"), "never the number: {why}"); + assert_eq!(books.journal_raw(), before, "nothing was imported"); + let chart = answer_of(&w.call("books.chart", json!({}))).unwrap(); + assert!(!chart.to_string().contains("Payroll"), "{chart}"); +} diff --git a/crates/ledger-core/src/arap.rs b/crates/ledger-core/src/arap.rs index 48ce38d2..3c7674dd 100644 --- a/crates/ledger-core/src/arap.rs +++ b/crates/ledger-core/src/arap.rs @@ -399,24 +399,32 @@ pub const MAX_REFERENCE_CHARS: usize = 200; impl PaymentDetails { /// The payment entry's description: `base`, then the reference when - /// there is one (`base (ref R)`). + /// there is one (`base (ref R)`), with a run of nine digits in it masked + /// to its last four: the reference is kept whole in the payment's own + /// record, and an entry's description is free text, which holds no + /// number that reads as a tax id (WB-partner-15). pub fn description(&self, base: &str) -> String { match self.reference.as_deref().map(str::trim) { - Some(r) if !r.is_empty() => format!("{base} (ref {r})"), + Some(r) if !r.is_empty() => { + format!("{base} (ref {})", crate::settings::mask_printed_tins(r)) + } _ => base.to_string(), } } /// Refuse a reference that isn't one line of at most - /// [`MAX_REFERENCE_CHARS`] characters. A blank one is none. (A bank - /// trace number is fifteen digits, so no nine-digit scan here.) + /// [`MAX_REFERENCE_CHARS`] characters, or one that looks like a tax id's + /// printed SSN or EIN (a bare nine digits is a check or confirmation + /// number: a reference's reading, WB-partner-15; not in a replay, + /// BS-entry-4). A blank one is none. pub fn check(&self) -> Result<(), LedgerError> { - if let Some(r) = &self.reference - && (r.contains(['\n', '\r']) || r.chars().count() > MAX_REFERENCE_CHARS) - { - return Err(LedgerError::InvalidPayment(format!( - "a payment's reference is one line of at most {MAX_REFERENCE_CHARS} characters" - ))); + if let Some(r) = &self.reference { + if r.contains(['\n', '\r']) || r.chars().count() > MAX_REFERENCE_CHARS { + return Err(LedgerError::InvalidPayment(format!( + "a payment's reference is one line of at most {MAX_REFERENCE_CHARS} characters" + ))); + } + LedgerError::reference_text("the payment reference", r)?; } Ok(()) } @@ -1253,6 +1261,65 @@ impl Bill { } } +/// A new document's free text may not look like a tax id (BS-partner-2): +/// the customer's or the vendor's own reference, the memo, and why a +/// repeated vendor invoice number is entered anyway. For new documents; +/// replay restores them as journaled (BS-entry-4). +pub fn check_document_text( + reference: Option<&str>, + memo: Option<&str>, + duplicate_reason: Option<&str>, +) -> Result<(), LedgerError> { + for (field, text) in [ + ("the memo", memo), + ("the duplicate reason", duplicate_reason), + ] { + if let Some(t) = text { + LedgerError::free_text(field, t)?; + } + } + if let Some(t) = reference { + LedgerError::reference_text("the reference", t)?; + } + Ok(()) +} + +/// The party details a new invoice prints: the customer's (a party's +/// fields: strict, no run of nine digits, [`crate::parties::check_text`]) +/// and the seller's (the company's own, free text: no tax id's shape). +pub fn check_snapshots( + bill_to: Option<&PartySnapshot>, + seller: Option<&PartySnapshot>, +) -> Result<(), LedgerError> { + let fields = |s: &'_ PartySnapshot| -> [(&'static str, Option); 8] { + [ + ("the bill-to name", Some(s.name.clone())), + ("the bill-to address", s.address.clone()), + ("the bill-to email", s.email.clone()), + ("the bill-to phone", s.phone.clone()), + ("the bill-to contact", s.contact.clone()), + ("the billing address", s.billing_address.clone()), + ("the shipping address", s.shipping_address.clone()), + ("the billing email", s.billing_email.clone()), + ] + }; + if let Some(s) = bill_to { + for (field, text) in fields(s) { + if let Some(t) = text { + crate::parties::check_text(field, &t).map_err(LedgerError::InvalidParty)?; + } + } + } + if let Some(s) = seller { + for (field, text) in fields(s) { + if let Some(t) = text { + LedgerError::free_text(&field.replace("bill-to", "seller"), &t)?; + } + } + } + Ok(()) +} + /// Validate document lines: at least one, all positive amounts, each in a /// journal line's range, and a quantity and unit price that multiply to /// the amount exactly (plan P4b S4.1). For new documents; replay restores @@ -1262,6 +1329,7 @@ pub fn validate_lines(lines: &[DocumentLine]) -> Result<(), LedgerError> { return Err(LedgerError::EmptyDocumentLines); } for line in lines { + LedgerError::free_text("a line's description", &line.description)?; if line.amount <= Decimal::ZERO { return Err(LedgerError::InvalidDocumentLineAmount(line.amount)); } diff --git a/crates/ledger-core/src/error.rs b/crates/ledger-core/src/error.rs index ab09ed05..bc2e5898 100644 --- a/crates/ledger-core/src/error.rs +++ b/crates/ledger-core/src/error.rs @@ -367,6 +367,13 @@ pub enum LedgerError { )] AccountNameHoldsTin, + /// Free text (a memo, a note, a reason, a description, a tag) that + /// looks like it holds a tax id: nine digits standing alone, or an + /// SSN's 3-2-4 or an EIN's 2-7 grouping (BS-partner-2). The words name + /// the field and where a tax id goes, never the number. + #[error("{0}")] + FreeTextHoldsTin(String), + /// A new account name (a new account's, or a rename's) that isn't one /// line of text within the bound ([`crate::account::MAX_ACCOUNT_NAME`] /// characters): every report, export and the IIF print it on one line. @@ -993,6 +1000,23 @@ pub enum LedgerError { ApprovalNeedsDraft(String), } +impl LedgerError { + /// Free text a command may keep: it must not look like a tax id + /// ([`crate::settings::check_free_text`]; never refused in a replay). + /// `field` is how the refusal names it ("the memo", "the entry + /// description"). + pub fn free_text(field: &str, text: &str) -> Result<(), LedgerError> { + crate::settings::check_free_text(field, text).map_err(LedgerError::FreeTextHoldsTin) + } + + /// [`Self::free_text`] for a reference (a tag, a serial, a payment's or + /// an invoice's reference, an account code, a file name): a bare nine + /// digits is allowed ([`crate::settings::check_reference_text`]). + pub fn reference_text(field: &str, text: &str) -> Result<(), LedgerError> { + crate::settings::check_reference_text(field, text).map_err(LedgerError::FreeTextHoldsTin) + } +} + /// The refusal [`LedgerError::TaxCategoryRequired`] gives: what to pass, /// and where the categories are listed. fn tax_category_required_text(account: &str, clearing: bool) -> String { diff --git a/crates/ledger-core/src/evidence.rs b/crates/ledger-core/src/evidence.rs index d3bfacef..31551c78 100644 --- a/crates/ledger-core/src/evidence.rs +++ b/crates/ledger-core/src/evidence.rs @@ -74,6 +74,19 @@ impl AnnotationFields { self.category = trim(self.category); self.source = trim(self.source); self.reimbursable_to = trim(self.reimbursable_to); + // Who, what and where in words: no tax id among them (BS-partner-2; + // not in a replay, which keeps the journal as written). + for (field, text) in [ + ("the payee", &self.payee), + ("the payment method", &self.instrument), + ("the category", &self.category), + ("the source", &self.source), + ("who is to be reimbursed", &self.reimbursable_to), + ] { + if let Some(t) = text { + LedgerError::free_text(field, t)?; + } + } if self.receipt_number == Some(0) { return Err(LedgerError::InvalidEvidence( "a receipt number is positive".into(), @@ -111,6 +124,9 @@ impl Annotation { .note .map(|n| n.trim().to_string()) .filter(|n| !n.is_empty()); + if let Some(n) = &self.note { + LedgerError::free_text("the note", n)?; + } if self.fields.is_empty() && self.note.is_none() { return Err(LedgerError::InvalidEvidence( "an annotation records at least one field or a note".into(), diff --git a/crates/ledger-core/src/instruments.rs b/crates/ledger-core/src/instruments.rs index 5056e7a5..938b9b03 100644 --- a/crates/ledger-core/src/instruments.rs +++ b/crates/ledger-core/src/instruments.rs @@ -127,10 +127,11 @@ pub struct Instrument { pub account: AccountId, } -/// Check a label: one line, at most `MAX_TEXT` characters, no full TIN -/// (INVARIANT 1, all but uniqueness). Returns it trimmed. +/// Check a label: one line, at most `MAX_TEXT` characters, no printed SSN or +/// EIN (INVARIANT 1, all but uniqueness; a label is a reference, so a bare +/// nine digits is allowed, WB-partner-15). Returns it trimmed. pub fn check_label(label: &str) -> Result { - crate::settings::line_text("label", label, crate::settings::MAX_TEXT) + crate::settings::reference_line_text("label", label, crate::settings::MAX_TEXT) } /// Check a last four (INVARIANT 2). diff --git a/crates/ledger-core/src/ledger.rs b/crates/ledger-core/src/ledger.rs index eae6a1b4..7fe12abd 100644 --- a/crates/ledger-core/src/ledger.rs +++ b/crates/ledger-core/src/ledger.rs @@ -1024,6 +1024,7 @@ impl Ledger { if code.trim().is_empty() { return Err(LedgerError::EmptyAccountCode); } + LedgerError::reference_text("the account code", code)?; let name = name.trim(); if name.is_empty() { return Err(LedgerError::EmptyAccountName); @@ -1226,14 +1227,8 @@ impl Ledger { /// allowed but no other control character, and no full TIN ( /// BS-partner-2). Returns it trimmed. pub fn check_rename_reason(reason: &str) -> Result { - let r = crate::settings::long_text("reason", reason, crate::settings::MAX_LONG_TEXT) - .map_err(LedgerError::InvalidRenameReason)?; - if crate::parties::has_full_tin(&r) { - return Err(LedgerError::InvalidRenameReason( - "reason holds nine digits in a row, which read as a full SSN or EIN: write only the last four".into(), - )); - } - Ok(r) + crate::settings::long_text("reason", reason, crate::settings::MAX_LONG_TEXT) + .map_err(LedgerError::InvalidRenameReason) } /// Whether `policy.require_tax_category` lets an account be created @@ -1300,6 +1295,7 @@ impl Ledger { if code.trim().is_empty() { return Err(LedgerError::EmptyAccountCode); } + LedgerError::reference_text("the account code", code)?; if self.chart.find_by_code(code).is_some() { return Err(LedgerError::DuplicateAccountCode(code.to_string())); } @@ -1575,6 +1571,9 @@ impl Ledger { /// - NEVER create a draft there /// BECAUSE a closed period takes no new entries. /// 2. Otherwise: SHOULD return a fresh id, one past the last. + /// 3. IF the description looks like it holds a tax id (nine digits + /// standing alone, an SSN's 3-2-4 or an EIN's 2-7: BS-partner-2): + /// SHOULD refuse (FreeTextHoldsTin). /// ``` pub fn try_create_entry( &mut self, @@ -1582,6 +1581,7 @@ impl Ledger { description: &str, ) -> Result { crate::calendar::check(date)?; + LedgerError::free_text("the entry description", description)?; if let Some(pid) = self.closed_period_containing(date) { return Err(LedgerError::ClosedPeriod(pid, date.to_string())); } @@ -2086,7 +2086,7 @@ impl Ledger { state: crate::DraftState, ) -> Result<(), LedgerError> { if let crate::DraftState::AwaitingEvidence { note } = &state { - crate::parties::check_text("the note", note).map_err(LedgerError::InvalidDraft)?; + crate::parties::check_note("the note", note).map_err(LedgerError::InvalidDraft)?; } self.draft_mut(entry)?.set_draft_state(state); Ok(()) @@ -2135,7 +2135,7 @@ impl Ledger { "a discarded draft needs a reason".to_string(), )); } - crate::parties::check_text("the reason", reason).map_err(LedgerError::InvalidDraft)?; + crate::parties::check_note("the reason", reason).map_err(LedgerError::InvalidDraft)?; self.replay_discard_draft(entry) } @@ -2505,6 +2505,7 @@ impl Ledger { description: &str, ) -> Result { self.check_reversal(entry, date)?; + LedgerError::free_text("the reversal's description", description)?; let original = self .entries .get(&entry) @@ -2606,6 +2607,11 @@ impl Ledger { if new.description.trim().is_empty() { return Err(LedgerError::EmptyAssetDescription); } + // New work only: a journaled description replays as written + // (BS-entry-4). + if strict { + LedgerError::free_text("the asset description", &new.description)?; + } if new.cost.amount <= Decimal::ZERO { return Err(LedgerError::InvalidAssetCost(new.cost.amount)); } @@ -2767,6 +2773,7 @@ impl Ledger { tag: tag.to_string(), why, })?; + LedgerError::reference_text("the asset tag", tag)?; match self.asset_tags.get(&assets::tag_key(tag)) { Some(&holder) if Some(holder) != id => Err(LedgerError::AssetTagTaken { tag: tag.to_string(), @@ -2803,6 +2810,7 @@ impl Ledger { } if let Some(s) = serial { assets::check_serial(s).map_err(LedgerError::InvalidSerial)?; + LedgerError::reference_text("the serial number", s)?; } Ok(()) } @@ -3012,6 +3020,7 @@ impl Ledger { if description.trim().is_empty() { return Err(LedgerError::EmptyAssetDescription); } + LedgerError::free_text("the asset description", description)?; Ok(()) } @@ -3581,6 +3590,7 @@ impl Ledger { end: NaiveDate, ) -> Result { periods::validate_period_range(start, end)?; + LedgerError::free_text("the period name", name)?; let nested = |a: (NaiveDate, NaiveDate), b: (NaiveDate, NaiveDate)| { (a.0 >= b.0 && a.1 <= b.1) || (b.0 >= a.0 && b.1 <= a.1) }; @@ -5596,7 +5606,7 @@ impl Ledger { "say why the entry has no counterparty".into(), )); } - crate::parties::check_text("reason", reason).map_err(LedgerError::InvalidParty) + crate::parties::check_note("the reason", reason).map_err(LedgerError::InvalidParty) } /// Why an entry has no counterparty, when it was marked so. @@ -5892,6 +5902,8 @@ impl Ledger { } arap::validate_lines(&lines)?; arap::validate_due_date(date, due_date)?; + arap::check_document_text(fields.customer_ref.as_deref(), fields.memo.as_deref(), None)?; + arap::check_snapshots(fields.bill_to.as_ref(), fields.seller.as_ref())?; if let Some(number) = &fields.number && self .invoices @@ -6029,6 +6041,11 @@ impl Ledger { if let Some(received_on) = fields.received_on { crate::calendar::check(received_on)?; } + arap::check_document_text( + fields.vendor_ref.as_deref(), + fields.memo.as_deref(), + fields.duplicate_reason.as_deref(), + )?; if let Some(vendor_ref) = fields.vendor_ref.as_deref() { self.check_vendor_ref(vendor_id, vendor_ref, fields.duplicate_reason.as_deref())?; } @@ -6203,11 +6220,11 @@ impl Ledger { crate::parties::check_text("a recipient", to).map_err(LedgerError::InvalidSend)?; } if let Some(reference) = &sent.reference { - crate::parties::check_text("the reference", reference) + crate::parties::check_reference_note("the reference", reference) .map_err(LedgerError::InvalidSend)?; } if let Some(note) = &sent.note { - crate::parties::check_text("the note", note).map_err(LedgerError::InvalidSend)?; + crate::parties::check_note("the note", note).map_err(LedgerError::InvalidSend)?; } self.invoices .get_mut(&invoice) @@ -6768,6 +6785,9 @@ impl Ledger { arap::MAX_REFERENCE_CHARS, )); } + if let Some(reason) = &app.discount_reason { + LedgerError::free_text("the discount reason", reason)?; + } if app.discount > Decimal::ZERO { self.check_discount(app, kind, total, doc_date, params.date)?; } @@ -7262,6 +7282,7 @@ impl Ledger { arap::MAX_REFERENCE_CHARS ))); } + LedgerError::free_text("the reason", reason)?; if amount <= Decimal::ZERO { return Err(LedgerError::InvalidWriteOff(format!( "a write-off's amount must be above zero, got {amount}" @@ -7373,6 +7394,7 @@ impl Ledger { arap::MAX_REFERENCE_CHARS ))); } + LedgerError::free_text("the reason", reason)?; let (_, _, origin, _) = self.doc_header(doc)?; let chain = self.reversal_chain(origin); let target = *chain.last().unwrap_or(&origin); @@ -8732,7 +8754,7 @@ impl Ledger { &mut self, annotation: crate::evidence::Annotation, ) -> Result<(), LedgerError> { - self.annotate_attachment(annotation) + crate::parties::replaying(|| self.annotate_attachment(annotation)) } /// The entries `entry` records settling (`entry.settles`, plan P6). diff --git a/crates/ledger-core/src/parties.rs b/crates/ledger-core/src/parties.rs index 194019cc..b1316efd 100644 --- a/crates/ledger-core/src/parties.rs +++ b/crates/ledger-core/src/parties.rs @@ -416,7 +416,7 @@ fn tin_separator(c: char) -> bool { /// right-to-left marks and the other directional formatting characters, /// the word joiner, the byte-order mark, the variation selectors, the tags /// and the fillers. None is ASCII. -fn tin_invisible(c: char) -> bool { +pub(crate) fn tin_invisible(c: char) -> bool { matches!( c, '\u{AD}' @@ -717,6 +717,34 @@ pub fn check_text(field: &str, text: &str) -> Result<(), String> { Ok(()) } +/// Check a free text field: no tax id's shape (a nine-digit number standing +/// alone, an SSN's 3-2-4, an EIN's 2-7: [`crate::settings::check_free_text`]), +/// at most 500 characters, no control characters except newline. For a +/// memo, a note or a reason; a party's own fields keep the strict +/// [`check_text`] (BS-partner-2; the owner's choice, 2026-11-21). +pub fn check_note(field: &str, text: &str) -> Result<(), String> { + crate::settings::check_free_text(field, text)?; + check_note_form(field, text) +} + +/// [`check_note`] for a reference (a payment's or a send's reference, a +/// file's location): only the grouped shapes are refused, a bare nine +/// digits is allowed ([`crate::settings::check_reference_text`]). +pub fn check_reference_note(field: &str, text: &str) -> Result<(), String> { + crate::settings::check_reference_text(field, text)?; + check_note_form(field, text) +} + +fn check_note_form(field: &str, text: &str) -> Result<(), String> { + if text.chars().count() > 500 { + return Err(format!("{field} is at most 500 characters")); + } + if text.chars().any(|c| c.is_control() && c != '\n') { + return Err(format!("{field} can't contain control characters")); + } + Ok(()) +} + /// Check an email address: one line of party text ([`check_text`], which /// refuses a full TIN) in a plain address shape, one `@` and no spaces. Not /// an RFC grammar test: the books only print it, they never send (A-4). @@ -746,12 +774,14 @@ impl W9Facts { ("entity_type", Some(self.entity_type.as_str())), ("exempt_payee_code", self.exempt_payee_code.as_deref()), ("fatca_code", self.fatca_code.as_deref()), - ("kept_at", Some(self.kept_at.as_str())), ] { if let Some(t) = t { check_text(f, t)?; } } + // Where the paper is kept is a reference (a binder, a portal, a + // file name): a bare nine digits is allowed (WB-partner-15). + check_reference_note("kept_at", &self.kept_at)?; if let Some(h) = &self.vault_record && (h.len() != 64 || !h.chars().all(|c| c.is_ascii_hexdigit())) { @@ -770,7 +800,7 @@ impl W4Facts { if self.kept_at.trim().is_empty() { return Err("say where the W-4 itself is kept".into()); } - check_text("kept_at", &self.kept_at) + check_reference_note("kept_at", &self.kept_at) } } diff --git a/crates/ledger-core/src/payroll.rs b/crates/ledger-core/src/payroll.rs index 2da38aea..a1dd3154 100644 --- a/crates/ledger-core/src/payroll.rs +++ b/crates/ledger-core/src/payroll.rs @@ -109,6 +109,7 @@ pub fn validate_payroll_lines(lines: &[PayrollLine]) -> Result<(), LedgerError> return Err(LedgerError::EmptyPayroll); } for line in lines { + LedgerError::free_text("the employee name", &line.employee_name)?; for amount in [ line.gross_pay, line.federal_withholding, diff --git a/crates/ledger-core/src/schedules.rs b/crates/ledger-core/src/schedules.rs index 93c6becb..3563a14f 100644 --- a/crates/ledger-core/src/schedules.rs +++ b/crates/ledger-core/src/schedules.rs @@ -508,6 +508,7 @@ pub fn validate_schedule_under( chart: &ChartOfAccounts, ) -> Result<(), LedgerError> { validate_schedule_shape(new, chart)?; + LedgerError::free_text("the schedule's description", &new.description)?; crate::calendar::check(new.start)?; let past_the_calendar = || { Err(LedgerError::InvalidSchedule(format!( @@ -773,6 +774,7 @@ pub fn validate_recurring(new: &NewRecurring, chart: &ChartOfAccounts) -> Result return Err(LedgerError::AmountOutOfRange); } validate_recurring_journaled(new, chart)?; + LedgerError::free_text("the recurring entry's description", &new.description)?; crate::calendar::check(new.start)?; if let Some(end) = new.end { crate::calendar::check(end)?; diff --git a/crates/ledger-core/src/settings.rs b/crates/ledger-core/src/settings.rs index b7cb089e..30bbc6bf 100644 --- a/crates/ledger-core/src/settings.rs +++ b/crates/ledger-core/src/settings.rs @@ -713,10 +713,50 @@ pub fn decimal(s: &str) -> Option { /// Whether `text` holds a number that reads as a full TIN (INVARIANT 4): /// nine digits standing alone (no digit right before or after), bare or /// printed the way an SSN (3-2-4) or an EIN (2-7) is, the groups joined by -/// a hyphen or any other dash, a dot, or a space (or a dash with spaces -/// around it); full-width digits count as digits. +/// a hyphen or any other dash, or a space (or a dash with spaces around +/// it), whatever Unicode form the dash, space or digit takes (full-width, +/// Arabic-Indic, no-break space, en space, a line break, ...), with +/// zero-width and soft-hyphen characters not counted. A dot joins an SSN's +/// groups only when it joins both (`000.00.0000`), never an EIN's, so a +/// coordinate (`47.6062095`) is no tax id. +/// +/// ```text +/// GOAL: the one test free text meets before it is kept: it refuses what +/// looks like a tax id and nothing else. +/// SOURCE: BS-partner-2 (no full TIN in the books); wanderbooks' CHOICE on +/// it (the owner, 2026-11-21: shapes on free text, strict on party +/// fields, masking on bank imports; a reference field allows a +/// bare nine digits, decided by the lead the same day within that +/// choice), WB-partner-15. +/// INVARIANTS: +/// 1. Nine digits standing alone, an SSN's 3-2-4 and an EIN's 2-7 are +/// found, with any dash or space (Unicode forms and line breaks +/// too) between the groups, and a dot between all of an SSN's. +/// 2. An invoice number (`2026-11-0042`), a phone number, an order +/// number, a reference of ten digits or more, an amount with comma +/// groups, a date, a date followed by a reference +/// (`2026-11-21 0001234`) and a decimal (`47.6062095`) are not found. +/// 3. A group that starts or ends inside a longer run of digits and +/// dashes (a digit and a dash before its first digit, or a dash and a +/// digit after its last) is part of that run, not a tax id. +/// 4. During a replay ([`crate::parties::replaying`]) the Unicode forms, +/// line breaks and invisible characters are not read, so a line an +/// earlier version took still replays (BS-entry-4). +/// SCENARIOS: +/// 1. IF a memo says `paid 000-00-0000`: SHOULD be found. +/// 2. IF it says `inv 2026-11-0042`: SHOULD NOT be. +/// 3. IF it says `at 47.6062095`: SHOULD NOT be. +/// ``` pub fn holds_printed_tin(text: &str) -> bool { - printed_tin(text, false) + !printed_tin_spans(text, Reading::Free).1.is_empty() +} + +/// [`holds_printed_tin`] for a reference (an asset tag, a serial number, an +/// invoice or bill number, a payment reference, an account code, a file +/// name): a bare run of nine digits is a legitimate number there, so only +/// the printed SSN (3-2-4) and EIN (2-7) forms count (WB-partner-15). +pub fn holds_printed_tin_in_reference(text: &str) -> bool { + !printed_tin_spans(text, Reading::Reference).1.is_empty() } /// [`holds_printed_tin`] for a web address: the printed SSN (3-2-4) and @@ -725,44 +765,154 @@ pub fn holds_printed_tin(text: &str) -> bool { /// id in a path or query (an app store listing's `id284882215`), not a /// TIN someone wrote down (BS-partner-2). pub fn holds_printed_tin_in_link(text: &str) -> bool { - printed_tin(text, true) + !printed_tin_spans(text, Reading::Link).1.is_empty() } -/// [`holds_printed_tin`], with a link's bare runs let through when `link`. -fn printed_tin(text: &str, link: bool) -> bool { - // Full-width digits read as the digits they are. - let c: Vec = text - .chars() - .map(|ch| match ch { - '\u{ff10}'..='\u{ff19}' => char::from_digit(ch as u32 - 0xff10, 10).unwrap_or(ch), - _ => ch, - }) +/// `text` with every number [`holds_printed_tin`] finds masked down to its +/// last four digits: every other digit becomes `•`, the separators stay +/// (`•••-••-0000`), the form the books show a TIN in everywhere else. For +/// text that is not typed by a person and must be kept (a bank's +/// description of a transaction, a line the program composes from text the +/// books already hold), never for a refusal's words. +pub fn mask_printed_tins(text: &str) -> std::borrow::Cow<'_, str> { + mask_spans(text, Reading::Free) +} + +/// [`mask_printed_tins`] for a reference ([`holds_printed_tin_in_reference`]): +/// a bare run of nine digits stays. +pub fn mask_printed_tins_in_reference(text: &str) -> std::borrow::Cow<'_, str> { + mask_spans(text, Reading::Reference) +} + +fn mask_spans(text: &str, reading: Reading) -> std::borrow::Cow<'_, str> { + let (mut chars, spans) = printed_tin_spans(text, reading); + if spans.is_empty() { + return std::borrow::Cow::Borrowed(text); + } + for (from, to) in spans { + let digits: Vec = (from..to).filter(|&i| chars[i].is_numeric()).collect(); + let keep = digits.len().saturating_sub(4); + for &i in &digits[..keep] { + chars[i] = '\u{2022}'; + } + } + std::borrow::Cow::Owned(chars.into_iter().collect()) +} + +/// How many numbers [`holds_printed_tin`] finds in `text`. +pub fn count_printed_tins(text: &str) -> usize { + printed_tin_spans(text, Reading::Free).1.len() +} + +/// What [`printed_tin_spans`] looks for. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Reading { + /// Free text: nine digits alone, an SSN's 3-2-4, an EIN's 2-7. + Free, + /// A reference: the grouped shapes only. + Reference, + /// A web address: free text, but a bare nine digits joined to a letter + /// or URL punctuation is an id in a path. + Link, +} + +/// A character that stands for a digit: ASCII, full-width, or any other +/// script's numeral (outside a replay, which reads ASCII and full-width +/// only). +fn digit_like(ch: char, extended: bool) -> bool { + ch.is_ascii_digit() || matches!(ch, '\u{ff10}'..='\u{ff19}') || (extended && ch.is_numeric()) +} + +/// A space between a TIN's groups: the plain one, and outside a replay +/// the tab, a line break and every Unicode space separator. +fn tin_space(ch: char, extended: bool) -> bool { + ch == ' ' + || (extended + && matches!( + ch, + '\t' | '\n' + | '\r' + | '\u{85}' + | '\u{2028}' + | '\u{2029}' + | '\u{a0}' + | '\u{1680}' + | '\u{2000}' + ..='\u{200a}' | '\u{202f}' | '\u{205f}' | '\u{3000}' + )) +} + +/// A dash or dot between a TIN's groups: the hyphen, the dashes U+2010 to +/// U+2015, the minus sign and the dot, and outside a replay every other +/// Unicode dash and dot form. +fn tin_dash(ch: char, extended: bool) -> bool { + matches!(ch, '-' | '\u{2010}'..='\u{2015}' | '\u{2212}' | '.') + || (extended + && matches!( + ch, + '\u{58a}' + | '\u{1806}' + | '\u{2024}' + | '\u{2043}' + | '\u{2e3a}' + | '\u{2e3b}' + | '\u{fe58}' + | '\u{fe63}' + | '\u{ff0d}' + | '\u{ff0e}' + )) +} + +/// The dots among [`tin_dash`]'s characters. +fn tin_dot(ch: char) -> bool { + matches!(ch, '.' | '\u{2024}' | '\u{ff0e}') +} + +/// The characters of `text` and the runs ([from, to) in characters) of it +/// that read as a full TIN, non-overlapping, left to right. +fn printed_tin_spans(text: &str, reading: Reading) -> (Vec, Vec<(usize, usize)>) { + let extended = !crate::parties::is_replaying(); + let all: Vec = text.chars().collect(); + // What is read: outside a replay, the zero-width and soft-hyphen + // characters are not there (`1\u{200B}2` shows as `12`). `seen[i]` is + // where the i-th character read sits in `all`. + let seen: Vec = (0..all.len()) + .filter(|&i| !(extended && crate::parties::tin_invisible(all[i]))) .collect(); - let digit = |i: usize| c.get(i).is_some_and(char::is_ascii_digit); - let dash = |ch: char| matches!(ch, '-' | '\u{2010}'..='\u{2015}' | '\u{2212}' | '.'); + let c: Vec = seen.iter().map(|&i| all[i]).collect(); + let digit = |i: usize| c.get(i).is_some_and(|&ch| digit_like(ch, extended)); + // A hyphen or other dash, the dot not counted. + let hyphen = |i: usize| { + c.get(i) + .is_some_and(|&ch| tin_dash(ch, extended) && !tin_dot(ch)) + }; // A joiner at `i`: a dash, dot or space, or a dash with spaces around - // it; returns where the next group starts. - let joiner = |i: usize| -> Option { + // it; returns where the next group starts, and whether it is a dot. + let joiner = |i: usize| -> Option<(usize, bool)> { let mut j = i; - while c.get(j) == Some(&' ') { + while c.get(j).is_some_and(|&ch| tin_space(ch, extended)) { j += 1; } - let mut dashes = 0; - while c.get(j).copied().is_some_and(dash) { + let (mut dashes, mut dotted) = (0, false); + while c.get(j).is_some_and(|&ch| tin_dash(ch, extended)) { + dotted |= tin_dot(c[j]); j += 1; dashes += 1; } - while c.get(j) == Some(&' ') { + while c.get(j).is_some_and(|&ch| tin_space(ch, extended)) { j += 1; } let spaces = j - i - dashes; - (j > i && dashes <= 1 && spaces <= 2).then_some(j) + (j > i && dashes <= 1 && spaces <= 2).then_some((j, dotted)) }; - let groups_at = |at: usize, groups: &[usize]| -> Option { - let mut i = at; + // Where `groups` of digits end from `at`, and how many joiners were dots. + let groups_at = |at: usize, groups: &[usize]| -> Option<(usize, usize)> { + let (mut i, mut dots) = (at, 0); for (n, g) in groups.iter().enumerate() { if n > 0 { - i = joiner(i)?; + let (next, dotted) = joiner(i)?; + i = next; + dots += usize::from(dotted); } for _ in 0..*g { if !digit(i) { @@ -771,29 +921,101 @@ fn printed_tin(text: &str, link: bool) -> bool { i += 1; } } - Some(i) + Some((i, dots)) }; let url_joined = |i: Option| { i.and_then(|i| c.get(i)) .is_some_and(|ch| ch.is_alphabetic() || matches!(ch, '/' | '=' | '?' | '&' | '#')) }; - (0..c.len()).any(|at| { - (at == 0 || !digit(at - 1)) - && [&[9][..], &[3, 2, 4][..], &[2, 7][..]].iter().any(|g| { - groups_at(at, g).is_some_and(|end| { - !digit(end) - && !(link - && g.len() == 1 - && (url_joined(at.checked_sub(1)) || url_joined(Some(end)))) - }) - }) - }) + // The text before `at` ends in a digit and a dash: the group is the + // tail of a longer number (a date's day, a part number). + let digit_dash_before = |at: usize| at >= 2 && hyphen(at - 1) && digit(at - 2); + // The text from `end` is a dash and a digit: the group is the head of a + // longer number. + let dash_digit_after = |end: usize| hyphen(end) && digit(end + 1); + // A dot with a digit on each side: a decimal point. + let decimal_point = |i: usize| c.get(i) == Some(&'.') && i >= 1 && digit(i - 1) && digit(i + 1); + let shapes: &[&[usize]] = match reading { + Reading::Reference => &[&[3, 2, 4], &[2, 7]], + Reading::Free | Reading::Link => &[&[9], &[3, 2, 4], &[2, 7]], + }; + let mut spans = Vec::new(); + let mut at = 0; + while at < c.len() { + if at > 0 && digit(at - 1) { + at += 1; + continue; + } + let found = shapes.iter().find_map(|g| { + let (end, dots) = groups_at(at, g)?; + if digit(end) { + return None; + } + match g.len() { + // Nine digits alone: not a number in a path (a link), not + // the digits of a decimal. + 1 => { + let in_a_path = reading == Reading::Link + && (url_joined(at.checked_sub(1)) || url_joined(Some(end))); + let in_a_decimal = (at >= 1 && decimal_point(at - 1)) || decimal_point(end); + (!in_a_path && !in_a_decimal).then_some(end) + } + // An EIN: never joined by a dot. + 2 => (dots == 0 && !digit_dash_before(at) && !dash_digit_after(end)).then_some(end), + // An SSN: dots at both joiners or at neither. + _ => ((dots == 0 || dots == 2) && !digit_dash_before(at) && !dash_digit_after(end)) + .then_some(end), + } + }); + match found { + Some(end) => { + spans.push((seen[at], seen[end - 1] + 1)); + at = end; + } + None => at += 1, + } + } + (all, spans) +} + +/// What a refusal says of a field that looks like it holds a tax id +/// (BS-partner-2): which field, why, where a tax id goes instead. Never +/// the number. +pub fn tin_refusal(field: &str) -> String { + format!( + "{field} looks like it holds a tax id (a full SSN or EIN: nine digits, bare or written 3-2-4 or 2-7), so nothing was changed. Tax ids are stored only with books.set_tin or a W-9 (books.set_w9), never in a name, note or description; to mention a number, write only its last four digits" + ) +} + +/// Free text (a memo, a note, a reason, a description, a name) that may be +/// kept: it must not look like a tax id ([`holds_printed_tin`]). Returns +/// why not, in [`tin_refusal`]'s words. Never refuses during a replay +/// ([`crate::parties::replaying`]): the journal holds what it holds, and +/// books an earlier version wrote open (BS-entry-4). +pub fn check_free_text(field: &str, text: &str) -> Result<(), String> { + if !crate::parties::is_replaying() && holds_printed_tin(text) { + return Err(tin_refusal(field)); + } + Ok(()) +} + +/// A reference (an asset tag, a serial number, an invoice or bill number, a +/// payment reference, an account code, a file name, a label) that may be +/// kept: it must not look like a tax id's *printed* shapes +/// ([`holds_printed_tin_in_reference`]), a bare run of nine digits being a +/// legitimate number there. Returns why not, in [`tin_refusal`]'s words. +/// Never refuses during a replay (BS-entry-4). +pub fn check_reference_text(field: &str, text: &str) -> Result<(), String> { + if !crate::parties::is_replaying() && holds_printed_tin_in_reference(text) { + return Err(tin_refusal(field)); + } + Ok(()) } fn no_tin(what: &str, s: &str) -> Result<(), String> { if holds_printed_tin(s) { return Err(format!( - "{what} holds a number that reads as a full SSN or EIN (nine digits, bare or printed 3-2-4 or 2-7): a full TIN goes only into the vault (books.set_tin), the company's EIN into company.ein and its D-U-N-S number into company.duns; for any other nine-digit number, write its last four" + "{what} holds a number that reads as a full SSN or EIN (nine digits, bare or printed 3-2-4 or 2-7): a full TIN goes only into the vault (books.set_tin or a W-9, books.set_w9), the company's EIN into company.ein and its D-U-N-S number into company.duns; for any other nine-digit number, write its last four" )); } Ok(()) @@ -807,6 +1029,19 @@ pub fn line_text(what: &str, s: &str, max: usize) -> Result { Ok(t) } +/// [`line_text`] for a reference (a label): one line, with only the printed +/// SSN and EIN shapes refused, a bare nine digits allowed +/// ([`holds_printed_tin_in_reference`]). +pub fn reference_line_text(what: &str, s: &str, max: usize) -> Result { + let t = bare_line_text(what, s, max)?; + if holds_printed_tin_in_reference(&t) { + return Err(format!( + "{what} holds a number that reads as a full SSN or EIN (printed 3-2-4 or 2-7): a full TIN goes only into the vault (books.set_tin or a W-9, books.set_w9); for any other number, write it without that grouping" + )); + } + Ok(t) +} + /// [`line_text`] without the full-TIN check: for the one place a nine-digit /// number is legitimate (an `ach` or `wire` payment method's bank-detail /// line, where it is a routing number: A-3). @@ -2090,8 +2325,6 @@ mod tests { "123-45-6789", "a 12-3456789.", "(123-45-6789)", - "1-123-45-6789", - "12-3456789-0", "123\u{2010}45\u{2010}6789", "123 45 6789", "SSN 123456789", @@ -2105,6 +2338,12 @@ mod tests { "12-34567890", "1234567890", "14745117-0160", + // the tail or head of a longer run of digits and dashes + "1-123-45-6789", + "12-3456789-0", + // a decimal, a date and its reference + "47.6062095", + "2026-11-21 0001234", "801-555-0142", "2026-10-04", "100 Example Way, Midvale, UT 84047", diff --git a/crates/ledger-core/tests/free_text_tin.rs b/crates/ledger-core/tests/free_text_tin.rs new file mode 100644 index 00000000..3a46c16f --- /dev/null +++ b/crates/ledger-core/tests/free_text_tin.rs @@ -0,0 +1,946 @@ +//! Free text never holds a tax id (BS-partner-2): the one detector free +//! text meets (`ledger_core::settings::holds_printed_tin`), the masking a +//! bank's description gets, and the engine commands that take free text. +//! +//! Oracle: the owner's decision of 2026-11-21 (docs/spec/claims/partner.md, +//! the CHOICE on BS-partner-2): free text refuses what looks like a tax id, +//! that is nine digits standing alone, an SSN's 3-2-4 and an EIN's 2-7, with +//! any dash, dot or space between the groups; it lets an invoice number, a +//! phone number, an order number, a reference of ten digits or more, an +//! amount and a date through. The fake ids are `000-00-0000` and +//! `00-0000000`; no real one appears here. + +use ledger_core::settings::{ + check_free_text, check_reference_text, count_printed_tins, holds_printed_tin, + holds_printed_tin_in_reference, mask_printed_tins, mask_printed_tins_in_reference, tin_refusal, +}; +use proptest::prelude::*; + +/// Every separator the detector reads between a TIN's groups, the dot +/// aside (a dot joins only the three groups of an SSN, both: `DOTS`). +const SEPARATORS: &[&str] = &[ + "-", + "\u{2010}", + "\u{2011}", + "\u{2012}", + "\u{2013}", + "\u{2014}", + "\u{2015}", + "\u{2212}", + "\u{fe58}", + "\u{fe63}", + "\u{ff0d}", + " ", + " ", + "\t", + "\u{a0}", + "\u{2002}", + "\u{2003}", + "\u{2009}", + "\u{202f}", + "\u{3000}", + " - ", + " \u{2013} ", + "\u{a0}\u{2014}\u{a0}", + // a line break reads as a space + "\n", + "\r\n", +]; + +/// The dots: they join an SSN's groups when they join both of them. +const DOTS: &[&str] = &[".", "\u{ff0e}", "\u{2024}"]; + +/// Text around a number that has no digit at its edge. +const CONTEXTS: &[(&str, &str)] = &[ + ("", ""), + ("paid ", ""), + ("", " paid"), + ("SSN ", "."), + ("(", ")"), + ("ref: ", ", thanks"), + ("a\u{e9}", "z"), +]; + +fn digits(n: usize) -> impl Strategy { + prop::collection::vec(0u8..10, n) + .prop_map(|d| d.into_iter().map(|x| char::from(b'0' + x)).collect()) +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(512))] + + /// Every 3-2-4 grouping with any listed separator is found. + #[test] + fn every_ssn_grouping_is_found( + a in digits(3), b in digits(2), c in digits(4), + s1 in 0..SEPARATORS.len(), s2 in 0..SEPARATORS.len(), ctx in 0..CONTEXTS.len(), + ) { + let text = format!("{}{a}{}{b}{}{c}{}", CONTEXTS[ctx].0, SEPARATORS[s1], SEPARATORS[s2], CONTEXTS[ctx].1); + prop_assert!(holds_printed_tin(&text), "{text:?}"); + } + + /// An SSN written with a dot at both joiners (`000.00.0000`) is found. + #[test] + fn a_dotted_ssn_is_found( + a in digits(3), b in digits(2), c in digits(4), + s1 in 0..DOTS.len(), s2 in 0..DOTS.len(), ctx in 0..CONTEXTS.len(), + ) { + let text = format!("{}{a}{}{b}{}{c}{}", CONTEXTS[ctx].0, DOTS[s1], DOTS[s2], CONTEXTS[ctx].1); + prop_assert!(holds_printed_tin(&text), "{text:?}"); + } + + /// A dot at one joiner only, or between an EIN's groups, is a decimal or + /// a version, not a tax id (a coordinate: `47.6062095`). + #[test] + fn a_dot_alone_is_not_a_joiner( + a in digits(3), b in digits(2), c in digits(4), e in digits(7), + dot in 0..DOTS.len(), sep in 0..SEPARATORS.len(), ctx in 0..CONTEXTS.len(), + ) { + let ein = format!("{}{}{}{e}{}", CONTEXTS[ctx].0, &a[..2], DOTS[dot], CONTEXTS[ctx].1); + prop_assert!(!holds_printed_tin(&ein), "{ein:?}"); + let first = format!("{}{a}{}{b}{}{c}{}", CONTEXTS[ctx].0, DOTS[dot], SEPARATORS[sep], CONTEXTS[ctx].1); + prop_assert!(!holds_printed_tin(&first), "{first:?}"); + let second = format!("{}{a}{}{b}{}{c}{}", CONTEXTS[ctx].0, SEPARATORS[sep], DOTS[dot], CONTEXTS[ctx].1); + prop_assert!(!holds_printed_tin(&second), "{second:?}"); + } + + /// A date followed by a seven-digit reference is a date and a + /// reference, whatever stands between them, and a decimal with seven + /// digits after its point is a number (`47.6062095`). + #[test] + fn a_date_then_a_reference_and_a_decimal_are_no_tax_id( + y in 1990u32..2100, m in 1u32..13, d in 1u32..29, r in digits(7), + whole in digits(2), sep in 0..4usize, ctx in 0..CONTEXTS.len(), + ) { + let between = [" ", "\t", "\n", " "][sep]; + let date = format!("{}{y}-{m:02}-{d:02}{between}{r}{}", CONTEXTS[ctx].0, CONTEXTS[ctx].1); + prop_assert!(!holds_printed_tin(&date), "{date:?}"); + let decimal = format!("{}{whole}.{r}{}", CONTEXTS[ctx].0, CONTEXTS[ctx].1); + prop_assert!(!holds_printed_tin(&decimal), "{decimal:?}"); + } + + /// Every 2-7 grouping with any listed separator is found. + #[test] + fn every_ein_grouping_is_found( + a in digits(2), b in digits(7), s in 0..SEPARATORS.len(), ctx in 0..CONTEXTS.len(), + ) { + let text = format!("{}{a}{}{b}{}", CONTEXTS[ctx].0, SEPARATORS[s], CONTEXTS[ctx].1); + prop_assert!(holds_printed_tin(&text), "{text:?}"); + } + + /// Nine digits standing alone are found. + #[test] + fn nine_digits_alone_are_found(a in digits(9), ctx in 0..CONTEXTS.len()) { + let text = format!("{}{a}{}", CONTEXTS[ctx].0, CONTEXTS[ctx].1); + prop_assert!(holds_printed_tin(&text), "{text:?}"); + } + + /// Ten digits or more are a reference, never a tax id: one digit more + /// before, after or inside a shape takes it out of the reading. + #[test] + fn ten_or_more_digits_are_a_reference(a in digits(10), extra in 0usize..6, ctx in 0..CONTEXTS.len()) { + let tail: String = "7".repeat(extra); + let text = format!("{}{a}{tail}{}", CONTEXTS[ctx].0, CONTEXTS[ctx].1); + prop_assert!(!holds_printed_tin(&text), "{text:?}"); + } + + /// Masking leaves nothing for the detector to find, keeps the last four + /// digits of each number and its length, and changes nothing else. + #[test] + fn masking_keeps_the_last_four_and_the_rest( + a in digits(3), b in digits(2), c in digits(4), s1 in 0..SEPARATORS.len(), + s2 in 0..SEPARATORS.len(), ctx in 0..CONTEXTS.len(), + ) { + let text = format!("{}{a}{}{b}{}{c}{}", CONTEXTS[ctx].0, SEPARATORS[s1], SEPARATORS[s2], CONTEXTS[ctx].1); + let masked = mask_printed_tins(&text).into_owned(); + prop_assert!(!holds_printed_tin(&masked), "{masked:?}"); + prop_assert_eq!(masked.chars().count(), text.chars().count()); + prop_assert_eq!(count_printed_tins(&text), 1); + let expect = format!("{}\u{2022}\u{2022}\u{2022}{}\u{2022}\u{2022}{}{c}{}", CONTEXTS[ctx].0, SEPARATORS[s1], SEPARATORS[s2], CONTEXTS[ctx].1); + prop_assert_eq!(masked, expect); + } +} + +/// What must go through: the allow-list of the owner's table. +#[test] +fn the_allow_list_passes() { + for fine in [ + // invoice numbers + "INV-2026-11-0042", + "2026-11-0042", + "invoice 2026-0042", + "INV 20261121", + // phone numbers + "801-555-0142", + "(801) 555-0142", + "+1 801 555 0142", + "+44 20 7946 0958", + // order numbers + "ORD-48213-7", + "order 4821-3377-12", + "PO 12-345", + // references of ten digits or more + "1234567890", + "REF 202611210042", + "000000000000", + "12345678901234567890", + // amounts + "$1,234,567.89", + "1,234,567", + "$12,345,678.00", + "USD 1 234 567,89", + // dates + "2026-11-21", + "11/21/2026", + "21.11.2026", + "2026-11-21T10:30:00Z", + // decimals: a coordinate, a version, an amount + "47.6062095", + "at 47.6062095, -122.3321", + "17.2345678", + "v 12.3456789", + "$1234567.8901234", + // a date followed by, or inside, a longer number + "2026-11-21 0001234", + "on 2026-11-21 0001234 paid", + "2026-11-0001234", + "55-1234567-001", + "part 5-000-00-0000", + // plain words + "Office rent, November", + "", + ] { + assert!(!holds_printed_tin(fine), "{fine:?} must pass"); + assert!(check_free_text("memo", fine).is_ok(), "{fine:?} must pass"); + } +} + +/// What must be found, written out: the shapes with the fake ids. +#[test] +fn the_shapes_are_found() { + for caught in [ + "000-00-0000", + "00-0000000", + "000000000", + "tin 000 00 0000", + "ein 00 0000000", + "000\u{2013}00\u{2013}0000", + "000\u{a0}00\u{a0}0000", + "\u{ff10}\u{ff10}\u{ff10}-\u{ff10}\u{ff10}-\u{ff10}\u{ff10}\u{ff10}\u{ff10}", + "\u{660}\u{660}\u{660}-\u{660}\u{660}-\u{660}\u{660}\u{660}\u{660}", + "pay 00-0000000 now", + "SSN: 000.00.0000.", + // a line break between the groups reads as a space + "000\n00\n0000", + "000\r\n00\r\n0000", + "ein 00\n0000000", + "ein 00\r0000000", + // zero-width and soft-hyphen characters between digits are not there + "000\u{200b}-00-0000", + "0\u{200b}0\u{200c}0\u{200d}-0\u{2060}0-00\u{feff}00", + "00\u{ad}-0000000", + "00-000\u{ad}0\u{ad}000", + "0\u{200b}00000000", + "\u{200b}000000000\u{200b}", + // the text around a number + "words 000-00-0000 words", + "(00-0000000)", + ] { + assert!(holds_printed_tin(caught), "{caught:?} must be found"); + let why = check_free_text("the memo", caught).unwrap_err(); + assert!( + why.starts_with("the memo looks like it holds a tax id"), + "{why}" + ); + assert!(why.contains("books.set_tin"), "{why}"); + assert!(why.contains("W-9"), "{why}"); + assert!( + !why.contains("0000"), + "a refusal never repeats the number: {why}" + ); + } +} + +/// What the shapes do not take for a tax id: a dot is no joiner but between +/// both groups of an SSN, and a group that is the tail or head of a longer +/// run of digits and dashes belongs to that run. +#[test] +fn a_dot_and_a_longer_run_are_no_tax_id() { + for fine in [ + "47.6062095", + "17.2345678", + "12.3456789", + "000.00 0000", + "000 00.0000", + "000.00-0000", + "000-00.0000", + "2026-11-21 0001234", + "2026-11-21\n0001234", + "12-3456789-0", + "1-123-45-6789", + "0000-00-0000000", + "123456789.5", + "0.123456789", + ] { + assert!(!holds_printed_tin(fine), "{fine:?} must pass"); + assert!(check_free_text("memo", fine).is_ok(), "{fine:?} must pass"); + } + // ... while the shapes, with words around them, are still found. + for caught in [ + "2026-11-21 paid 00-0000000", + "on 2026-11-21: 000-00-0000", + "47.6062095 and then 00-0000000", + "ref 12-3456789.", + "123456789.", + ] { + assert!(holds_printed_tin(caught), "{caught:?} must be found"); + } + // The line break and the invisible characters are read only outside a + // replay, as the Unicode forms are (BS-entry-4). + let broken = "000\n00\n0000"; + assert!(holds_printed_tin(broken)); + ledger_core::parties::replaying(|| { + assert!(!holds_printed_tin(broken)); + assert!(!holds_printed_tin("0\u{200b}00000000")); + }); +} + +/// Letters between digits, and a number split across two fields, are an +/// accident and not a way to hide one: the reading leaves them (WB-partner-15). +#[test] +fn letters_between_digits_are_left_alone() { + for fine in ["000a00b0000", "00-0000 000", "000-00x0000"] { + assert!(!holds_printed_tin(fine), "{fine:?}"); + } +} + +/// A reference's reading (an asset tag, a serial, an invoice or bill +/// number, a payment reference, an account code, a file name): a bare nine +/// digits is a number there; the printed shapes are still refused. +#[test] +fn a_reference_may_be_nine_digits_but_not_a_printed_tax_id() { + for fine in [ + "123456789", + "SN 000000000", + "tag 000000000.", + "000000000", + "INV-2026-11-0042", + "1234567890", + "scan 000000000.pdf", + ] { + assert!(!holds_printed_tin_in_reference(fine), "{fine:?}"); + assert!(check_reference_text("the tag", fine).is_ok(), "{fine:?}"); + assert_eq!( + mask_printed_tins_in_reference(fine), + fine, + "a bare nine digits stays in a reference" + ); + } + for caught in [ + "000-00-0000", + "00-0000000", + "SN 000 00 0000", + "w9 00\u{2013}0000000.pdf", + "000.00.0000", + "000\n00\n0000", + "0\u{200b}0-0000000", + ] { + assert!(holds_printed_tin_in_reference(caught), "{caught:?}"); + let why = check_reference_text("the tag", caught).unwrap_err(); + assert!( + why.starts_with("the tag looks like it holds a tax id") && !why.contains("0000"), + "{why}" + ); + } + // Free text says the same of the same bare run: refused. + assert!(holds_printed_tin("123456789")); + // A mask of a reference keeps its bare run and covers its shapes. + assert_eq!( + mask_printed_tins_in_reference("SN 123456789 / 000-00-0000"), + "SN 123456789 / \u{2022}\u{2022}\u{2022}-\u{2022}\u{2022}-0000" + ); +} + +/// Two numbers in one text are two finds, each masked to its last four. +#[test] +fn masking_masks_each_number() { + let text = "ACH 000-00-0000 and ref 00-0000000, then 1234567890"; + assert_eq!(count_printed_tins(text), 2); + assert_eq!( + mask_printed_tins(text), + "ACH \u{2022}\u{2022}\u{2022}-\u{2022}\u{2022}-0000 and ref \u{2022}\u{2022}-\u{2022}\u{2022}\u{2022}0000, then 1234567890" + ); + // Nothing to mask: the text comes back as it was. + assert!(matches!( + mask_printed_tins("Whole Foods #1234"), + std::borrow::Cow::Borrowed(_) + )); +} + +#[test] +fn the_refusal_names_the_field_and_never_a_number() { + let why = tin_refusal("books.add_class name"); + assert!(why.starts_with("books.add_class name looks like it holds a tax id")); + assert!(why.contains("books.set_tin") && why.contains("books.set_w9")); +} + +// --------------------------------------------------------------------- +// The engine: a caller other than the MCP layer meets the same check. +// --------------------------------------------------------------------- + +mod engine { + use chrono::NaiveDate; + use ledger_core::arap::{BillFields, DocumentLine, InvoiceFields, PartySnapshot}; + use ledger_core::schedules::{ + Frequency, NewRecurring, NewSchedule, ScheduleConvention, ScheduleKind, + }; + use ledger_core::{ + AccountId, AccountType, Currency, Ledger, LedgerError, Money, NewAsset, Side, + }; + use rust_decimal::Decimal; + use std::str::FromStr; + + const TIN: &str = "000-00-0000"; + + fn day(d: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(2026, 3, d).unwrap() + } + + fn usd(s: &str) -> Money { + Money::new(Decimal::from_str(s).unwrap(), Currency::USD) + } + + struct Fx { + l: Ledger, + cash: AccountId, + revenue: AccountId, + expense: AccountId, + asset: AccountId, + accum: AccountId, + liability: AccountId, + } + + fn fx() -> Fx { + let mut l = Ledger::new(Currency::USD); + let mut add = |code: &str, name: &str, t: AccountType| { + l.add_account(code, name, t, None, false).unwrap() + }; + let cash = add("1000", "Cash", AccountType::Asset); + let asset = add("1500", "Equipment", AccountType::Asset); + let accum = add("1590", "Accumulated depreciation", AccountType::Asset); + let liability = add("2500", "Deferred", AccountType::Liability); + let revenue = add("4000", "Sales", AccountType::Revenue); + let expense = add("6000", "Supplies", AccountType::Expense); + Fx { + l, + cash, + revenue, + expense, + asset, + accum, + liability, + } + } + + fn line(desc: &str) -> DocumentLine { + DocumentLine { + description: desc.into(), + amount: Decimal::from(10), + class_id: None, + account: None, + quantity: None, + unit_price: None, + } + } + + fn holds_tin(r: Result, field: &str) { + match r { + Err(LedgerError::FreeTextHoldsTin(why)) => { + assert!( + why.starts_with(&format!("{field} looks like it holds a tax id")), + "{why}" + ); + assert!( + why.contains("books.set_tin") && why.contains("W-9"), + "{why}" + ); + assert!(!why.contains("0000"), "never the number: {why}"); + } + other => panic!("{field}: expected FreeTextHoldsTin, got {other:?}"), + } + } + + /// An entry's description, a reversal's, a write-off's and a void's + /// reason, a period's name, an account's code. + #[test] + fn entries_periods_and_codes() { + let mut f = fx(); + holds_tin( + f.l.try_create_entry(day(1), &format!("paid {TIN}")), + "the entry description", + ); + // Nothing was made: the next entry is still the first. + let e = + f.l.try_create_entry(day(1), "inv 2026-11-0042, ref 1234567890") + .unwrap(); + f.l.add_line(e, f.cash, Side::Debit, usd("5.00")).unwrap(); + f.l.add_line(e, f.revenue, Side::Credit, usd("5.00")) + .unwrap(); + f.l.post_entry(e).unwrap(); + let before = f.l.clone(); + holds_tin( + f.l.reverse_entry(e, day(2), &format!("oops {TIN}")), + "the reversal's description", + ); + assert_eq!(f.l, before, "a refusal changes nothing"); + holds_tin( + f.l.create_period(&format!("P {TIN}"), day(1), day(31)), + "the period name", + ); + // An account code is a reference: its printed shape is refused, a + // bare nine digits is a code (WB-partner-15). + holds_tin( + f.l.add_account(TIN, "Odd", AccountType::Asset, None, false), + "the account code", + ); + let nine = + f.l.add_account("123456789", "Nine", AccountType::Asset, None, false); + assert!(nine.is_ok(), "{nine:?}"); + holds_tin( + f.l.renumber_account(f.cash, "00-0000000"), + "the account code", + ); + f.l.renumber_account(f.cash, "000000000").unwrap(); + f.l.create_period("2026-03", day(1), day(31)).unwrap(); + } + + /// A document's memo, references, duplicate reason, lines and the + /// customer's printed details. + #[test] + fn documents() { + let mut f = fx(); + let c = f.l.add_customer("Acme").unwrap(); + let v = f.l.add_vendor("Beta").unwrap(); + let inv = |l: &mut Ledger, lines: Vec, fields: InvoiceFields| { + l.create_invoice_with(c, day(1), day(31), lines, fields) + }; + holds_tin( + inv( + &mut f.l, + vec![line(&format!("work {TIN}"))], + InvoiceFields::default(), + ), + "a line's description", + ); + holds_tin( + inv( + &mut f.l, + vec![line("ok")], + InvoiceFields { + memo: Some(format!("see {TIN}")), + ..Default::default() + }, + ), + "the memo", + ); + holds_tin( + inv( + &mut f.l, + vec![line("ok")], + InvoiceFields { + customer_ref: Some("PO 00-0000000".into()), + ..Default::default() + }, + ), + "the reference", + ); + let snap = |name: &str| PartySnapshot { + name: name.into(), + address: None, + email: None, + phone: None, + contact: None, + billing_address: None, + shipping_address: None, + billing_email: None, + }; + // The customer's printed details are a party's: any nine digits. + let strict = inv( + &mut f.l, + vec![line("ok")], + InvoiceFields { + bill_to: Some(snap("Acme 1234 56789")), + ..Default::default() + }, + ); + assert!( + matches!(strict, Err(LedgerError::InvalidParty(_))), + "{strict:?}" + ); + // The company's own details are free text: its shapes only. + holds_tin( + inv( + &mut f.l, + vec![line("ok")], + InvoiceFields { + seller: Some(snap(&format!("Us {TIN}"))), + ..Default::default() + }, + ), + "the seller name", + ); + // Neither a 10-digit PO nor a ZIP+4 in the company's address is a tax id. + let mut us = snap("Us"); + us.address = Some("1 Main St, Midvale UT 84047-1234".into()); + inv( + &mut f.l, + vec![line("ok")], + InvoiceFields { + customer_ref: Some("1234567890".into()), + memo: Some("2026-11-0042".into()), + seller: Some(us), + ..Default::default() + }, + ) + .unwrap(); + let bill = |l: &mut Ledger, fields: BillFields| { + l.create_bill_with(v, day(1), day(31), vec![line("ok")], fields) + }; + holds_tin( + bill( + &mut f.l, + BillFields { + vendor_ref: Some(TIN.into()), + ..Default::default() + }, + ), + "the reference", + ); + // A bare nine digits is a vendor's invoice number, and a customer's + // purchase order: references. + bill( + &mut f.l, + BillFields { + vendor_ref: Some("000000000".into()), + ..Default::default() + }, + ) + .unwrap(); + inv( + &mut f.l, + vec![line("ok")], + InvoiceFields { + customer_ref: Some("PO 123456789".into()), + ..Default::default() + }, + ) + .unwrap(); + holds_tin( + bill( + &mut f.l, + BillFields { + memo: Some(TIN.into()), + ..Default::default() + }, + ), + "the memo", + ); + holds_tin( + bill( + &mut f.l, + BillFields { + duplicate_reason: Some(format!("again {TIN}")), + ..Default::default() + }, + ), + "the duplicate reason", + ); + bill( + &mut f.l, + BillFields { + vendor_ref: Some("INV-2026-11-0042".into()), + ..Default::default() + }, + ) + .unwrap(); + } + + /// A payment's reference is the engine's to check, as the tools check + /// it: a printed SSN or EIN is refused, a bare nine digits (a check or + /// a confirmation number) is kept, and the entry's description, which + /// is free text, shows it masked. A discount's reason is free text. + #[test] + fn payments_check_their_reference_and_discount_reason() { + use ledger_core::{Application, DocRef, PaymentDetails, SettleParams}; + let mut f = fx(); + let c = f.l.add_customer("Acme").unwrap(); + let v = f.l.add_vendor("Beta").unwrap(); + let invoice = + f.l.create_invoice_with( + c, + day(1), + day(31), + vec![line("work")], + InvoiceFields::default(), + ) + .unwrap(); + let bill = + f.l.create_bill_with( + v, + day(1), + day(31), + vec![line("parts")], + BillFields::default(), + ) + .unwrap(); + let pay = |l: &mut Ledger, reference: &str| { + l.receive_payment_with( + invoice, + day(5), + Decimal::from(1), + f.cash, + &PaymentDetails { + instrument: None, + reference: Some(reference.into()), + }, + ) + }; + holds_tin(pay(&mut f.l, TIN), "the payment reference"); + holds_tin(pay(&mut f.l, "check 00-0000000"), "the payment reference"); + let before = f.l.clone(); + holds_tin( + f.l.pay_bill_with( + bill, + day(5), + Decimal::from(1), + f.cash, + &PaymentDetails { + instrument: None, + reference: Some(format!("wire {TIN}")), + }, + ), + "the payment reference", + ); + assert_eq!(f.l, before, "a refusal changes nothing"); + // A bare nine digits is a reference ... + let e = pay(&mut f.l, "123456789").unwrap(); + // ... and the entry's description, free text, holds it masked. + assert_eq!( + f.l.get_entry(e).unwrap().description(), + "Payment on invoice 1 (ref \u{2022}\u{2022}\u{2022}\u{2022}\u{2022}6789)" + ); + // A ten-digit trace number is kept as it is. + let e = pay(&mut f.l, "1234567890").unwrap(); + assert_eq!( + f.l.get_entry(e).unwrap().description(), + "Payment on invoice 1 (ref 1234567890)" + ); + // The discount reason of a settlement. + let settle = |l: &mut Ledger, why: &str| { + l.settle(SettleParams { + date: day(6), + description: "Payment".into(), + cash_account: f.cash, + party: c, + applications: vec![Application { + doc: DocRef::Invoice(invoice), + cash: Decimal::from(1), + discount: Decimal::ZERO, + discount_reason: Some(why.into()), + }], + fee: None, + instrument: None, + reference: None, + }) + }; + holds_tin( + settle(&mut f.l, &format!("early {TIN}")), + "the discount reason", + ); + settle(&mut f.l, "paid within 10 days, ref 1234567890").unwrap(); + // A replay reads none of it. + ledger_core::parties::replaying(|| { + let d = PaymentDetails { + instrument: None, + reference: Some(TIN.into()), + }; + d.check().unwrap(); + }); + } + + /// A project's fields are refused by the engine itself, whoever calls + /// (the tools' own check runs before it, and says it first). + #[test] + fn a_project_field_is_refused_by_the_engine() { + use ledger_core::classes::ProjectFacts; + let mut f = fx(); + let id = f.l.add_class("Harbor").unwrap(); + let facts = |notes: Option<&str>, description: Option<&str>, links: &[&str]| ProjectFacts { + notes: notes.map(Into::into), + description: description.map(Into::into), + links: links.iter().map(|l| (*l).to_string()).collect(), + ..Default::default() + }; + let engine_refusal = |r: Result<(String, ProjectFacts), LedgerError>, field: &str| match r { + Err(LedgerError::InvalidProject(why)) => { + assert!(why.contains(field), "{why}"); + assert!(why.contains("full SSN or EIN"), "{why}"); + assert!(!why.contains("0000"), "never the number: {why}"); + } + other => panic!("{field}: expected the engine's refusal, got {other:?}"), + }; + engine_refusal( + f.l.check_set_project(id, "Harbor", &facts(Some(&format!("ssn {TIN}")), None, &[])), + "notes", + ); + engine_refusal( + f.l.check_set_project(id, "Harbor", &facts(None, Some("ein 00-0000000"), &[])), + "description", + ); + engine_refusal( + f.l.check_set_project( + id, + "Harbor", + &facts(None, None, &["https://x.test/000-00-0000"]), + ), + "link", + ); + match f + .l + .set_project(id, &format!("Harbor {TIN}"), facts(None, None, &[])) + { + Err(LedgerError::InvalidProject(why)) => { + assert!(why.contains("full SSN or EIN"), "{why}"); + } + other => panic!("the name: {other:?}"), + } + // A reference of ten digits, an invoice number and a store listing's + // id are no tax id. + f.l.set_project( + id, + "Harbor 2026-11-0042", + facts( + Some("ref 1234567890"), + Some("PO 2026-0042"), + &["https://apps.example.com/app/id284882215"], + ), + ) + .unwrap(); + } + + /// Assets, schedules, recurring entries and payroll names. + #[test] + fn assets_schedules_and_payroll() { + let mut f = fx(); + let new = |d: &str| NewAsset { + description: d.into(), + in_service_date: day(1), + cost: usd("1200.00"), + salvage_value: usd("0"), + useful_life_months: 12, + cost_account: f.asset, + accum_depr_account: f.accum, + expense_account: f.expense, + }; + holds_tin( + f.l.register_asset(new(&format!("van {TIN}"))), + "the asset description", + ); + let a = f.l.register_asset(new("van 1234567890")).unwrap(); + holds_tin( + f.l.set_asset_serial(a, Some("SN 00-0000000")), + "the serial number", + ); + holds_tin( + f.l.set_asset_description(a, "000000000"), + "the asset description", + ); + holds_tin(f.l.set_asset_tag(a, "T-000-00-0000"), "the asset tag"); + f.l.set_asset_serial(a, Some("C02XK1ABCDEF")).unwrap(); + // A tag and a serial number are references: a bare nine digits + // is one. + f.l.set_asset_serial(a, Some("000000000")).unwrap(); + f.l.set_asset_tag(a, "123456789").unwrap(); + let sched = |d: &str| NewSchedule { + description: d.into(), + kind: ScheduleKind::PrepaidExpense, + total: usd("1200.00"), + start: day(1), + months: 12, + balance_account: f.asset, + pl_account: f.expense, + convention: ScheduleConvention::Daily, + }; + holds_tin( + f.l.register_schedule(sched(&format!("rent {TIN}"))), + "the schedule's description", + ); + let _ = f.liability; + let rec = |d: &str| NewRecurring { + description: d.into(), + lines: vec![ + (f.expense, Side::Debit, usd("5.00")), + (f.cash, Side::Credit, usd("5.00")), + ], + frequency: Frequency::Monthly, + start: day(1), + end: None, + }; + holds_tin( + f.l.register_recurring(rec(&format!("fee {TIN}"))), + "the recurring entry's description", + ); + f.l.register_recurring(rec("fee 2026-11-0042")).unwrap(); + } + + /// A draft's note, a discard's reason and a no-party reason: free + /// text now, no longer the strict nine-digit reading. + #[test] + fn notes_and_reasons_use_the_shapes() { + let mut f = fx(); + let e = f.l.try_create_entry(day(1), "x").unwrap(); + let wait = |n: &str| ledger_core::DraftState::AwaitingEvidence { note: n.into() }; + assert!( + f.l.set_draft_state(e, wait(&format!("waiting {TIN}"))) + .is_err() + ); + f.l.set_draft_state(e, wait("waiting on ref 1234567890, inv 2026-11-0042")) + .unwrap(); + assert!(Ledger::check_no_party_reason(&format!("own account {TIN}")).is_err()); + Ledger::check_no_party_reason("own account 1234567890").unwrap(); + assert!(f.l.discard_draft(e, &format!("dup {TIN}")).is_err()); + f.l.discard_draft(e, "entered twice, ref 1234567890") + .unwrap(); + } + + /// BS-entry-4: a journal line an earlier version took replays, whatever + /// it holds; the books open on it. (A replay is the only way such a + /// line is ever applied: every command refuses it.) + #[test] + fn a_journaled_line_replays_whatever_it_holds() { + let mut f = fx(); + let e = f.l.create_entry(day(1), &format!("paid {TIN}")); + f.l.add_line(e, f.cash, Side::Debit, usd("5.00")).unwrap(); + f.l.add_line(e, f.revenue, Side::Credit, usd("5.00")) + .unwrap(); + f.l.post_entry(e).unwrap(); + let r = + f.l.replay_reverse_entry(e, day(2), &format!("undo {TIN}")) + .unwrap(); + assert_eq!( + f.l.get_entry(r).unwrap().description(), + format!("undo {TIN}") + ); + let ann = ledger_core::Annotation { + attachment_id: 1, + fields: ledger_core::AnnotationFields { + payee: Some(format!("Pat {TIN}")), + ..Default::default() + }, + note: Some(format!("see {TIN}")), + }; + f.l.replay_annotate_attachment(ann.clone()).unwrap(); + // The same annotation as a command is refused. + holds_tin(f.l.annotate_attachment(ann), "the payee"); + } +} diff --git a/crates/ledger-core/tests/spec_parties.rs b/crates/ledger-core/tests/spec_parties.rs index a1db34d4..732e111c 100644 --- a/crates/ledger-core/tests/spec_parties.rs +++ b/crates/ledger-core/tests/spec_parties.rs @@ -444,9 +444,15 @@ fn w9_check_refuses_full_tin_in_any_text() { let mut f = w9("6789"); f.entity_type = "LLC 12-3456789".to_string(); assert!(f.check().is_err()); + // Where the paper is kept is a reference, not a name or a detail: its + // printed shapes are refused, and a bare nine digits (a binder's or a + // file's number) is a number there (WB-partner-15). + let mut f = w9("6789"); + f.kept_at = "drawer 123-45-6789".to_string(); + assert!(f.check().is_err()); let mut f = w9("6789"); f.kept_at = "drawer 123456789".to_string(); - assert!(f.check().is_err()); + assert!(f.check().is_ok()); let mut f = w9("6789"); f.exempt_payee_code = Some("123-45-6789".to_string()); assert!(f.check().is_err()); diff --git a/crates/ledger-import/src/bank_csv.rs b/crates/ledger-import/src/bank_csv.rs index f3f77245..3bfc77e7 100644 --- a/crates/ledger-import/src/bank_csv.rs +++ b/crates/ledger-import/src/bank_csv.rs @@ -84,6 +84,86 @@ 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, + /// Each transaction's description exactly as the bank wrote it, in the + /// same order as `transactions`: for matching a categorizing rule + /// against (a rule keyed on a reference of nine digits still matches), + /// never to be kept or shown. + pub as_written: 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; WB-partner-15 (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 mut as_written = Vec::new(); + let transactions = parse_rows(text, order)? + .into_iter() + .map(|(line, mut txn)| { + as_written.push(txn.description.clone()); + 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, + as_written, + }) +} + /// 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 +176,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 +225,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 = crate::line_of(text, &record, idx + 1); + 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() } @@ -264,6 +359,73 @@ mod tests { assert_eq!(txns[0].amount, Decimal::new(-123456, 2)); } + /// parse_bank_csv_masked SCENARIOS 1 and 2, INVARIANTS 1 and 2: a bank's + /// reference is masked to its last four and named by line; a long + /// reference stays; amounts and dates are unchanged. + #[test] + fn a_tax_id_shape_in_a_description_is_masked_and_named() { + let csv = "Date,Description,Amount\n\ + 2026-01-02,ACH 000-00-0000 payroll,-12.50\n\ + 2026-01-03,CHECK 1234567890,-3.25\n\ + \n\ + 2026-01-04,\"WIRE 000000000, REF 00-0000000\",40.00\n"; + let got = parse_bank_csv_masked(csv, None).unwrap(); + let plain = parse_bank_csv_with(csv, None).unwrap(); + assert_eq!(got.transactions.len(), 3); + assert_eq!( + got.transactions[0].description, + "ACH \u{2022}\u{2022}\u{2022}-\u{2022}\u{2022}-0000 payroll" + ); + assert_eq!(got.transactions[1].description, "CHECK 1234567890"); + assert_eq!( + got.transactions[2].description, + "WIRE \u{2022}\u{2022}\u{2022}\u{2022}\u{2022}0000, REF \u{2022}\u{2022}-\u{2022}\u{2022}\u{2022}0000" + ); + for (m, p) in got.transactions.iter().zip(&plain) { + assert_eq!((m.date, m.amount), (p.date, p.amount)); + } + // The file's lines, the blank one counted: 2, and 5. + assert_eq!( + got.masked, + vec![ + MaskedCell { + line: 2, + column: "Description", + numbers: 1 + }, + MaskedCell { + line: 5, + column: "Description", + numbers: 2 + }, + ] + ); + assert!( + got.transactions + .iter() + .all(|t| { !ledger_core::settings::holds_printed_tin(&t.description) }) + ); + // A file with none masks none. + let clean = parse_bank_csv_masked("2026-01-02,Rent,-1.00\n", None).unwrap(); + assert!(clean.masked.is_empty()); + assert_eq!(clean.as_written, ["Rent"]); + } + + /// `as_written` is each description as the bank wrote it, in order, + /// for matching a rule against: a rule keyed on a nine-digit reference + /// still finds it, while the kept description is masked. + #[test] + fn the_bank_s_own_words_are_kept_for_matching_rules() { + let csv = "2026-01-02,ACH 000000000 payroll,-1.00\n2026-01-03,Rent,-2.00\n"; + let got = parse_bank_csv_masked(csv, None).unwrap(); + assert_eq!(got.as_written, ["ACH 000000000 payroll", "Rent"]); + assert_eq!( + got.transactions[0].description, + "ACH \u{2022}\u{2022}\u{2022}\u{2022}\u{2022}0000 payroll" + ); + assert_eq!(got.transactions.len(), got.as_written.len()); + } + #[test] fn bad_column_count_rejected() { let csv = "a,b\n"; diff --git a/crates/ledger-import/src/chart_csv.rs b/crates/ledger-import/src/chart_csv.rs index 47d1d89c..096e28c4 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,32 @@ 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 = crate::line_of(text, &record, idx + 1); + 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 if n == 0 || n == 3 { + // An account code (and its parent's) is a reference: a + // bare nine digits is a code, only the printed shapes + // read as a tax id (WB-partner-15). + ledger_core::settings::holds_printed_tin_in_reference(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" => {} @@ -148,6 +182,30 @@ mod tests { assert_eq!(rows[2].account_type, "revenue"); } + /// An account code is a reference: a bare nine digits is a code, a + /// printed SSN or EIN is refused, naming its row and column. + #[test] + fn a_code_may_be_nine_digits_but_not_a_printed_tax_id() { + let ok = + "code,name,type,parent_code\n123456789,Cash,asset,\n123456790,Bank,asset,123456789\n"; + assert_eq!(parse_chart_csv(ok).unwrap().len(), 2); + for csv in [ + "code,name,type,parent_code\n000-00-0000,Cash,asset,\n", + "code,name,type,parent_code\n1000,Cash,asset,\n1001,Bank,asset,00-0000000\n", + ] { + assert!( + matches!(parse_chart_csv(csv), Err(ChartCsvError::LooksLikeTin(_))), + "{csv}" + ); + } + // A name is a party-style field: any run of nine digits. + let name = "code,name,type,parent_code\n1000,Acct 123456789,asset,\n"; + assert!(matches!( + parse_chart_csv(name), + Err(ChartCsvError::LooksLikeTin(_)) + )); + } + #[test] fn parses_optional_tax_category_column() { let csv = "code,name,type,parent_code,tax_category\n4000,Sales,revenue,,gross_receipts\n1000,Cash,asset,,\n"; @@ -171,6 +229,35 @@ mod tests { )); } + /// INVARIANT 4: a cell that looks like a tax id refuses the file, naming + /// its row and column and never the number; a ten-digit code goes through + /// (a name is read strictly, as an account name is). + #[test] + fn a_tax_id_in_a_cell_is_refused_with_its_row_and_column() { + let header = "code,name,type,parent_code\n"; + let why = |rows: &str| match parse_chart_csv(&format!("{header}{rows}")) { + Err(ChartCsvError::LooksLikeTin(why)) => why, + other => panic!("expected a refusal, got {other:?}"), + }; + let w = why("1000,Cash,asset,\n1010,Payroll 000-00-0000,asset,1000\n"); + assert!( + w.starts_with("the name cell of row 3 looks like it holds a tax id"), + "{w}" + ); + assert!(w.contains("books.set_tin") && w.contains("W-9"), "{w}"); + assert!(!w.contains("0000"), "never the number: {w}"); + // A name is read strictly, as an account name is: any nine digits. + assert!(why("1000,Card 1234 56789,asset,\n").contains("name cell of row 2")); + // Another column is read by its shape. + assert!(why("000-00-0000,Cash,asset,\n").contains("code cell of row 2")); + assert!(why("1000,Cash,asset,00-0000000\n").contains("parent_code cell of row 2")); + // A blank line counts as a line of the file. + assert!(why("1000,Cash,asset,\n\n1010,Bad 000000000,asset,\n").contains("row 4")); + // What is no tax id goes through. + let ok = parse_chart_csv(&format!("{header}1234567890,Loan 2026,liability,\n")); + assert_eq!(ok.unwrap().len(), 1); + } + /// Found by fuzz_import_csv (2026-10-13): a row with a blank code or /// name was accepted. #[test] diff --git a/crates/ledger-import/src/lib.rs b/crates/ledger-import/src/lib.rs index 49822aff..53b6ae4f 100644 --- a/crates/ledger-import/src/lib.rs +++ b/crates/ledger-import/src/lib.rs @@ -29,8 +29,28 @@ pub mod templates; pub mod workpaper; pub mod xlsx; +/// The line of `text` (the first is 1) a CSV record starts on, counted from +/// its byte offset: the csv reader reports a record's position from where +/// it began looking, before it skipped any blank lines, and a row is named +/// by the line a person sees it on. +pub(crate) fn line_of(text: &str, record: &csv::StringRecord, fallback: usize) -> u64 { + record.position().map_or(fallback as u64, |p| { + let bytes = text.as_bytes(); + let mut at = usize::try_from(p.byte()) + .unwrap_or(usize::MAX) + .min(bytes.len()); + while bytes.get(at).is_some_and(|b| matches!(b, b'\n' | b'\r')) { + at += 1; + } + bytes[..at].iter().filter(|b| **b == b'\n').count() as u64 + 1 + }) +} + 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/handbook/attestations-and-audit.md b/crates/ledger-mcp/handbook/attestations-and-audit.md index 8041133b..b55bda7d 100644 --- a/crates/ledger-mcp/handbook/attestations-and-audit.md +++ b/crates/ledger-mcp/handbook/attestations-and-audit.md @@ -8,7 +8,7 @@ The receipt rule in force: {evidence_rule} - books.audit { through, scope } without confirmed lists the checks and changes nothing; show it to the human. Then call it again with confirmed: true and the preview. It files the workpaper (JSON and PDF, category workpaper) and journals the run. books.workpaper { id } gives it back: the JSON, and the PDF handed over (run its download command to save it). - scope: month (a month-end), annual (a fiscal year), cpa_handoff (the year, for the CPA package), full (everything from the start of the books). -- It checks the trial balance, the accounting equation, the profit and loss against equity, the cash flow's footing, the A/R and A/P control accounts, closes, schedules and depreciation, the asset register, every posted entry against the receipt rule, open drafts, tax categories, 1099 decisions and the settings; then the journal's chain, the stored files, the access log and the backups. A finding is a failure (the books are wrong or cannot be shown right), a warning (unfinished or a rule not met) or a note (listed so the workpaper is whole: a reversal rests on its original's receipt). +- It checks the trial balance, the accounting equation, the profit and loss against equity, the cash flow's footing, the A/R and A/P control accounts, closes, schedules and depreciation, the asset register, every posted entry against the receipt rule, open drafts, tax categories, 1099 decisions and the settings; then the journal's chain, the stored files, the access log, a journal line whose text field looks like a tax id (a warning naming the line and the field, never the number; the journal is never rewritten, so correct it with a reversal and keep the tax id in the vault) and the backups. A finding is a failure (the books are wrong or cannot be shown right), a warning (unfinished or a rule not met) or a note (listed so the workpaper is whole: a reversal rests on its original's receipt). - Fix findings with journaled corrections (a reversal, a receipt attached, a decision recorded), never by editing: posted entries stay as they are. Then audit again. - The same books, day and scope give the run that exists: asking again files nothing. The books are "the same" while no entry, document, close, settings or role change has been made; filing a receipt, an audit or an attestation does not change them. - Books that have not declared audits refuse a confirmed audit and every attestation with format_upgrade_pending until the owner's upgrade (books.start says so). Nothing else about them changes. diff --git a/crates/ledger-mcp/handbook/files-in-out.md b/crates/ledger-mcp/handbook/files-in-out.md index 6f220b06..10dc8886 100644 --- a/crates/ledger-mcp/handbook/files-in-out.md +++ b/crates/ledger-mcp/handbook/files-in-out.md @@ -8,7 +8,7 @@ ## Importing a bank CSV (books.import_bank_csv) -A QuickBooks-style bank or credit-card CSV: 3 columns Date, Description, Amount (payments negative), or 4 columns Date, Description, money out, money in (Intuit heads them Credit, Debit). Slash dates must settle month-first or day-first from the file itself or from date_order ("month_first" for mm/dd, "day_first" for dd/mm); ask the human when the tool says the dates read either way. It creates one DRAFT entry per transaction, all or none: the bank account on one side, a categorized offset on the other (the longest matching rule pattern, else default_offset_code). Give the CSV as upload_id: upload it with books.begin_upload purpose import and `wanderbooks upload` (a file never passes through you). Review with books.digest, then post. File the export too (books.file_document category import_source) and pass source_attachment_id: it is linked to the bank account, so the import traces to its source (never to the drafts: a bank export is not a receipt). +A QuickBooks-style bank or credit-card CSV: 3 columns Date, Description, Amount (payments negative), or 4 columns Date, Description, money out, money in (Intuit heads them Credit, Debit). Slash dates must settle month-first or day-first from the file itself or from date_order ("month_first" for mm/dd, "day_first" for dd/mm); ask the human when the tool says the dates read either way. It creates one DRAFT entry per transaction, all or none: the bank account on one side, a categorized offset on the other (the longest matching rule pattern, else default_offset_code). Give the CSV as upload_id: upload it with books.begin_upload purpose import and `wanderbooks upload` (a file never passes through you). Review with books.digest, then post. File the export too (books.file_document category import_source) and pass source_attachment_id: it is linked to the bank account, so the import traces to its source (never to the drafts: a bank export is not a receipt). A bank's description often carries a nine-digit reference, so the file is not refused for one: a number in it that reads as a tax id is kept masked to its last four digits, and the answer says how many values were masked and on which lines (masked_count, masked, masked_note); tell the human, who can check the bank's own statement. A chart CSV (books.import_chart_csv) is refused whole if a cell looks like a tax id; the refusal names its row and column. ## Exporting a report (books.export) diff --git a/crates/ledger-mcp/handbook/parties-and-tins.md b/crates/ledger-mcp/handbook/parties-and-tins.md index bcf77ca0..46fd02e8 100644 --- a/crates/ledger-mcp/handbook/parties-and-tins.md +++ b/crates/ledger-mcp/handbook/parties-and-tins.md @@ -11,7 +11,7 @@ - Every post_entry preview says where the entry stands (party_policy, party_missing, party_suggestions): under the `[books] parties` setting "suggest" (the default), when party_missing, name the likely party to the human and tag it (or add it) before confirming; under "require", posting is refused (party_required) until the entry names a party or is marked as having none (books.set_entry_party with party null and no_party_reason, or draft_entry no_party_reason: only for an entry with truly no counterparty, like a transfer between the company's own accounts); under "off", don't raise it. - Record W-9 facts (books.set_w9) for contractors and landlords before paying them, and W-4 facts (books.set_w4) for employees before their first payroll; name the employee party on every books.run_payroll line. - Never put a full TIN or SSN anywhere in the books, only the last four digits: the engine refuses any nine-digit number in a party field. The full TIN goes only to the encrypted TIN vault, and every member's and every 1099 payee's belongs there: books.set_tin (party, tin, tin_type: ssn, ein, itin; any role, so each member's SSN for their K-1) and books.set_w9 with tin and tin_type for a payee's W-9, and the signed form with w9_upload_id (books.begin_upload purpose w9; never books.file_document or books.attach_receipt: the form shows the TIN). -- A full TIN lives in the vault: keep it out of descriptions, notes, file names and version-history messages. books.get_w9 hands the signed form over (run its download command to save it for the human); books.purge_tin (preview, then confirmed, with a reason) deletes a TIN no longer needed. +- A full TIN lives in the vault: keep it out of descriptions, notes, file names and version-history messages. Every tool refuses a string that looks like a tax id (nine digits standing alone, or an SSN's 3-2-4 or an EIN's 2-7 grouping), whichever field it is in, before anything is written, and says which field; a party's own fields refuse any run of nine digits. A field that is an identifier by nature (an asset's tag or serial number, a vendor's or customer's reference, a payment's reference, an account code, a file name, an instrument's label, where a W-9 is kept) takes nine digits as a number and refuses only the grouped forms. An invoice number, a phone number, a coordinate or a reference of ten digits or more is no tax id. If a bank or vendor reference is nine digits and goes into a memo or a description, write its last four. books.get_w9 hands the signed form over (run its download command to save it for the human); books.purge_tin (preview, then confirmed, with a reason) deletes a TIN no longer needed. - books.parties lists the directory (each party's TIN last four from its TIN or W-9 facts), books.party shows one party with the year's totals, and books.show party opens it in the viewer. Archive (books.update_party archived) parties no longer dealt with; never delete history. ## Tagging an entry with several parties (books.set_entry_party) diff --git a/crates/ledger-mcp/src/access.rs b/crates/ledger-mcp/src/access.rs index 6d0da0a8..1f151b53 100644 --- a/crates/ledger-mcp/src/access.rs +++ b/crates/ledger-mcp/src/access.rs @@ -133,6 +133,9 @@ pub(crate) const STOPPED: &str = "stopped"; pub(crate) const STOPPED_BY_CLOSE: &str = "stopped_by_close"; /// A file's bytes or text came as an argument (D-46). pub(crate) const INLINE_FILE: &str = "inline_file"; +/// A call refused unrun because a string in it looks like a tax id +/// (text_fields.rs). +pub(crate) const TIN_IN_TEXT: &str = "tin_in_text"; /// What a refused call is told when its record couldn't be kept, or a /// call that ran is told instead of its answer (INVARIANT 3). diff --git a/crates/ledger-mcp/src/server.rs b/crates/ledger-mcp/src/server.rs index d4684b8c..21decb2b 100644 --- a/crates/ledger-mcp/src/server.rs +++ b/crates/ledger-mcp/src/server.rs @@ -1588,6 +1588,8 @@ mod next_steps; mod projects; #[path = "tools/prompts.rs"] mod prompts; +#[path = "text_fields.rs"] +mod text_fields; pub use kept::SettingKeyOut; // The tool groups: one file each (plan/served.md 8.2 U0a). A unit adds a @@ -1934,6 +1936,15 @@ impl ServerHandler for BooksServer { } calls::key_problem(request_key.as_ref()) .map(|why| (calls::MISSING_KEY, Ok(tool_error(why)))) + }) + // A string that looks like a tax id isn't run, whatever it was for: + // the vault is where one goes (text_fields.rs INVARIANT 5). + .or_else(|| { + if !calls::writes(&request.name) { + return None; + } + text_fields::refusal(&request.name, request.arguments.as_ref()) + .map(|why| (access::TIN_IN_TEXT, Ok(tool_error(why)))) }); if let Some((code, answer)) = refusal { call.digested(refused_digest(request.arguments.clone()).await); diff --git a/crates/ledger-mcp/src/server_tests.rs b/crates/ledger-mcp/src/server_tests.rs index e64ee358..8f086e43 100644 --- a/crates/ledger-mcp/src/server_tests.rs +++ b/crates/ledger-mcp/src/server_tests.rs @@ -1702,3 +1702,59 @@ fn the_envelope_keeps_what_a_tool_said_and_carries_a_refusal_guard() { assert_eq!(g["code"], "approval_required"); assert_eq!(g["remedy_tool"], "books.approve_entry"); } + +/// text_fields.rs INVARIANT 5 (WB-format-10): a call with a string that +/// looks like a tax id is refused before it runs, in words that name the +/// field and never repeat the number; the books are as they were and the +/// access record says why. A reference that is no tax id goes on to the tool. +#[test] +fn a_call_with_a_tax_id_in_free_text_is_refused_unrun_and_writes_nothing() { + rt().block_on(async { + let s = session("tin-text").await; + let (server, books) = logged("tin-text"); + let key = "key-0123456789"; + let add = |name: &str| { + tool_call( + "books.add_class", + serde_json::json!({"name": name, "request_key": key}), + ) + }; + let (refusal, text) = answer( + server + .call_tool(add("Rondo 000-00-0000"), context(&s.peer, Some(ALL))) + .await, + ) + .unwrap(); + assert!(refusal, "{text}"); + assert!( + text.starts_with("the name of books.add_class looks like it holds a tax id"), + "{text}" + ); + assert!(text.contains("books.set_tin") && text.contains("W-9"), "{text}"); + assert!(!text.contains("000"), "never the number: {text}"); + // A preview is refused too: its text would be shown to a person. + let draft = tool_call( + "books.draft_entry", + serde_json::json!({"date": "2026-11-21", "description": "pay 00-0000000", "request_key": key}), + ); + let (refusal, text) = + answer(server.call_tool(draft, context(&s.peer, Some(ALL))).await).unwrap(); + assert!(refusal && text.contains("the description of books.draft_entry"), "{text}"); + // Nothing was made: no class, no entry. + let projects = tool_call("books.projects", serde_json::json!({})); + let (refusal, text) = + answer(server.call_tool(projects, context(&s.peer, Some(ALL))).await).unwrap(); + assert!(!refusal && !text.contains("Rondo"), "{text}"); + // A reference that is no tax id is not refused for being one. + let (_, text) = answer( + server + .call_tool(add("Rondo 2026-11-0042"), context(&s.peer, Some(ALL))) + .await, + ) + .unwrap(); + assert!(!text.contains("looks like it holds a tax id"), "{text}"); + let log = records(&books); + assert_eq!(log[0], ("books.add_class".into(), refused("tin_in_text"), true)); + assert_eq!(log[1], ("books.draft_entry".into(), refused("tin_in_text"), true)); + }); +} diff --git a/crates/ledger-mcp/src/text_fields.rs b/crates/ledger-mcp/src/text_fields.rs new file mode 100644 index 00000000..5f2efc02 --- /dev/null +++ b/crates/ledger-mcp/src/text_fields.rs @@ -0,0 +1,1442 @@ +//! The text a write tool is given never holds a tax id (BS-partner-2), checked +//! once, before the call runs or writes anything, from one table of every +//! string a write tool takes. +//! +//! ```text +//! GOAL: a full tax id enters the books only through the vault +//! (books.set_tin, books.set_w9). Free text, which most of a write +//! tool's strings are, is checked here for what looks like one, in +//! one place, so a field is never forgotten because its tool never +//! thought of it. +//! SOURCE: BS-partner-2; WB-format-10 (a refused call writes nothing); +//! wanderbooks' CHOICE on BS-partner-2 (the owner, 2026-11-21: +//! shapes on free text, strict on party fields, masking on bank +//! imports), WB-partner-15. +//! INVARIANTS: +//! 1. Every string a write tool's schema has (a field, an array's +//! items, a map's values and keys, any untyped value) is in TABLE +//! under one class, and every row of TABLE is a string the schema +//! has (tests `every_string_a_write_tool_takes_is_in_the_table`, +//! `the_table_names_only_strings_the_tools_take`): a new field fails +//! the build until it is classed. +//! 2. FREE text is refused when it looks like a tax id +//! (`ledger_core::settings::holds_printed_tin`: nine digits standing +//! alone, an SSN's 3-2-4, an EIN's 2-7, with any dash, dot or space +//! between). STRICT text (a party's fields, a name that becomes +//! one, an account name, a recipient) is refused at any run of nine +//! digits (`ledger_core::parties::has_full_tin`), as the engine +//! refuses it. +//! 3. EXEMPT strings are exempt for a reason the class names: the vault's +//! own input, a lookup key for a record the books already hold, an +//! id or digest, an amount, a date, a word from a fixed vocabulary, +//! the last four digits, a bank pattern that is never kept, a link +//! (the engine's link rule reads it), or a structured value the +//! engine's own validation reads (a setting, a convention). +//! 4. A string whose path the table does not know is checked as FREE: +//! the check fails toward refusing. +//! 5. The check is made for any call that can write, preview or not, +//! before the call runs; the refusal says which field, that it looks +//! like a tax id, and where a tax id goes, never the number, and the +//! books are as they were. +//! SCENARIOS: +//! 1. IF books.add_class is given the name `Acme 000-00-0000`: SHOULD +//! refuse in words naming `name`, and write nothing. +//! 2. IF books.create_invoice is given the memo `inv 2026-11-0042`: +//! SHOULD NOT refuse. +//! 3. IF books.set_tin is given a full tax id in `tin`: SHOULD NOT +//! refuse here (the vault is where it goes). +//! ``` + +use std::collections::HashMap; +use std::sync::OnceLock; + +use serde_json::{Map, Value}; + +/// Why a string needs no check for a tax id. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Why { + /// A full tax id as the vault takes it (`books.set_tin`, `books.set_w9`). + Vault, + /// A key that names a record the books hold (an account code, a party, + /// a vendor, an asset, a project): a key nothing matches is refused, + /// and what is kept is the record's, never this text. + Lookup, + /// An id, an upload, a digest or a preview the books made. + Id, + /// A decimal amount, quantity or rate: parsed as a number, never kept + /// as text. + Amount, + /// A date or a month: parsed, never kept as text. + Date, + /// A word from a fixed vocabulary the tool parses; a word outside it is + /// refused. + Enum, + /// The last four digits of a card, account or tax id: exactly four + /// digits are accepted, and nothing else. + Digits, + /// A bank pattern matched against descriptions and never kept. + Pattern, + /// A web address: the engine reads it with the link rule + /// (`holds_printed_tin_in_link`), under which an app listing's id in a + /// path is no tax id. + Link, + /// A structured value (a setting's, a convention's) that the engine's + /// own validation reads, every text of it, with the same shapes + /// (`ledger_core::settings`, `ledger_core::conventions`). + Engine, +} + +/// What the check does with a string. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Class { + /// Free text: refused when it looks like a tax id. + Free, + /// An identifier by nature (an asset tag, a serial number, an invoice or + /// bill number, a payment reference, an account code, a file name, a + /// label, where a paper is kept): refused only in a tax id's printed + /// shapes (an SSN's 3-2-4, an EIN's 2-7); a bare run of nine digits is + /// a legitimate number there (WB-partner-15). + Reference, + /// A party's own field (or a name that becomes one): refused at any + /// run of nine digits. + Strict, + /// Not checked, for the reason named. + Exempt(Why), +} + +const FREE: Class = Class::Free; +const REFERENCE: Class = Class::Reference; +const STRICT: Class = Class::Strict; +const VAULT: Class = Class::Exempt(Why::Vault); +const LOOKUP: Class = Class::Exempt(Why::Lookup); +const ID: Class = Class::Exempt(Why::Id); +const AMOUNT: Class = Class::Exempt(Why::Amount); +const DATE: Class = Class::Exempt(Why::Date); +const ENUM: Class = Class::Exempt(Why::Enum); +const DIGITS: Class = Class::Exempt(Why::Digits); +const PATTERN: Class = Class::Exempt(Why::Pattern); +const LINK: Class = Class::Exempt(Why::Link); +const ENGINE: Class = Class::Exempt(Why::Engine); + +/// Every string a write tool takes, by tool and path: `a.b` for a field, +/// `a[]` for an array's items, `a.*` for a map's values and `a.#key` for +/// its keys. A tool with no string at all is not listed. +pub(crate) const TABLE: &[(&str, &[(&str, Class)])] = &[ + ( + "books.add_account", + &[ + ("account_type", ENUM), + ("code", REFERENCE), + ("deductible_percent", AMOUNT), + ("name", STRICT), + ("tax_category", ENUM), + ], + ), + ("books.add_class", &[("name", FREE)]), + ("books.add_customer", &[("name", STRICT)]), + ( + "books.add_instrument", + &[ + ("account", LOOKUP), + ("kind", ENUM), + ("label", REFERENCE), + ("last4", DIGITS), + ("owner_party", LOOKUP), + ], + ), + ( + "books.add_line", + &[ + ("account", LOOKUP), + ("amount", AMOUNT), + ("class", LOOKUP), + ("foreign_amount", AMOUNT), + ("foreign_currency", ENUM), + ("fx_rate", AMOUNT), + ("side", ENUM), + ], + ), + ("books.add_party", &[("name", STRICT), ("roles[]", ENUM)]), + ( + "books.add_project", + &[ + ("description", FREE), + ("ended_on", DATE), + ("kind", ENUM), + ("links[]", LINK), + ("name", FREE), + ("notes", FREE), + ("party", LOOKUP), + ("started_on", DATE), + ("status", ENUM), + ], + ), + ("books.add_vendor", &[("name", STRICT)]), + ( + "books.annotate_attachment", + &[ + ("fields.amount", AMOUNT), + ("fields.category", FREE), + ("fields.date", DATE), + ("fields.instrument", LOOKUP), + ("fields.payee", FREE), + ("fields.reimbursable_to", FREE), + ("fields.source", FREE), + ("note", FREE), + ], + ), + ( + "books.approve_entry", + &[("approved_on", DATE), ("approver", FREE), ("note", FREE)], + ), + ( + "books.assign_role", + &[("account", LOOKUP), ("role", LOOKUP)], + ), + ( + "books.attach_receipt", + &[ + ("description", FREE), + ("file_name", REFERENCE), + ("link_to[].id", LOOKUP), + ("link_to[].kind", ENUM), + ("mime_type", FREE), + ("upload_id", ID), + ], + ), + ( + "books.attest_period", + &[ + ("method.model", FREE), + ("method.reasoning_effort", FREE), + ("note", FREE), + ("period", DATE), + ], + ), + ( + "books.attest_receipt", + &[ + ("amount", AMOUNT), + ("date", DATE), + ("method.model", FREE), + ("method.reasoning_effort", FREE), + ("note", FREE), + ], + ), + ( + "books.audit", + &[("preview", ID), ("scope", ENUM), ("through", DATE)], + ), + ( + "books.begin_upload", + &[ + ("file_name", REFERENCE), + ("mime_type", FREE), + ("purpose", ENUM), + ("sha256", ID), + ], + ), + ("books.close_period", &[("preview", ID)]), + ("books.consolidate_duplicates", &[("preview", ID)]), + ( + "books.correct_asset", + &[ + ("asset", LOOKUP), + ("cost", AMOUNT), + ("in_service", DATE), + ("in_service_date", DATE), + ("reason", FREE), + ("salvage_value", AMOUNT), + ], + ), + ( + "books.create_bill", + &[ + ("date", DATE), + ("due_date", DATE), + ("duplicate_reason", FREE), + ("lines[].account", LOOKUP), + ("lines[].amount", AMOUNT), + ("lines[].class", LOOKUP), + ("lines[].description", FREE), + ("lines[].quantity", AMOUNT), + ("lines[].unit_price", AMOUNT), + ("memo", FREE), + ("preview", ID), + ("received_on", DATE), + ("terms", FREE), + ("upload_id", ID), + ("vendor", LOOKUP), + ("vendor_ref", REFERENCE), + ], + ), + ( + "books.create_invoice", + &[ + ("bill_to.address", STRICT), + ("bill_to.billing_address", STRICT), + ("bill_to.billing_email", STRICT), + ("bill_to.contact", STRICT), + ("bill_to.email", STRICT), + ("bill_to.name", STRICT), + ("bill_to.phone", STRICT), + ("bill_to.shipping_address", STRICT), + ("customer", LOOKUP), + ("customer_ref", REFERENCE), + ("date", DATE), + ("due_date", DATE), + ("lines[].account", LOOKUP), + ("lines[].amount", AMOUNT), + ("lines[].class", LOOKUP), + ("lines[].description", FREE), + ("lines[].quantity", AMOUNT), + ("lines[].unit_price", AMOUNT), + ("memo", FREE), + ("preview", ID), + ("terms", FREE), + ], + ), + ( + "books.create_period", + &[("end", DATE), ("name", FREE), ("start", DATE)], + ), + ( + "books.create_recurring", + &[ + ("description", FREE), + ("end", DATE), + ("frequency", ENUM), + ("lines[].account", LOOKUP), + ("lines[].amount", AMOUNT), + ("lines[].side", ENUM), + ("start", DATE), + ], + ), + ( + "books.create_schedule", + &[ + ("balance_account", LOOKUP), + ("convention", ENUM), + ("description", FREE), + ("kind", ENUM), + ("pl_account", LOOKUP), + ("start", DATE), + ("total", AMOUNT), + ], + ), + ("books.discard_draft", &[("preview", ID), ("reason", FREE)]), + ( + "books.dispose_asset", + &[ + ("buyer", LOOKUP), + ("date", DATE), + ("gain_loss_account", LOOKUP), + ("preview", ID), + ("proceeds", AMOUNT), + ("proceeds_account", LOOKUP), + ("tag", LOOKUP), + ], + ), + ( + "books.draft_entry", + &[ + ("date", DATE), + ("description", FREE), + ("instrument", LOOKUP), + ("no_party_reason", FREE), + ("parties[].amount", AMOUNT), + ("parties[].party", LOOKUP), + ("parties[].percent", AMOUNT), + ("party", LOOKUP), + ("vendor", LOOKUP), + ], + ), + ( + "books.draft_from_template", + &[ + ("accounts.#key", ENUM), + ("accounts.*", LOOKUP), + ("amount", AMOUNT), + ("date", DATE), + ("description", FREE), + ("no_party_reason", FREE), + ("party", LOOKUP), + ("template_id", LOOKUP), + ], + ), + ( + "books.file_document", + &[ + ("category", ENUM), + ("description", FREE), + ("file_name", REFERENCE), + ("link_to[].id", LOOKUP), + ("link_to[].kind", ENUM), + ("mime_type", FREE), + ("upload_id", ID), + ], + ), + ( + "books.import_bank_csv", + &[ + ("bank_account_code", LOOKUP), + ("date_order", ENUM), + ("default_offset_code", LOOKUP), + ("rules.#key", PATTERN), + ("rules.*", LOOKUP), + ("upload_id", ID), + ], + ), + ("books.import_chart_csv", &[("upload_id", ID)]), + ( + "books.label_asset", + &[ + ("asset", LOOKUP), + ("description", FREE), + ("serial", REFERENCE), + ("tag", REFERENCE), + ], + ), + ( + "books.link_attachment", + &[("subject.id", LOOKUP), ("subject.kind", ENUM)], + ), + ( + "books.mark_sent", + &[ + ("by", FREE), + ("invoice", LOOKUP), + ("kind", ENUM), + ("note", FREE), + ("on", DATE), + ("recipients[]", STRICT), + ("reference", REFERENCE), + ("via", FREE), + ], + ), + ( + "books.pay_bill", + &[ + ("amount", AMOUNT), + ("applications[].amount", AMOUNT), + ("applications[].discount", AMOUNT), + ("applications[].discount_reason", FREE), + ("date", DATE), + ("deposit_to", LOOKUP), + ("fee.account", LOOKUP), + ("fee.amount", AMOUNT), + ("fee.vendor", LOOKUP), + ("instrument", LOOKUP), + ("paid_from", LOOKUP), + ("preview", ID), + ("reference", REFERENCE), + ], + ), + ( + "books.post_entry", + &[("expected_total", AMOUNT), ("preview", ID)], + ), + ( + "books.purge_tin", + &[("party", LOOKUP), ("preview", ID), ("reason", FREE)], + ), + ( + "books.raise_item", + &[ + ("citation", FREE), + ("decided_by", FREE), + ("decided_on", DATE), + ("detail_md", FREE), + ("due", DATE), + ("note", FREE), + ("reason", FREE), + ("title", FREE), + ], + ), + ( + "books.receive_payment", + &[ + ("amount", AMOUNT), + ("applications[].amount", AMOUNT), + ("applications[].discount", AMOUNT), + ("applications[].discount_reason", FREE), + ("date", DATE), + ("deposit_to", LOOKUP), + ("fee.account", LOOKUP), + ("fee.amount", AMOUNT), + ("fee.vendor", LOOKUP), + ("instrument", LOOKUP), + ("paid_from", LOOKUP), + ("preview", ID), + ("reference", REFERENCE), + ], + ), + ( + "books.reconcile", + &[ + ("account", LOOKUP), + ("preview", ID), + ("statement_balance", AMOUNT), + ("statement_date", DATE), + ], + ), + ( + "books.record_decision", + &[ + ("citation", FREE), + ("decided_by[]", FREE), + ("decided_on", DATE), + ("decision_md", FREE), + ("projects[]", LOOKUP), + ("reason", FREE), + ("subject", FREE), + ], + ), + ( + "books.record_payout", + &[ + ("adjustments[].account", LOOKUP), + ("adjustments[].amount", AMOUNT), + ("adjustments[].class", LOOKUP), + ("adjustments[].side", ENUM), + ("date", DATE), + ("deposit", AMOUNT), + ("deposit_account", LOOKUP), + ("description", FREE), + ("fees[].account", LOOKUP), + ("fees[].amount", AMOUNT), + ("fees[].class", LOOKUP), + ("revenue[].account", LOOKUP), + ("revenue[].amount", AMOUNT), + ("revenue[].class", LOOKUP), + ], + ), + ( + "books.record_statement", + &[ + ("account", LOOKUP), + ("closing_balance", AMOUNT), + ("opening_balance", AMOUNT), + ("period_end", DATE), + ("period_start", DATE), + ], + ), + ( + "books.register_asset", + &[ + ("accum_depr_account", LOOKUP), + ("basis_rule", ENUM), + ("basis_source.citation", FREE), + ("basis_source.decided_by", FREE), + ("basis_source.decided_on", DATE), + ("basis_source.note", FREE), + ("contributor_adjusted_basis", AMOUNT), + ("contributor_basis", AMOUNT), + ("cost", AMOUNT), + ("cost_account", LOOKUP), + ("description", FREE), + ("expense_account", LOOKUP), + ("fmv_at_contribution", AMOUNT), + ("in_service_date", DATE), + ("purchase_date", DATE), + ("salvage_value", AMOUNT), + ("sec704c_method", ENUM), + ("serial", REFERENCE), + ("tag", REFERENCE), + ("tax_basis_rule", ENUM), + ], + ), + ( + "books.remit_payroll_taxes", + &[("agency", LOOKUP), ("cash_account", LOOKUP), ("date", DATE)], + ), + ( + "books.rename_account", + &[("account", LOOKUP), ("name", STRICT), ("reason", FREE)], + ), + ( + "books.renumber_account", + &[("account", LOOKUP), ("code", REFERENCE)], + ), + ( + "books.resolve_item", + &[ + ("citation", FREE), + ("decided_by", FREE), + ("decided_on", DATE), + ("note", FREE), + ("resolution", FREE), + ], + ), + ( + "books.retire_convention", + &[ + ("citation", FREE), + ("decided_by", FREE), + ("decided_on", DATE), + ("id", FREE), + ("note", FREE), + ("reason", FREE), + ], + ), + ( + "books.reverse_entry", + &[("date", DATE), ("description", FREE), ("preview", ID)], + ), + ( + "books.review_entry", + &[ + ("method.model", FREE), + ("method.reasoning_effort", FREE), + ("note", FREE), + ], + ), + ("books.run_depreciation", &[("period", DATE)]), + ( + "books.run_payroll", + &[ + ("cash_account", LOOKUP), + ("date", DATE), + ("lines[].employee", LOOKUP), + ("lines[].employee_name", FREE), + ("lines[].federal_withholding", AMOUNT), + ("lines[].gross_pay", AMOUNT), + ("lines[].medicare_employee", AMOUNT), + ("lines[].medicare_employer", AMOUNT), + ("lines[].other_deductions", AMOUNT), + ("lines[].ss_employee", AMOUNT), + ("lines[].ss_employer", AMOUNT), + ("lines[].state_withholding", AMOUNT), + ], + ), + ("books.run_recurring", &[("through", DATE)]), + ("books.run_schedules", &[("preview", ID), ("through", DATE)]), + ( + "books.set_asset_tax_basis", + &[ + ("asset", LOOKUP), + ("basis_source.citation", FREE), + ("basis_source.decided_by", FREE), + ("basis_source.decided_on", DATE), + ("basis_source.note", FREE), + ("contributor_adjusted_basis", AMOUNT), + ("contributor_basis", AMOUNT), + ("fmv_at_contribution", AMOUNT), + ("rule", ENUM), + ("sec704c_method", ENUM), + ], + ), + ( + "books.set_convention", + &[ + ("body_md", FREE), + ("citation", FREE), + ("decided_by", FREE), + ("decided_on", DATE), + ("id", FREE), + ("kind", ENUM), + ("note", FREE), + ("reason", FREE), + ("structured", ENGINE), + ("title", FREE), + ], + ), + ("books.set_draft_state", &[("note", FREE), ("state", ENUM)]), + ("books.set_entry_instrument", &[("instrument", LOOKUP)]), + ( + "books.set_entry_party", + &[ + ("no_party_reason", FREE), + ("parties[].amount", AMOUNT), + ("parties[].party", LOOKUP), + ("parties[].percent", AMOUNT), + ("party", LOOKUP), + ], + ), + ("books.set_entry_vendor", &[("vendor", LOOKUP)]), + ( + "books.set_fx_rate", + &[("currency", ENUM), ("date", DATE), ("rate", AMOUNT)], + ), + ( + "books.set_party_roles", + &[("add[]", ENUM), ("party", LOOKUP), ("remove[]", ENUM)], + ), + ( + "books.set_setting", + &[ + ("changes[].key", ENUM), + ("changes[].value", ENGINE), + ("citation", FREE), + ("decided_by", FREE), + ("decided_on", DATE), + ("note", FREE), + ], + ), + ( + "books.set_tax_category", + &[ + ("account", LOOKUP), + ("category", ENUM), + ("deductible_percent", AMOUNT), + ], + ), + ( + "books.set_tin", + &[("party", LOOKUP), ("tin", VAULT), ("tin_type", ENUM)], + ), + ( + "books.set_vendor_1099", + &[ + ("citation", FREE), + ("decided_by", FREE), + ("decided_on", DATE), + ("effective", DATE), + ("form_1099", ENUM), + ("note", FREE), + ("reason", FREE), + ("reason_kind", ENUM), + ("vendor", LOOKUP), + ], + ), + ( + "books.set_w4", + &[ + ("kept_at", REFERENCE), + ("party", LOOKUP), + ("received_on", DATE), + ("state", FREE), + ], + ), + ( + "books.set_w9", + &[ + ("entity_type", FREE), + ("exempt_payee_code", FREE), + ("fatca_code", FREE), + ("kept_at", REFERENCE), + ("party", LOOKUP), + ("received_on", DATE), + ("tin", VAULT), + ("tin_last4", DIGITS), + ("tin_type", ENUM), + ("w9_file_name", REFERENCE), + ("w9_upload_id", ID), + ], + ), + ( + "books.unlink_attachment", + &[ + ("reason", FREE), + ("subject.id", LOOKUP), + ("subject.kind", ENUM), + ], + ), + ("books.unlink_receipt", &[("reason", FREE)]), + ( + "books.update_party", + &[ + ("address", STRICT), + ("billing_address", STRICT), + ("billing_email", STRICT), + ("contact", STRICT), + ("creditor_of[]", LOOKUP), + ("default_terms_as_customer", STRICT), + ("default_terms_as_vendor", STRICT), + ("display_name", STRICT), + ("email", STRICT), + ("name", STRICT), + ("notes", STRICT), + ("party", LOOKUP), + ("phone", STRICT), + ("shipping_address", STRICT), + ("website", STRICT), + ], + ), + ( + "books.update_project", + &[ + ("description", FREE), + ("ended_on", DATE), + ("kind", ENUM), + ("links[]", LINK), + ("name", FREE), + ("notes", FREE), + ("party", LOOKUP), + ("project", LOOKUP), + ("started_on", DATE), + ("status", ENUM), + ], + ), + ( + "books.void_document", + &[("date", DATE), ("kind", ENUM), ("reason", FREE)], + ), + ("books.void_reconciliation", &[("reason", FREE)]), + ("books.void_statement", &[("reason", FREE)]), + ("books.withdraw_attachment", &[("reason", FREE)]), + ( + "books.write_off_invoice", + &[ + ("amount", AMOUNT), + ("date", DATE), + ("preview", ID), + ("reason", FREE), + ("upload_id", ID), + ], + ), +]; + +/// The table as lookups: tool, then path. +fn classes() -> &'static HashMap<&'static str, HashMap<&'static str, Class>> { + static MAP: OnceLock>> = OnceLock::new(); + MAP.get_or_init(|| { + TABLE + .iter() + .map(|(tool, rows)| (*tool, rows.iter().copied().collect())) + .collect() + }) +} + +/// The class of the string at `path` of `tool`: its row, or FREE +/// (INVARIANT 4). +fn class_of(tool: &str, path: &str) -> Class { + classes() + .get(tool) + .and_then(|t| t.get(path)) + .copied() + .unwrap_or(Class::Free) +} + +/// Whether `text` is refused as `class`. +fn looks_like_a_tax_id(class: Class, text: &str) -> bool { + match class { + Class::Free => ledger_core::settings::holds_printed_tin(text), + Class::Reference => ledger_core::settings::holds_printed_tin_in_reference(text), + Class::Strict => ledger_core::parties::has_full_tin(text), + Class::Exempt(_) => false, + } +} + +/// Why `tool` can't take `args`, in words, when a string in them looks like +/// a tax id (INVARIANTS 2 to 5); None when every string will do. Only a +/// tool that can write is asked (`calls::writes`). +pub(crate) fn refusal(tool: &str, args: Option<&Map>) -> Option { + let mut found = None; + for (k, v) in args?.iter() { + let child = Path::root().field(tool, k); + walk(tool, v, &child, &mut found); + if found.is_some() { + break; + } + } + found +} + +/// Where a value sits: its path as the table spells it, and as a refusal +/// names it: the table's own words with the index of an array's item, never +/// a key the caller chose (a key the table does not know is "an +/// unrecognised field"), so a refusal never echoes the caller's text. +struct Path { + table: String, + shown: String, + /// Under a key the table does not have: no name for it is quoted. + unknown: bool, +} + +impl Path { + fn root() -> Self { + Path { + table: String::new(), + shown: String::new(), + unknown: false, + } + } + + /// The field `key` of the object here: a map's value when the table + /// has the object's `*` row, else a field of its own. + fn field(&self, tool: &str, key: &str) -> Path { + let dot = |base: &str, add: &str| { + if base.is_empty() { + add.to_string() + } else { + format!("{base}.{add}") + } + }; + let rows = classes().get(tool); + let map = dot(&self.table, "*"); + let is_map = rows.is_some_and(|r| r.contains_key(map.as_str())); + let table = if is_map { map } else { dot(&self.table, key) }; + // Known when the table has this path or a row below it. + let known = rows.is_some_and(|r| { + r.keys().any(|row| { + *row == table + || row + .strip_prefix(table.as_str()) + .is_some_and(|rest| rest.starts_with('.') || rest.starts_with("[]")) + }) + }); + Path { + shown: if is_map { + dot(&self.shown, "*") + } else { + dot(&self.shown, if known { key } else { "?" }) + }, + unknown: self.unknown || !known, + table, + } + } + + /// How a refusal names the string here: "the lines[1].description of + /// books.create_invoice", or "an unrecognised field of books.x". + fn named(&self, tool: &str) -> String { + if self.unknown { + format!("an unrecognised field of {tool}") + } else { + format!("the {} of {tool}", self.shown) + } + } +} + +/// Check `v` and everything under it; `found` takes the first refusal. +fn walk(tool: &str, v: &Value, at: &Path, found: &mut Option) { + if found.is_some() { + return; + } + match v { + Value::String(s) => { + if looks_like_a_tax_id(class_of(tool, &at.table), s) { + *found = Some(ledger_core::settings::tin_refusal(&at.named(tool))); + } + } + Value::Array(items) => { + for (i, item) in items.iter().enumerate() { + let child = Path { + table: format!("{}[]", at.table), + shown: format!("{}[{i}]", at.shown), + unknown: at.unknown, + }; + walk(tool, item, &child, found); + } + } + Value::Object(map) => { + // A structured value the engine reads whole. + if class_of(tool, &at.table) == ENGINE { + return; + } + let keys = format!("{}.#key", at.table); + let keyed = classes() + .get(tool) + .is_some_and(|r| r.contains_key(keys.as_str())); + for (k, item) in map { + // A map's key is text too. + if keyed && looks_like_a_tax_id(class_of(tool, &keys), k) { + *found = Some(ledger_core::settings::tin_refusal(&format!( + "a key of {}", + at.named(tool) + ))); + return; + } + let child = at.field(tool, k); + walk(tool, item, &child, found); + } + } + _ => {} + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::server::BooksServer; + use serde_json::json; + + /// Every place in a tool's input schema a string can go, as a path: + /// `a.b` for a field, `a[]` for an array's items, `a.*` for a map's values + /// and `a.#key` for its keys, resolving `$ref`s and following `anyOf`. + /// A node that says nothing of its type (any JSON) is a leaf too. + pub(super) fn schema_leaves(root: &serde_json::Value) -> std::collections::BTreeSet { + use serde_json::Value; + fn walk( + root: &Value, + v: &Value, + path: &str, + out: &mut std::collections::BTreeSet, + depth: usize, + ) { + assert!(depth < 12, "schema nesting too deep at {path}"); + if v.as_bool() == Some(true) { + out.insert(path.to_string()); + return; + } + if let Some(r) = v.get("$ref").and_then(Value::as_str) { + let key = r.rsplit('/').next().unwrap_or_default(); + let target = ["$defs", "definitions"] + .iter() + .find_map(|d| root.get(d).and_then(|d| d.get(key))) + .unwrap_or_else(|| panic!("schema {r} not found")); + walk(root, target, path, out, depth + 1); + return; + } + let mut typed = false; + for k in ["anyOf", "oneOf", "allOf"] { + if let Some(a) = v.get(k).and_then(Value::as_array) { + typed = true; + for x in a { + walk(root, x, path, out, depth + 1); + } + } + } + if v.get("enum").is_some() || v.get("const").is_some() { + typed = true; + out.insert(path.to_string()); + } + let names: Vec<&str> = match v.get("type") { + Some(Value::String(s)) => vec![s.as_str()], + Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).collect(), + _ => vec![], + }; + for n in &names { + typed = true; + match *n { + "string" => { + out.insert(path.to_string()); + } + "array" => { + if let Some(it) = v.get("items") { + walk(root, it, &format!("{path}[]"), out, depth + 1); + } + } + "object" => { + let join = |k: &str| { + if path.is_empty() { + k.to_string() + } else { + format!("{path}.{k}") + } + }; + if let Some(p) = v.get("properties").and_then(Value::as_object) { + for (k, x) in p { + walk(root, x, &join(k), out, depth + 1); + } + } + match v.get("additionalProperties") { + Some(ap) if ap.is_object() || ap.as_bool() == Some(true) => { + out.insert(join("#key")); + walk(root, ap, &join("*"), out, depth + 1); + } + _ => {} + } + } + _ => {} + } + } + if !typed && !path.is_empty() { + // `{}` or only a description: any JSON goes here. + out.insert(path.to_string()); + } + } + let mut out = std::collections::BTreeSet::new(); + walk(root, root, "", &mut out, 0); + out + } + + fn write_tools() -> Vec { + let mut tools: Vec<_> = BooksServer::tool_router() + .list_all() + .into_iter() + .filter(|t| crate::server::calls::writes(&t.name)) + .collect(); + tools.sort_by(|a, b| a.name.cmp(&b.name)); + assert!(tools.len() >= 80, "the write tools: {}", tools.len()); + tools + } + + fn args(v: Value) -> Map { + v.as_object().cloned().expect("an object") + } + + /// INVARIANT 1: a new field is classed or the build fails. + #[test] + fn every_string_a_write_tool_takes_is_in_the_table() { + let mut missing = Vec::new(); + for t in write_tools() { + let root = Value::Object((*t.input_schema).clone()); + for leaf in schema_leaves(&root) { + if !classes() + .get(&*t.name) + .is_some_and(|r| r.contains_key(leaf.as_str())) + { + missing.push(format!(" (\"{}\", &[(\"{leaf}\", ?)]),", t.name)); + } + } + } + assert!( + missing.is_empty(), + "a write tool takes strings that text_fields::TABLE does not class (FREE unless an amount, a date, a lookup key ...):\n{}", + missing.join("\n") + ); + } + + /// INVARIANT 1, the other way: no row for a string no tool takes, no + /// row twice, no tool that cannot write. + #[test] + fn the_table_names_only_strings_the_tools_take() { + let mut leaves = std::collections::BTreeMap::new(); + for t in write_tools() { + let root = Value::Object((*t.input_schema).clone()); + leaves.insert(t.name.to_string(), schema_leaves(&root)); + } + let mut tools = std::collections::BTreeSet::new(); + for (tool, rows) in TABLE { + assert!(tools.insert(*tool), "{tool} is in the table twice"); + let have = leaves + .get(*tool) + .unwrap_or_else(|| panic!("{tool} is no write tool")); + let mut paths = std::collections::BTreeSet::new(); + for (path, _) in *rows { + assert!(paths.insert(*path), "{tool} {path} is in the table twice"); + assert!(have.contains(*path), "{tool} takes no string at {path}"); + } + } + for (tool, have) in &leaves { + assert_eq!( + tools.contains(tool.as_str()), + !have.is_empty(), + "{tool}: listed exactly when it takes a string" + ); + } + } + + /// Every class is used, and the fields a tax id must never reach are + /// FREE or STRICT: the table is no list of exemptions in disguise. + #[test] + fn the_free_text_is_checked_and_the_vault_is_the_only_input_for_a_tin() { + let class = |tool: &str, path: &str| class_of(tool, path); + for (tool, path) in [ + ("books.add_class", "name"), + ("books.add_project", "name"), + ("books.add_project", "notes"), + ("books.draft_entry", "description"), + ("books.reverse_entry", "description"), + ("books.create_invoice", "memo"), + ("books.create_invoice", "lines[].description"), + ("books.create_bill", "duplicate_reason"), + ("books.pay_bill", "applications[].discount_reason"), + ("books.receive_payment", "applications[].discount_reason"), + ("books.attach_receipt", "description"), + ("books.record_decision", "decision_md"), + ("books.set_convention", "body_md"), + ("books.raise_item", "title"), + ("books.attest_period", "note"), + ("books.rename_account", "reason"), + ("books.void_document", "reason"), + ] { + assert_eq!(class(tool, path), Class::Free, "{tool} {path}"); + } + for (tool, path) in [ + ("books.add_customer", "name"), + ("books.add_vendor", "name"), + ("books.add_party", "name"), + ("books.update_party", "notes"), + ("books.create_invoice", "bill_to.address"), + ("books.add_account", "name"), + ("books.mark_sent", "recipients[]"), + ] { + assert_eq!(class(tool, path), Class::Strict, "{tool} {path}"); + } + // Identifiers by nature: a bare nine digits is a number there. + for (tool, path) in [ + ("books.add_account", "code"), + ("books.renumber_account", "code"), + ("books.add_instrument", "label"), + ("books.attach_receipt", "file_name"), + ("books.file_document", "file_name"), + ("books.begin_upload", "file_name"), + ("books.set_w9", "w9_file_name"), + ("books.set_w9", "kept_at"), + ("books.set_w4", "kept_at"), + ("books.create_bill", "vendor_ref"), + ("books.create_invoice", "customer_ref"), + ("books.pay_bill", "reference"), + ("books.receive_payment", "reference"), + ("books.mark_sent", "reference"), + ("books.register_asset", "tag"), + ("books.register_asset", "serial"), + ("books.label_asset", "tag"), + ("books.label_asset", "serial"), + ] { + assert_eq!(class(tool, path), Class::Reference, "{tool} {path}"); + } + let vault: Vec<_> = TABLE + .iter() + .flat_map(|(t, rows)| rows.iter().map(move |(p, c)| (*t, *p, *c))) + .filter(|(_, _, c)| *c == Class::Exempt(Why::Vault)) + .map(|(t, p, _)| (t, p)) + .collect(); + assert_eq!(vault, [("books.set_tin", "tin"), ("books.set_w9", "tin")]); + for why in [ + Why::Vault, + Why::Lookup, + Why::Id, + Why::Amount, + Why::Date, + Why::Enum, + Why::Digits, + Why::Pattern, + Why::Link, + Why::Engine, + ] { + assert!( + TABLE + .iter() + .any(|(_, rows)| rows.iter().any(|(_, c)| *c == Class::Exempt(why))), + "{why:?} is used by no row" + ); + } + } + + /// SCENARIOS 1 to 3, with the shape of the words. + #[test] + fn a_tax_id_in_free_text_is_refused_and_a_reference_is_not() { + let why = refusal( + "books.add_class", + Some(&args(json!({"name": "Acme 000-00-0000"}))), + ) + .expect("refused"); + assert!( + why.starts_with("the name of books.add_class looks like it holds a tax id"), + "{why}" + ); + assert!( + why.contains("books.set_tin") && why.contains("W-9"), + "{why}" + ); + assert!(why.contains("nothing was changed"), "{why}"); + assert!( + !why.contains("0000"), + "the words never repeat the number: {why}" + ); + // The allow-list: an invoice number, a phone, a long reference. + for fine in [ + "inv 2026-11-0042", + "call 801-555-0142", + "ref 202611210042", + "$1,234,567.89 paid 2026-11-21", + ] { + assert_eq!( + refusal("books.create_invoice", Some(&args(json!({"memo": fine})))), + None, + "{fine}" + ); + } + // The vault's own input is no concern of this check. + assert_eq!( + refusal( + "books.set_tin", + Some(&args( + json!({"party": "Acme", "tin": "000-00-0000", "tin_type": "ssn"}) + )) + ), + None + ); + assert_eq!( + refusal( + "books.set_w9", + Some(&args(json!({"party": "Acme", "tin": "00-0000000"}))) + ), + None + ); + // ... but the same number beside it is refused. + assert!( + refusal( + "books.set_tin", + Some(&args(json!({"party": "000-00-0000", "tin": "x"}))) + ) + .is_none(), + "a party is a lookup key: nothing is kept" + ); + assert!( + refusal( + "books.set_w9", + Some(&args(json!({"kept_at": "folder 000-00-0000"}))) + ) + .is_some() + ); + } + + /// A reference field (a tag, a serial, an invoice or payment reference, + /// a code, a file name) takes a bare nine digits and refuses the printed + /// shapes; a free text field refuses both (WB-partner-15). + #[test] + fn a_reference_takes_nine_digits_and_refuses_a_printed_tax_id() { + for (tool, field) in [ + ("books.register_asset", "serial"), + ("books.label_asset", "tag"), + ("books.create_bill", "vendor_ref"), + ("books.create_invoice", "customer_ref"), + ("books.pay_bill", "reference"), + ("books.receive_payment", "reference"), + ("books.mark_sent", "reference"), + ("books.add_account", "code"), + ("books.attach_receipt", "file_name"), + ("books.add_instrument", "label"), + ("books.set_w9", "kept_at"), + ] { + let call = |v: &str| refusal(tool, Some(&args(json!({ field: v })))); + assert_eq!(call("123456789"), None, "{tool} {field}"); + assert_eq!(call("SN 000000000.pdf"), None, "{tool} {field}"); + for shaped in ["000-00-0000", "ein 00-0000000", "000 00 0000"] { + let why = call(shaped).unwrap_or_else(|| panic!("{tool} {field} {shaped}")); + assert!( + why.starts_with(&format!( + "the {field} of {tool} looks like it holds a tax id" + )), + "{why}" + ); + } + } + // The same run in free text is refused. + assert!( + refusal( + "books.create_invoice", + Some(&args(json!({"memo": "123456789"}))) + ) + .is_some() + ); + assert!( + refusal( + "books.pay_bill", + Some(&args( + json!({"applications": [{"discount_reason": "123456789"}]}) + )) + ) + .is_some() + ); + } + + /// A refusal names the table's own field, never a key the caller chose + /// (an object's key is the caller's to pick, and could be the number). + #[test] + fn a_refusal_never_quotes_a_key_the_caller_chose() { + let key = "key-from-the-caller"; + // An unknown field, an unknown key deep under a known one, and one + // under a field the table takes as a map. + for (tool, a) in [ + ("books.add_class", json!({key: "000-00-0000"})), + ("books.add_class", json!({key: {"deeper": ["00-0000000"]}})), + ( + "books.create_invoice", + json!({"bill_to": {key: "000-00-0000"}}), + ), + ( + "books.create_invoice", + json!({"lines": [{"description": "ok"}, {key: "00-0000000"}]}), + ), + ("books.no_such_tool", json!({key: "000-00-0000"})), + ] { + let why = refusal(tool, Some(&args(a.clone()))).unwrap_or_else(|| panic!("{a}")); + assert!(!why.contains(key), "{tool}: {why}"); + assert!( + why.starts_with(&format!( + "an unrecognised field of {tool} looks like it holds a tax id" + )), + "{why}" + ); + } + // A known field is named as the table names it, with an item's index. + let why = refusal( + "books.create_invoice", + Some(&args(json!({"lines": [{"description": "00-0000000"}]}))), + ) + .unwrap(); + assert!( + why.starts_with("the lines[0].description of books.create_invoice"), + "{why}" + ); + } + + /// A nested string is found with its index, whichever depth. + #[test] + fn a_nested_string_is_found_where_it_is() { + let why = refusal( + "books.create_invoice", + Some(&args(json!({ + "customer": "Acme", + "lines": [ + {"description": "ok", "amount": "1.00"}, + {"description": "tax 00-0000000", "amount": "1.00"}, + ], + }))), + ) + .expect("refused"); + assert!( + why.starts_with("the lines[1].description of books.create_invoice"), + "{why}" + ); + // A party's field is strict: ten digits are refused there ... + assert!( + refusal( + "books.update_party", + Some(&args(json!({"notes": "1234567890"}))) + ) + .is_some() + ); + // ... and let through in a memo. + assert!( + refusal( + "books.create_invoice", + Some(&args(json!({"memo": "1234567890"}))) + ) + .is_none() + ); + // A bill-to name is a party field. + assert!( + refusal( + "books.create_invoice", + Some(&args(json!({"bill_to": {"name": "Acme 123 45 6789"}}))) + ) + .is_some() + ); + } + + /// The untyped value of a setting, and a structured convention, are + /// the engine's to read; the maps' keys are text, a pattern is not. + #[test] + fn a_structured_value_is_the_engines_and_a_map_key_is_text() { + let setting = json!({"changes": [{"key": "company.ein", "value": "00-0000000"}]}); + assert_eq!(refusal("books.set_setting", Some(&args(setting))), None); + let note = json!({"changes": [{"key": "x", "value": 1}], "note": "ein 00-0000000"}); + assert!(refusal("books.set_setting", Some(&args(note))).is_some()); + let conv = json!({"structured": {"lines": [{"account": "6000", "text": "00-0000000"}]}}); + assert_eq!(refusal("books.set_convention", Some(&args(conv))), None); + // A bank pattern is never kept; its account is a code. + let rules = json!({"rules": {"payroll 00-0000000": "6000"}}); + assert_eq!(refusal("books.import_bank_csv", Some(&args(rules))), None); + // A template's slot names are a vocabulary the tool parses: no + // check, and a slot nothing matches is refused by the tool. + let slots = json!({"accounts": {"00-0000000": "6000"}}); + assert!(refusal("books.draft_from_template", Some(&args(slots))).is_none()); + } + + /// INVARIANT 4: an unknown tool or field is FREE text. + #[test] + fn what_the_table_does_not_know_is_checked_as_free_text() { + assert!(refusal("books.no_such", Some(&args(json!({"x": "000-00-0000"})))).is_some()); + assert!( + refusal( + "books.add_class", + Some(&args(json!({"later": {"deep": ["00-0000000"]}}))) + ) + .is_some() + ); + assert_eq!(refusal("books.add_class", None), None); + assert_eq!( + refusal( + "books.add_class", + Some(&args(json!({"name": 5, "x": null}))) + ), + None + ); + } +} diff --git a/crates/ledger-mcp/src/tools/chart.rs b/crates/ledger-mcp/src/tools/chart.rs index 7b0f8b57..4073b7aa 100644 --- a/crates/ledger-mcp/src/tools/chart.rs +++ b/crates/ledger-mcp/src/tools/chart.rs @@ -371,7 +371,7 @@ impl BooksServer { #[tool( name = "books.import_chart_csv", title = "Import a chart of accounts", - description = "Import a chart of accounts from CSV (header: code,name,type,parent_code,tax_category; the last is optional), as upload_id: upload it with books.begin_upload purpose import and `wanderbooks upload` (a file never passes through you). Types: asset, liability, equity, revenue, expense. Parents must come before children. Fails on the first bad row; nothing is half-imported. A revenue or expense row without a tax_category is listed in warnings, or, under policy.require_tax_category = refuse, refuses the file.", + description = "Import a chart of accounts from CSV (header: code,name,type,parent_code,tax_category; the last is optional), as upload_id: upload it with books.begin_upload purpose import and `wanderbooks upload` (a file never passes through you). Types: asset, liability, equity, revenue, expense. Parents must come before children. Fails on the first bad row, a cell that looks like a tax id included (it names the row and column); nothing is half-imported. A revenue or expense row without a tax_category is listed in warnings, or, under policy.require_tax_category = refuse, refuses the file.", annotations( read_only_hint = false, destructive_hint = false, diff --git a/crates/ledger-mcp/src/tools/documents.rs b/crates/ledger-mcp/src/tools/documents.rs index 3b615d72..daa98659 100644 --- a/crates/ledger-mcp/src/tools/documents.rs +++ b/crates/ledger-mcp/src/tools/documents.rs @@ -474,10 +474,10 @@ impl BooksServer { "due_date, or terms, or the customer's default terms, or invoicing.default_terms", )?; if let Some(r) = &p.customer_ref { - ledger_core::parties::check_text("the customer reference", r)?; + ledger_core::parties::check_reference_note("the customer reference", r)?; } if let Some(m) = &p.memo { - ledger_core::parties::check_text("the memo", m)?; + ledger_core::parties::check_note("the memo", m)?; } let settings = self.settings(); let fields = arap::InvoiceFields { @@ -616,10 +616,10 @@ impl BooksServer { ); } if let Some(m) = &p.memo { - ledger_core::parties::check_text("the memo", m)?; + ledger_core::parties::check_note("the memo", m)?; } if let Some(r) = &p.duplicate_reason { - ledger_core::parties::check_text("the duplicate reason", r)?; + ledger_core::parties::check_note("the duplicate reason", r)?; } // The file is taken before anything is written: an upload is used // up only by the call that files it (files.rs INVARIANT 1). diff --git a/crates/ledger-mcp/src/tools/entries.rs b/crates/ledger-mcp/src/tools/entries.rs index 1d41d459..2ad348ac 100644 --- a/crates/ledger-mcp/src/tools/entries.rs +++ b/crates/ledger-mcp/src/tools/entries.rs @@ -709,7 +709,7 @@ impl BooksServer { #[tool( name = "books.import_bank_csv", title = "Import a bank CSV as drafts", - description = "Import a bank or card CSV (Date, Description, Amount; or Date, Description, money out, money in) as one DRAFT entry per transaction, all or none: the bank account on one side, a categorized offset on the other. Give the CSV as upload_id (books.begin_upload purpose import; a file never passes through you). Ambiguous slash dates need date_order. Review with books.digest, then post. Also file the export (books.file_document category import_source) and pass source_attachment_id. Details in books.handbook section files-in-out.", + description = "Import a bank or card CSV (Date, Description, Amount; or Date, Description, money out, money in) as one DRAFT entry per transaction, all or none: the bank account on one side, a categorized offset on the other. Give the CSV as upload_id (books.begin_upload purpose import; a file never passes through you). Ambiguous slash dates need date_order. A description holding a number that reads as a tax id is kept masked to its last four digits (masked_count, masked). Review with books.digest, then post. Also file the export (books.file_document category import_source) and pass source_attachment_id. Details in books.handbook section files-in-out.", annotations( read_only_hint = false, destructive_hint = false, @@ -732,7 +732,14 @@ 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, + as_written, + } = ledger_import::parse_bank_csv_masked(&csv, order).map_err(|e| e.to_string())?; let mut store = self.lock()?; let bank = store .ledger() @@ -788,8 +795,10 @@ impl BooksServer { // can't become a draft (a date in a closed period, say) refuses the // file instead of leaving the ones before it behind. let mut scratch = store.ledger().clone(); - for txn in &txns { - let (offset_id, _) = offset_for(&txn.description); + for (txn, written) in txns.iter().zip(&as_written) { + // A rule reads the bank's own words, a nine-digit reference + // in them included; what is kept is the masked text. + let (offset_id, _) = offset_for(written); let amount = Money::new(txn.amount.abs(), base); let (bank_side, offset_side) = if txn.amount > Decimal::ZERO { (Side::Debit, Side::Credit) @@ -806,8 +815,8 @@ impl BooksServer { // Rehearsed whole: the upload is used up as the writing begins. files::filed(claim); let mut imported = Vec::new(); - for txn in txns { - let (offset_id, offset_code) = offset_for(&txn.description); + for (txn, written) in txns.into_iter().zip(&as_written) { + let (offset_id, offset_code) = offset_for(written); let amount = Money::new(txn.amount.abs(), store.ledger().base_currency()); let entry_id = store .create_entry(txn.date, &format!("Bank import — {}", txn.description)) @@ -838,11 +847,34 @@ impl BooksServer { .map_err(|e| e.to_string())?; } let count = imported.len(); + let masked_count: usize = masked + .iter() + .fold(0, |n: usize, m| n.saturating_add(m.numbers)); + 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/tools/parties.rs b/crates/ledger-mcp/src/tools/parties.rs index bb5f03a1..dcf322b6 100644 --- a/crates/ledger-mcp/src/tools/parties.rs +++ b/crates/ledger-mcp/src/tools/parties.rs @@ -1550,7 +1550,7 @@ impl BooksServer { if r.trim().is_empty() { return Err("say why the entry has no counterparty".into()); } - ledger_core::parties::check_text("reason", r)?; + ledger_core::parties::check_note("the reason", r)?; store .set_entry_party(p.entry_id, None) .map_err(|e| e.to_string())?; 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..107e7887 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,84 @@ fn found(code: &'static str, subject: Subject, message: String) -> Finding { } } +/// How the audit reads one journal field for a tax id. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum TextClass { + /// Free words: nine digits standing alone, an SSN's 3-2-4 or an EIN's + /// 2-7 are found. + Free, + /// A reference (a tag, a serial, an invoice number, a file name, an + /// account code): only the grouped shapes are found, a bare nine digits + /// being a legitimate number there (WB-partner-15). + Reference, +} + +/// The journal fields that hold words someone wrote (never an id, a digest +/// or an amount) and how each is read: what [`Store::integrity_findings`] +/// reads for a tax id. +const TEXT_KEYS: &[(&str, TextClass)] = &[ + ("description", TextClass::Free), + ("memo", TextClass::Free), + ("note", TextClass::Free), + ("notes", TextClass::Free), + ("reason", TextClass::Free), + ("name", TextClass::Free), + ("label", TextClass::Reference), + ("title", TextClass::Free), + ("citation", TextClass::Free), + ("decided_by", TextClass::Free), + ("detail", TextClass::Free), + ("detail_md", TextClass::Free), + ("resolution", TextClass::Free), + ("decision_md", TextClass::Free), + ("body_md", TextClass::Free), + ("subject", TextClass::Free), + ("reference", TextClass::Reference), + ("customer_ref", TextClass::Reference), + ("vendor_ref", TextClass::Reference), + ("duplicate_reason", TextClass::Free), + ("no_party_reason", TextClass::Free), + ("payee", TextClass::Free), + ("source", TextClass::Free), + ("reimbursable_to", TextClass::Free), + ("file_name", TextClass::Reference), + ("serial", TextClass::Reference), + ("tag", TextClass::Reference), + ("code", TextClass::Reference), + ("employee_name", TextClass::Free), + ("display_name", TextClass::Free), + ("address", TextClass::Free), + ("contact", TextClass::Free), + ("kept_at", TextClass::Reference), + ("approver", TextClass::Free), +]; + +/// Every text field of `v` named by [`TEXT_KEYS`], as (its key, how it is +/// read, 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, TextClass, String)>) { + match v { + Value::Object(m) => { + for (k, x) in m { + if let Some((_, class)) = TEXT_KEYS.iter().find(|(key, _)| *key == k.as_str()) { + match x { + Value::String(s) => out.push((k.clone(), *class, s.clone())), + Value::Array(a) => out.extend( + a.iter() + .filter_map(Value::as_str) + .map(|s| (k.clone(), *class, 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)] @@ -304,6 +387,20 @@ pub struct Claim { } impl Claim { + /// The words a claim keeps (the note, the model's name) hold no tax id + /// (BS-partner-2): checked before anything is journaled. + fn check(&self) -> Result<(), StoreError> { + for (field, text) in [ + ("the note", self.note.as_deref()), + ("the model", self.method.model.as_deref()), + ] { + if let Some(t) = text { + ledger_core::LedgerError::free_text(field, t)?; + } + } + Ok(()) + } + fn into_attestation(self, what: Attested) -> Attestation { Attestation { seq: 0, @@ -436,6 +533,51 @@ 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, class, text) in fields { + let looks = match class { + TextClass::Free => ledger_core::settings::holds_printed_tin(&text), + TextClass::Reference => { + ledger_core::settings::holds_printed_tin_in_reference(&text) + } + }; + if looks { + 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 } @@ -624,6 +766,7 @@ impl Store { date: NaiveDate, claim: Claim, ) -> Result { + claim.check()?; self.ensure_feature(crate::format::AUDITS)?; let entry = self .ledger @@ -668,6 +811,7 @@ impl Store { /// Record that an entry was reviewed whole (`entry.reviewed`). pub fn review_entry(&mut self, entry_id: u64, claim: Claim) -> Result { + claim.check()?; self.ensure_feature(crate::format::AUDITS)?; let entry = self .ledger @@ -710,6 +854,7 @@ impl Store { period_id: u64, claim: Claim, ) -> Result<(Attestation, AuditRun), StoreError> { + claim.check()?; self.ensure_feature(crate::format::AUDITS)?; let run = self.run_for_period(period_id)?; let a = self.journal_attestation( diff --git a/crates/ledger-store/src/store.rs b/crates/ledger-store/src/store.rs index c2791b03..56417d0b 100644 --- a/crates/ledger-store/src/store.rs +++ b/crates/ledger-store/src/store.rs @@ -1350,16 +1350,19 @@ impl Store { ) -> Result { let (default_description, lines) = self.ledger.template_lines(template_id, amount, slots)?; - let description = description - .map(str::to_string) - .or(default_description) - .unwrap_or_else(|| { + // The caller's words are checked as they come; a description the + // template or its convention's title gives is stored text, masked + // where an older version let it hold a tax id's shape. + let description = description.map(str::to_string).unwrap_or_else(|| { + let stored = default_description.unwrap_or_else(|| { self.ledger .conventions() .convention(template_id) .map(|c| c.title.clone()) .unwrap_or_default() }); + ledger_core::settings::mask_printed_tins(&stored).into_owned() + }); self.rehearse(|l| { let e = l.try_create_entry(date, &description)?; for (account, side, amount) in &lines { @@ -1801,6 +1804,7 @@ impl Store { // Every refusal before the journal: a journaled reversal the engine // then refuses could never be replayed, and the books would not open. self.check_reverse_entry(entry, date)?; + LedgerError::free_text("the reversal's description", description)?; let new_id = self.ledger.next_entry_id(); let flipped: Vec = orig.lines().iter().map(flip_line_json).collect(); // Reversals journal a single entry.reversed line (no separate @@ -2458,7 +2462,13 @@ impl Store { }); } let amount = due.amount; - let description = format!("Depreciation — {} — {period}", asset.description); + // Composed from the asset's own words, which the books may hold + // from before free text was read for a tax id's shape: a number + // that reads as one is masked, never refused (WB-partner-15). + let description = format!( + "Depreciation — {} — {period}", + ledger_core::settings::mask_printed_tins(&asset.description) + ); let money = Money::new(amount, self.base_currency); // Every refusal before the first journaled line: the entry on a // copy (and that it is the period's run, no more and no less: @@ -2884,7 +2894,8 @@ impl Store { ( format!( "Depreciation — {} — {} (final)", - asset.description, preview.period + ledger_core::settings::mask_printed_tins(&asset.description), + preview.period ), vec![ ( @@ -2901,7 +2912,11 @@ impl Store { ) }); let disposal = ( - format!("Disposal — {} — {}", asset.description, date), + format!( + "Disposal — {} — {}", + ledger_core::settings::mask_printed_tins(&asset.description), + date + ), Self::disposal_lines( &asset, &preview, @@ -3585,8 +3600,14 @@ impl Store { entry_id, "invoice entry diverged from journal" ); + // The copy's name is composed from the invoice's number (a prefix + // the books' settings give, then digits): a number that reads as a + // tax id's printed shape is masked, never refused (WB-partner-15). let file_name = match &fields.number { - Some(n) => format!("{n}.pdf"), + Some(n) => format!( + "{}.pdf", + ledger_core::settings::mask_printed_tins_in_reference(n) + ), None => format!("Invoice {live}.pdf"), }; // The entry's and the invoice's lines apply first: they were @@ -4172,6 +4193,20 @@ impl Store { )); } } + // The file's words, as `Self::attach_receipt` reads them, before + // the write-off's entry is journaled (a refusal after it would + // leave the entry without its evidence). + if let WriteOffEvidence::File { + file_name, + description, + .. + } = evidence + { + LedgerError::reference_text("the file name", file_name)?; + if let Some(d) = description { + LedgerError::free_text("the description", d)?; + } + } if let WriteOffEvidence::File { bytes, .. } = evidence && let Some(existing) = self.live_attachment_with_sha(&sha256_hex(bytes))? { @@ -4754,6 +4789,10 @@ impl Store { bytes: &[u8], description: Option<&str>, ) -> Result<(u64, String, bool), StoreError> { + LedgerError::reference_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", @@ -4794,6 +4833,10 @@ impl Store { bytes: &[u8], description: Option<&str>, ) -> Result<(u64, String, bool), StoreError> { + LedgerError::reference_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, @@ -5691,6 +5734,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)); @@ -5759,6 +5803,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())); @@ -5935,6 +5980,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 @@ -6064,6 +6110,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" @@ -6214,6 +6261,7 @@ impl Store { if reason.is_empty() { return Err(StoreError::ReasonRequired); } + LedgerError::free_text("the reason", reason)?; let r = self .reconciliations(None)? .into_iter() @@ -6813,9 +6861,11 @@ impl Store { .conn .prepare("SELECT asset_id, tag FROM asset_tags_log ORDER BY seq")?; let tags = tstmt.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)))?; + // History is read, not asked for: a tag or a serial number the books + // hold reads back whatever shape it has (BS-entry-4; WB-partner-15). for t in tags { let (id, tag) = t?; - ledger.set_asset_tag(id as u64, &tag)?; + ledger_core::parties::replaying(|| ledger.set_asset_tag(id as u64, &tag))?; } let mut sstmt = self .conn @@ -6823,7 +6873,7 @@ impl Store { let serials = sstmt.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)))?; for row in serials { let (id, serial) = row?; - ledger.set_asset_serial(id as u64, Some(&serial))?; + ledger_core::parties::replaying(|| ledger.set_asset_serial(id as u64, Some(&serial)))?; } // Basis records: a pre-P3 one (no value at contribution) as its // event replays, a newer one with its facts. diff --git a/crates/ledger-store/tests/audit.rs b/crates/ledger-store/tests/audit.rs index fb97f36b..9bf0740d 100644 --- a/crates/ledger-store/tests/audit.rs +++ b/crates/ledger-store/tests/audit.rs @@ -301,6 +301,77 @@ fn stale_head_period_attestation_refused() { s.verify().unwrap(); } +/// BS-partner-2 (WB-partner-15): the store's own texts (a file's name and +/// description, the reasons for unlinking, withdrawing and voiding, an +/// attestation's note, an entry's description) meet the one free-text check +/// before anything is journaled, whoever calls. +#[test] +fn the_store_refuses_text_that_looks_like_a_tax_id_and_journals_nothing() { + use ledger_core::LedgerError; + let dir = test_dir("tin-text"); + let (mut s, fx) = books(&dir, None); + let tin = "000-00-0000"; + let refused = |r: Result<(), StoreError>, what: &str| match r { + Err(StoreError::Ledger(LedgerError::FreeTextHoldsTin(why))) => { + assert!(!why.contains("0000"), "{what}: never the number: {why}"); + } + other => panic!("{what}: expected a refusal for the tax id, got {other:?}"), + }; + let (att, _, _) = s + .attach_receipt(Some(fx.entry), "r.txt", "text/plain", b"paper 40.00", None) + .unwrap(); + let head = s.head(); + refused( + s.attach_receipt( + None, + "s.txt", + "text/plain", + b"other", + Some(&format!("paid {tin}")), + ) + .map(drop), + "a description", + ); + refused( + s.attach_receipt(None, &format!("w9 {tin}.txt"), "text/plain", b"other", None) + .map(drop), + "a file name", + ); + refused( + s.file_document( + "tax", + "t.txt", + "text/plain", + b"doc", + Some(&format!("ein {tin}")), + ) + .map(drop), + "a document's description", + ); + refused( + s.unlink_receipt(att, &format!("dup {tin}")).map(drop), + "an unlink reason", + ); + refused( + s.withdraw_attachment(att, &format!("dup {tin}")), + "a withdraw reason", + ); + refused( + s.create_entry(d(2, 1), &format!("x {tin}")).map(drop), + "an entry description", + ); + refused( + s.reverse_entry(fx.entry, d(2, 1), &format!("x {tin}")) + .map(drop), + "a reversal", + ); + let mut c = claim("high"); + c.note = Some(format!("see {tin}")); + refused(s.review_entry(fx.entry, c).map(drop), "an attestation note"); + assert_eq!(s.head(), head, "a refusal journals nothing"); + s.verify().unwrap(); +} + /// The integrity table: each code seeded alone. #[test] fn integrity_detects_each_seeded_defect() { @@ -362,6 +433,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"), diff --git a/crates/ledger-store/tests/free_text_old_books.rs b/crates/ledger-store/tests/free_text_old_books.rs new file mode 100644 index 00000000..e54f955b --- /dev/null +++ b/crates/ledger-store/tests/free_text_old_books.rs @@ -0,0 +1,288 @@ +//! Text the books already hold is never refused when the program writes it +//! again (BS-partner-2, WB-partner-15; BS-entry-4): an asset an earlier +//! version took, whose description holds a number that reads as a tax id, +//! still depreciates and is still disposed of; the lines the program +//! composes from it hold the masked form. And a payment's reference of +//! nine digits is kept, shown masked in the entry's description, and is no +//! finding of the audit. + +use chrono::NaiveDate; +use ledger_core::{AccountType, Currency, Money}; +use ledger_store::{JOURNAL_FILE, JournalWriter, Store}; +use rust_decimal::Decimal; +use serde_json::json; +use tempfile::tempdir; + +fn usd(amount: &str) -> Money { + Money::new(amount.parse().unwrap(), Currency::USD) +} + +fn date(y: i32, m: u32, d: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(y, m, d).unwrap() +} + +struct Accounts { + cost: u64, + accum: u64, + expense: u64, + bank: u64, + gain: u64, +} + +fn accounts(store: &mut Store) -> Accounts { + let mut add = |code: &str, name: &str, t: AccountType| { + store.add_account(code, name, t, None, false).unwrap() + }; + Accounts { + cost: add("1500", "Equipment", AccountType::Asset), + accum: add("1501", "Accumulated Depreciation", AccountType::Asset), + expense: add("6100", "Depreciation Expense", AccountType::Expense), + bank: add("1000", "Bank", AccountType::Asset), + gain: add("4900", "Gain on Disposal", AccountType::Revenue), + } +} + +/// Books with two assets an earlier version took: one whose description +/// holds a bare run of nine digits (a serial number), one an SSN's shape. +/// They are written to the journal as that version wrote them: the engine +/// refuses such a description now, whoever asks. +fn old_books() -> (tempfile::TempDir, Store, Accounts, [u64; 2]) { + let dir = tempdir().unwrap(); + let mut store = Store::create(dir.path(), Currency::USD).unwrap(); + let a = accounts(&mut store); + let first = store.ledger().next_asset_id(); + drop(store); + let mut w = JournalWriter::open(&dir.path().join(JOURNAL_FILE)).unwrap(); + for (id, description) in [ + (first, "MacBook SN 000000000"), + (first + 1, "Laptop 000-00-0000 kit"), + ] { + w.append( + "asset.registered", + json!({ + "id": id, + "description": description, + "purchase_date": "2026-01-15", + "cost": {"amount": "1200.00", "currency": "USD"}, + "salvage_value": {"amount": "0", "currency": "USD"}, + "useful_life_months": 12, + "method": "straight_line", + "cost_account": a.cost, + "accum_depr_account": a.accum, + "expense_account": a.expense, + }), + ) + .unwrap(); + } + drop(w); + let store = Store::open(dir.path()).expect("books holding such an asset open"); + store.verify().expect("and verify"); + (dir, store, a, [first, first + 1]) +} + +/// An asset whose description holds the shape depreciates: the entry is +/// written, its description holds the shape masked, and the books verify. +#[test] +fn an_old_asset_still_depreciates() { + let (_dir, mut store, _, [bare, grouped]) = old_books(); + let run = store.run_depreciation(bare, "2026-02").unwrap(); + let entry = store.ledger().get_entry(run.entry_id.unwrap()).unwrap(); + assert_eq!( + entry.description(), + "Depreciation — MacBook SN \u{2022}\u{2022}\u{2022}\u{2022}\u{2022}0000 — 2026-02" + ); + let run = store.run_depreciation(grouped, "2026-02").unwrap(); + let entry = store.ledger().get_entry(run.entry_id.unwrap()).unwrap(); + assert_eq!( + entry.description(), + "Depreciation — Laptop \u{2022}\u{2022}\u{2022}-\u{2022}\u{2022}-0000 kit — 2026-02" + ); + store.verify().unwrap(); +} + +/// ... and is disposed of: the final depreciation's entry and the +/// disposal's both hold the masked form. +#[test] +fn an_old_asset_is_still_disposed_of() { + let (dir, mut store, a, [bare, grouped]) = old_books(); + for (id, masked) in [ + ( + bare, + "MacBook SN \u{2022}\u{2022}\u{2022}\u{2022}\u{2022}0000", + ), + ( + grouped, + "Laptop \u{2022}\u{2022}\u{2022}-\u{2022}\u{2022}-0000 kit", + ), + ] { + store.run_depreciation(id, "2026-02").unwrap(); + let on = date(2026, 3, 10); + let disposal = store + .dispose_asset(id, on, usd("100"), a.bank, a.gain) + .unwrap(); + let disposal = store.ledger().get_entry(disposal).unwrap(); + assert_eq!( + disposal.description(), + format!("Disposal — {masked} — {on}") + ); + // The final depreciation is the entry just before it. + let final_run = store.ledger().get_entry(disposal.id() - 1).unwrap(); + assert_eq!( + final_run.description(), + format!("Depreciation — {masked} — 2026-03 (final)") + ); + assert!(matches!( + store.ledger().get_asset(id).unwrap().status, + ledger_core::AssetStatus::Disposed { .. } + )); + } + store.verify().unwrap(); + // The books open again, as they were written. + drop(store); + let again = Store::open(dir.path()).unwrap(); + again.verify().unwrap(); + assert_eq!( + again.ledger().get_asset(bare).unwrap().description, + "MacBook SN 000000000" + ); +} + +/// The text of such an asset is not repeated in a line the audit would +/// then name: the lines the program wrote hold no number that reads as a +/// tax id, so the audit names only the line an earlier version wrote. +#[test] +fn what_the_program_writes_again_is_no_finding() { + let (_dir, mut store, a, [bare, _]) = old_books(); + store.run_depreciation(bare, "2026-02").unwrap(); + store + .dispose_asset(bare, date(2026, 3, 10), usd("100"), a.bank, a.gain) + .unwrap(); + let found: Vec = store + .integrity_findings() + .into_iter() + .filter(|f| f.code == "tax_id_in_journal") + .map(|f| f.message) + .collect(); + // Two lines are the earlier version's (the two assets, whose + // description the journal holds as written); none is the program's. + assert_eq!(found.len(), 2, "{found:?}"); + assert!( + found.iter().all(|m| m.contains("(asset.registered)")), + "{found:?}" + ); +} + +/// A payment reference of nine digits is a check or confirmation number: +/// kept whole as the reference, shown masked in the entry's description, +/// and no finding of the audit; a printed tax id is refused before +/// anything is journaled. +#[test] +fn a_nine_digit_payment_reference_is_kept_and_is_no_finding() { + let dir = tempdir().unwrap(); + let mut store = Store::create(dir.path(), Currency::USD).unwrap(); + let a = accounts(&mut store); + let customer = store.add_customer("Acme").unwrap(); + let invoice = store + .create_invoice( + customer, + date(2026, 3, 1), + date(2026, 3, 31), + vec![ledger_core::arap::DocumentLine { + description: "work".into(), + amount: Decimal::from(100), + class_id: None, + account: None, + quantity: None, + unit_price: None, + }], + ) + .unwrap(); + let head = store.head(); + let pay = |store: &mut Store, reference: &str| { + store.receive_payment_with( + invoice, + date(2026, 3, 5), + Decimal::from(10), + a.bank, + &ledger_core::PaymentDetails { + instrument: None, + reference: Some(reference.into()), + }, + ) + }; + assert!(pay(&mut store, "000-00-0000").is_err()); + assert_eq!(store.head(), head, "a refusal journals nothing"); + let entry = pay(&mut store, "123456789").unwrap(); + assert_eq!( + store.ledger().get_entry(entry).unwrap().description(), + "Payment on invoice 1 (ref \u{2022}\u{2022}\u{2022}\u{2022}\u{2022}6789)" + ); + let found: Vec = store + .integrity_findings() + .into_iter() + .filter(|f| f.code == "tax_id_in_journal") + .map(|f| f.message) + .collect(); + assert!(found.is_empty(), "{found:?}"); + store.verify().unwrap(); +} + +/// The audit reads each journal field as its class: a reference (a tag, a +/// serial, a file name, an invoice number) may be nine digits, free words +/// may not, and a printed shape is a finding in either. +#[test] +fn the_audit_reads_a_reference_as_a_reference() { + let dir = tempdir().unwrap(); + let mut store = Store::create(dir.path(), Currency::USD).unwrap(); + let a = accounts(&mut store); + let asset = store + .register_asset(ledger_core::NewAsset { + description: "Van".into(), + in_service_date: date(2026, 1, 15), + cost: usd("1200"), + salvage_value: usd("0"), + useful_life_months: 12, + cost_account: a.cost, + accum_depr_account: a.accum, + expense_account: a.expense, + }) + .unwrap(); + let next = store.ledger().next_entry_id(); + drop(store); + let mut w = JournalWriter::open(&dir.path().join(JOURNAL_FILE)).unwrap(); + // Nine digits as a tag: a reference. As the words of an entry: a finding. + w.append( + "asset.tagged", + json!({"asset_id": asset, "tag": "123456789", "previous_tag": null}), + ) + .unwrap(); + w.append( + "entry.created", + json!({"id": next, "date": "2026-03-01", "description": "paid 123456789"}), + ) + .unwrap(); + // A printed shape in a tag is a finding too. + w.append( + "asset.tagged", + json!({"asset_id": asset, "tag": "T-000-00-0000", "previous_tag": "123456789"}), + ) + .unwrap(); + drop(w); + let store = Store::open(dir.path()).unwrap(); + store.verify().unwrap(); + let fields: Vec = store + .integrity_findings() + .into_iter() + .filter(|f| f.code == "tax_id_in_journal") + .map(|f| f.message) + .collect(); + assert_eq!(fields.len(), 2, "{fields:?}"); + assert!( + fields[0].contains("(entry.created)") && fields[0].contains("`description`"), + "{fields:?}" + ); + assert!( + fields[1].contains("(asset.tagged)") && fields[1].contains("`tag`"), + "{fields:?}" + ); +} diff --git a/docs/mcp-interface.md b/docs/mcp-interface.md index 41736caf..dc4b85de 100644 --- a/docs/mcp-interface.md +++ b/docs/mcp-interface.md @@ -763,6 +763,42 @@ What the books keep of a call, and what a repeat is told: counts, the books server stopped to protect the books, and sending the call again with the same key answers what it answered and changes nothing. +**No tax id in a tool's text** (BS-partner-2, WB-partner-15). Before a write +tool runs (a preview included), every string in its arguments is checked once, +from one table of every string each write tool takes (`text_fields.rs`; 423 +strings in 78 tools; 109 free text, 18 reference, 27 party field, 2 for the +vault, the rest exempt): *free text* (memos, notes, reasons, descriptions, +names of classes, projects and periods, a receipt's description and +annotations, a discount's reason, a decision's or an item's words) is refused +when it looks like a tax id (nine digits standing alone, an SSN's 3-2-4 or an +EIN's 2-7 grouping, joined by any dash or space, or by a dot between all of +an SSN's groups; a line break is a space and zero-width characters are not +counted); a *reference field*, an identifier by nature (an asset's `tag` and +`serial`, a bill's `vendor_ref`, an invoice's `customer_ref`, the `reference` +of `pay_bill`, `receive_payment` and `mark_sent`, an account's `code`, a +`file_name`, an instrument's `label`, where a W-9 or W-4 is `kept_at`), is +refused only for the printed 3-2-4 and 2-7 shapes and may hold a bare nine +digits, a serial or a check number (the owner's choice of 2026-11-21 as the +lead decided it within it); a *party's own field* +(a party's or a customer's or vendor's name, the bill-to details, a +recipient, an account name) when it holds any run of nine digits; a string +that is a lookup key, an id, an amount, a date, a word from a fixed +vocabulary, the last four digits, a bank pattern or a link is exempt, and +`set_tin` and `set_w9` take their `tin` (the vault's input) unread. A +setting's value or a convention's structured body is read by the engine's own +checks (`company.ein` and the `ach` and `wire` routing lines are the only +exceptions). An invoice number, a phone number, a reference of ten digits or +more, an amount, a decimal (`47.6062095`) and a date, even followed by a +reference (`2026-11-21 0001234`), are no tax id. The refusal is in words, names +the table's own field ("the name of books.add_class looks like it holds a tax +id ..."; a key the caller chose is never quoted, it is "an unrecognised field +of" the tool), says +tax ids are stored only with `books.set_tin` or a W-9 (`books.set_w9`), never +repeats the number, writes nothing, and is recorded as refused `tin_in_text`. +The same text meets the same check in the engine, so no other caller can +journal one; books that already hold such a line open as ever, and +`books.audit` names the line and the field (`tax_id_in_journal`). + Books an older version wrote take no write at all until the owner gives the format upgrade its go-ahead (D-89, WB-format-11): every write is refused, before it runs, with `format_upgrade_pending` and the words "nothing can be @@ -1602,7 +1638,8 @@ statement 8). **Rules the engine enforces** (each refusal changes nothing, the journal byte for byte): no party field holds a full TIN (a run of nine digits, -single spaces or hyphens allowed between them); a W-9's TIN is its last +single spaces or hyphens allowed between them; free text such as a memo or a +note is read by a tax id's shapes only: "No tax id in a tool's text"); a W-9's TIN is its last four digits only; W-9 facts need a 1099 role (contractor or landlord), W-4 facts the employee role; names are unique among parties not archived; texts are at most 500 characters, no control characters. @@ -2325,7 +2362,8 @@ posting. - `books.import_bank_csv { upload_id, bank_account_code, default_offset_code, rules?, date_order?, source_attachment_id? }` → `{ imported: [{ entry_id, date, description, amount, offset_account }], - count, source_attachment_id, source_linked }`: one draft per + count, source_attachment_id, source_linked, masked_count, masked: [{ row, + column, numbers }], masked_note? }`: one draft per transaction, all or none, from the QuickBooks bank-upload layout (`Date,Description,Amount`, payments negative, or `Date,Description,,`). `rules` maps description @@ -2333,11 +2371,23 @@ posting. else `default_offset_code`. `source_attachment_id` (the export as filed, category `import_source`) is checked before any draft and linked to the bank account (`source_linked`; false when it was already), never to the - drafts: a bank export is not a receipt. + drafts: a bank export is not a receipt. 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: a number in a description that reads as a tax id (nine + digits standing alone, an SSN's or an EIN's shape) is kept masked to its + last four digits (`•••-••-1234`), `masked_count` says how many values were + masked, `masked` on which lines of the file (`row`, `column` + "Description"), and `masked_note` says so in words (WB-partner-15). A rule + matches the description as the bank wrote it, so a pattern keyed on a + nine-digit reference still matches; the draft keeps the masked text. - `books.import_chart_csv { upload_id }` → `{ created, count, warnings? }`: creates accounts from `code,name,type,parent_code[,tax_category]` CSV. All-or-nothing; the - name and tax category rules are `books.add_account`'s. + name and tax category rules are `books.add_account`'s. A chart is typed by + a person: a cell that looks like a tax id (a name with any run of nine + digits, another cell with a tax id's shape; a code may be nine digits, it + is a reference) refuses the whole file, + naming its row (the file's line) and column, never the number. - Each takes the CSV only as an upload (`books.begin_upload` purpose `import`; UTF-8; D-46). The CSV itself is not filed: file it with `books.file_document` (category `import_source`) for @@ -3069,7 +3119,10 @@ and the attestations wait for the books' format upgrade, refused with depreciation, the asset register, each posted entry against the receipt policy, open drafts, tax categories, 1099 decisions and the settings; then the journal's chain, the database against a replay, the stored - files, the access log, duplicate files and the backups. The same books + files, the access log, duplicate files, a journal line whose text field + looks like a tax id (`tax_id_in_journal`, a warning naming the line and + the field, never the number; the journal is not rewritten) and the + backups. The same books (the figure head), day, scope and programme return the run that exists (`already_run`) and file and journal nothing. "The same books" means no entry, document, close, settings or role change since: an audit, an diff --git a/docs/spec/claims/partner.md b/docs/spec/claims/partner.md index bc81cffc..4e0cdc0d 100644 --- a/docs/spec/claims/partner.md +++ b/docs/spec/claims/partner.md @@ -116,6 +116,21 @@ is its TIN facts', else its W-9 facts'. **Pick (BS-partner-8):** `outside-the-books`, the owner, 2026-10-15. +**CHOICE (the owner, 2026-11-21):** how text is read for a tax id depends +on what the text is: free text (a memo, a note, a reason, a description, a +reference, a class or project name) is refused only when it *looks like* a +tax id (nine digits standing alone, an SSN's 3-2-4 or an EIN's 2-7, with any +dash or space between, and a dot between all of an SSN's groups); a party's +own fields keep the strict reading (any run of nine digits); a bank file's +descriptions are kept with such a number masked to its last four digits. +Within that choice the lead decided on 2026-11-21 that a *reference field*, +an identifier by nature (an asset tag or serial, an invoice, bill, payment +or send reference, an account code, a file name, an instrument's label, +where a W-9 or W-4 is kept), refuses only the printed 3-2-4 and 2-7 shapes +and allows a bare nine digits, which is how a serial number or a check +number is written. WB-partner-15 states it, with the downsides the owner +accepted. + **Enforced:** `crate::parties` (has_full_tin, check_text, W9Facts::check, W4Facts::check), `Ledger::add_party`, `update_party`, `set_party_role`, @@ -303,6 +318,116 @@ directory read W-9 facts only, so a member's read as missing). `books.export_cpa_package`, `books.party`. **Checked:** `ledger-core` `tests/spec_parties.rs`; `ledger-cli` `tests/spec_vault.rs`. +**WB-partner-15** Free text meets a tax id's shapes, not every run of nine +digits (CHOICE, the owner, 2026-11-21). The refusal of BS-partner-2 reads +text two ways, on purpose: + +- *Free text* (entry and reversal descriptions, memos, notes, reasons, a + discount's reason, line descriptions, class, project, period, asset and + schedule texts, a receipt's description and annotations, a decision's or + an item's words) is refused when it holds nine digits standing alone, or + an SSN's 3-2-4 or an EIN's 2-7 grouping joined by a hyphen or any other + dash or space (a line break is a space), in any Unicode form, with + zero-width and soft-hyphen characters not counted + (`settings::holds_printed_tin`). A dot joins an SSN's groups only when it + joins both (`000.00.0000`) and never an EIN's, so a coordinate + (`47.6062095`) passes; a group that starts or ends inside a longer run of + digits and dashes (a date's day then its reference, `2026-11-21 0001234`; + a part number) belongs to that run. An invoice number (`2026-11-0042`), + a phone number, an order number, a reference of ten digits or more, an + amount, a decimal and a date pass. Letters between digits, and a number + split across two fields, are left alone: an accident, not an evasion. +- *A reference field* (an asset's tag and serial number, a bill's and an + invoice's reference, a payment's and a send's reference, an account's + code, a file's name, an instrument's label, where a W-9 or W-4 is kept) + is an identifier by nature, and a bare run of nine digits is a legitimate + value there: only the printed SSN and EIN shapes are refused + (`settings::holds_printed_tin_in_reference`, the one detector without its + bare-nine group). The refusal's words are the same as for free text. An + entry's description, which is free text, shows a payment's reference with + such a run masked (`PaymentDetails::description`), and the audit reads + each journal field as its class. +- *A party's own fields* (a party's name and details, a customer's or + vendor's name, the customer's printed details on an invoice, a recipient, + an account name) keep the strict reading of WB-partner-4: any run of nine + digits (`has_full_tin`). +- *A bank file's description* is not typed by a person and often carries a + nine-digit reference, so a bank import is not refused for one: a number + that reads as a tax id is kept masked to its last four digits + (`•••-••-1234`, `settings::mask_printed_tins`), and the import's answer + says how many values were masked and on which lines (`masked_count`, + `masked`, `masked_note`). A rule that categorizes a transaction matches the + bank's own words, so one keyed on a nine-digit reference still matches; + what is kept is the masked text. A *chart* file is typed by a person: a + cell that looks like a tax id refuses the file, naming its row and column + (an account code is a reference: a bare nine digits is a code). + +The downsides the owner accepted: a nine-digit bank reference or routing +number typed into a memo is refused (write its last four), and a tax id +typed with unusual spacing could slip into a memo, since the reading +catches an accident, not a deliberate evasion. The lead's, within them: a +bare nine digits in a reference field is kept, so a tax id written there +without its grouping is not caught. + +Text the program composes from what the books already hold is never +refused: a depreciation or disposal entry's description names the asset as +the books hold it, and the asset's description may hold a shape from before +this reading, so such a composed line holds it masked to its last four +(`settings::mask_printed_tins`), as a reference in a payment's description +and an issued invoice's file name do. The vault, the party fields +and the file check of WB-partner-7 stand around it. + +The reading is made in two places that agree. Every `Ledger` command that +takes free text refuses it (`LedgerError::FreeTextHoldsTin`), so a caller +other than the tools cannot journal one, and a journal line an earlier +version took still replays whatever it holds (BS-entry-4), so no books are +refused for opening. And the tools check every string of every write tool +once, before any call runs or writes anything (WB-format-10), from one +table that classes each string as free text, a reference, a party field, or +exempt for a named reason (the vault's input, a lookup key, an id, an amount, a date, a +fixed vocabulary, the last four digits, a bank pattern, a link, a value +the engine reads); a test fails when a write tool has a string the table +does not class. The refusal names the field, says it looks like a tax id and +that tax ids are stored with `books.set_tin` or a W-9 (`books.set_w9`), and +never repeats the number. + +Books that already hold such a line are never rewritten and always open; +`books.audit` names the journal line and the field in a `tax_id_in_journal` +warning, and never the number. + +**Enforced:** `settings::holds_printed_tin`, `settings::mask_printed_tins`, +`settings::holds_printed_tin_in_reference`, +`settings::mask_printed_tins_in_reference`, `settings::check_free_text`, +`settings::check_reference_text`, `parties::check_note`, +`parties::check_reference_note`, `PaymentDetails::check`, +`PaymentDetails::description`, `Ledger::try_create_entry`, +`Ledger::reverse_entry`, `Ledger::create_invoice_with`, +`Ledger::create_bill_with`, `Ledger::register_asset`, +`Ledger::create_period`, `Ledger::annotate_attachment`, +`Ledger::check_no_party_reason`, `Ledger::renumber_account`, +`Ledger::set_asset_tag`, `Ledger::set_asset_serial`; `ledger-mcp` `text_fields`, +`books.import_bank_csv`, `books.import_chart_csv`; `ledger-import` +`parse_bank_csv_masked`, `parse_chart_csv`; `ledger-store` +`integrity_findings`, `Store::attach_receipt`, `Store::file_document`, +`Store::unlink_receipt`, `Store::withdraw_attachment`, `Store::review_entry`. +**Checked:** `ledger-core` `tests/free_text_tin.rs` +(every grouping with every separator is found, a dot between all of an +SSN's groups only, a date and its reference or a decimal never, a line break +or a zero-width character does not hide one, nine digits alone, a reference +takes nine digits, the allow-list passes, each command refuses, the engine +refuses a project's field, a payment's reference and a discount's reason, a +replay never does); +`ledger-mcp` the unit tests in `text_fields.rs` (every string a write tool +takes is classed) and `a_call_with_a_tax_id_in_free_text_is_refused_unrun_and_writes_nothing`; +`ledger-import` the unit tests in `bank_csv.rs` and `chart_csv.rs`; +`ledger-store` `tests/audit.rs` (the store's own texts, and a journal line +an earlier version took opens and is named by the audit) and +`tests/free_text_old_books.rs` (an old asset still depreciates and is +disposed of, the lines hold the masked form, the audit reads a reference as +one); `ledger-cli` +`tests/tin_in_text.rs` (through the real server: a refusal writes nothing, +a reference is kept, a bank file is masked, a chart file is refused). + ## B-35 A party's part of an entry, and a party's totals **bookspec:** `BS-partner-3` diff --git a/docs/testing.md b/docs/testing.md index 4fde125a..23033b9d 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -99,6 +99,7 @@ that would fail if it broke: | A file with full TINs is never written to a path (handed over instead, D-29), and never filed into the books: every file the server read or wrote with TINs (from any session, after a restart, out of a CPA package), by every filing tool | `mcp_journeys.rs` `tin_bearing_files_are_refused_when_given_back_to_be_filed`; `spec_vault.rs` `a_package_is_handed_over_and_never_written`; `tin_files.rs` (tests) `a_tin_bearing_file_is_refused_from_every_session_and_after_a_restart`; unit test `a_recorded_tin_file_is_refused_by_every_reader_of_the_registry` | | Text filed into the books is refused when it holds a TIN the vault keeps (nine digits, 3-2-4 by hyphen, space or dot, 2-7 by hyphen or space, anywhere) or a stand-alone printed SSN or EIN (123-45-6789, 12-3456789), and only then: a bank export (routing numbers, long references, a date next to an amount) and a longer number holding an SSN shape go in; a locked vault leaves the printed shapes (BS-partner-2) | `tin_files.rs` (tests) `text_with_a_vault_tin_or_a_printed_one_is_refused_and_a_bank_export_is_not`; unit tests `text_holding_a_vault_tin_is_refused_in_every_rendering`, `a_printed_ssn_or_ein_is_refused`, `a_longer_number_holding_a_tin_shape_passes`, `an_ordinary_bank_export_passes`, `binary_bytes_are_not_scanned` | | Filing is no TIN oracle: text with more than two TIN-shaped numbers ending in a known TIN's last four (the books' TIN and W-9 facts, then the vault's own) is refused before the vault is opened, byte for byte alike whether one is the vault's TIN or none is, the vault open or locked, by every filing tool; one or two such numbers are compared against the vault, one number written many ways counts once, and other last fours never count (BS-partner-2) | `tin_files.rs` (tests) `text_probing_for_a_tin_is_refused_alike_by_every_filing_tool`; unit tests `text_probing_for_a_tin_is_refused_alike_whether_or_not_it_holds_it` (the vault never opened for a probe), `one_or_two_candidates_are_compared_against_the_vault` | +| Free text (a memo, note, reason, description, reference, a class, project or period name, a receipt's words) is refused when it looks like a tax id (nine digits alone, 3-2-4, 2-7, any dash, dot or space, in any Unicode form) and an invoice number, a phone number, a reference of ten digits or more, an amount and a date pass; a party's own fields stay strict; the refusal names the field, says where a tax id goes and never repeats it; every string of every write tool is classed in one table and a new one fails the build; a reference field (tag, serial, invoice or payment reference, account code, file name, label) takes a bare nine digits and refuses the grouped shapes; a dot joins only an SSN's both groups, a date and its reference or a decimal pass, a line break or a zero-width character hides nothing; a bank file is kept with the number masked to its last four, a rule matches the bank's own words, and the answer says how many and where; a chart file is refused naming row and column; text composed from stored text is masked, never refused (an old asset still depreciates and is disposed of); a journal line an earlier version took replays and the audit names it (WB-partner-15) | `tests/free_text_tin.rs` (ledger-core: every grouping, every separator, the allow-list, the dot and the longer run, a reference, each command, a payment's reference, a project's field, replay); `text_fields.rs` unit tests `every_string_a_write_tool_takes_is_in_the_table`, `the_table_names_only_strings_the_tools_take`, `a_reference_takes_nine_digits_and_refuses_a_printed_tax_id`, `a_refusal_never_quotes_a_key_the_caller_chose`; `ledger-store` `tests/free_text_old_books.rs`; `ledger-cli` `tests/tin_in_text.rs` `a_bank_rule_keyed_on_a_nine_digit_reference_still_matches`; `server_tests.rs` `a_call_with_a_tax_id_in_free_text_is_refused_unrun_and_writes_nothing`; `bank_csv.rs` and `chart_csv.rs` unit tests; `ledger-store` `tests/audit.rs` `the_store_refuses_text_that_looks_like_a_tax_id_and_journals_nothing`, `integrity_detects_each_seeded_defect`; `ledger-cli` `tests/tin_in_text.rs` | | The connect text fits its budgets, its lead stands alone, it states the receipt rule enforced (exact threshold in the base currency, required and exempt accounts, reversals) and the parties rule in force, and the company name can't break it (control and format characters) | `handbook.rs` `instructions_budget`, `a_typical_company_gets_the_whole_connect_text`, `the_company_name_is_one_plain_line`; `receipt_policy.rs` `the_rule_told_is_the_rule_enforced`, `a_long_or_odd_account_list_stays_short_and_plain`; a new session is told the settings in force: `a_new_session_is_told_the_settings_in_force` | | No text the agent is given (whole tool JSON, resources, connect text, handbook, every error template and refusal) points at files, git, GitHub, repo docs, flags or helper commands; descriptions fit 700 characters (listed exceptions, P5; and what git itself said of a failed backup, which `books.backup` passes on to the human as git said it, its paths hidden) | `tool_text_lint`, `tool_descriptions_fit_700_characters`; `ledger-core` `an_unknown_year_threshold_is_never_guessed` | | Every tool is annotated (openWorldHint false on all but `books.back_up_now`), and the read-only hint is true in behaviour (journal, every file of the books' folder but what every call writes by design: the access log, `ops/` (the viewer's side channel for `books.show`, which is not the books), the books' own backup and the files handed over; the database's rows and the vault unchanged) | `annotations_complete`; `spec_mcp.rs` `read_only_tools_change_nothing` (checked on every call in `Mcp::tool`) |