From c206652abe7dfd24be038c0800ef3ef5dfc46ac9 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 20:50:23 -0700 Subject: [PATCH] fix(core,mcp,store): a phone number is kept and a ZIP+4 is kept; only a tax id's printed shapes are refused in a phone A telephone is ten digits or more, so the strict reading of a party's fields (any run of nine digits) refused every phone number: the bill-to snapshot's check, new with the free-text change, refused `503-555-0100` and failed the window's invoice test. The party's own phone (since D-55) and the tool's bill-to phone had always been refused the same way; only 7-digit test numbers hid it. A phone field (a party's, a bill-to's, the seller's) is now its own class, read as a reference is: refuse the printed SSN 3-2-4 and EIN 2-7 and nothing else, since a nine-digit national number is ordinary. A postal address keeps the strict reading except a ZIP+4 (`98101-1234`, five and four, nine digits), a postal code. The formation state's entity number is a registration number (a Washington UBI is nine digits) and is read as a reference. The tools' table, the engine, and the audit's keys agree; the audit reads `phone` and `fax` as a phone. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/tests/tin_in_text.rs | 85 +++++ crates/ledger-core/src/arap.rs | 59 +++- crates/ledger-core/src/ledger.rs | 23 +- crates/ledger-core/src/parties.rs | 44 +++ crates/ledger-core/src/settings.rs | 32 +- crates/ledger-core/tests/phone_text.rs | 293 ++++++++++++++++++ crates/ledger-mcp/src/text_fields.rs | 62 +++- crates/ledger-mcp/src/tools/documents.rs | 14 +- crates/ledger-store/src/audit.rs | 6 + .../ledger-store/tests/free_text_old_books.rs | 89 ++++++ docs/mcp-interface.md | 20 +- docs/spec/claims/partner.md | 50 ++- 12 files changed, 725 insertions(+), 52 deletions(-) create mode 100644 crates/ledger-core/tests/phone_text.rs diff --git a/crates/ledger-cli/tests/tin_in_text.rs b/crates/ledger-cli/tests/tin_in_text.rs index bef43fd6..5365b902 100644 --- a/crates/ledger-cli/tests/tin_in_text.rs +++ b/crates/ledger-cli/tests/tin_in_text.rs @@ -277,3 +277,88 @@ fn a_chart_file_with_a_tax_id_is_refused_naming_its_row_and_column() { let chart = answer_of(&w.call("books.chart", json!({}))).unwrap(); assert!(!chart.to_string().contains("Payroll"), "{chart}"); } + +/// A telephone or fax number is kept, whatever its digits, and refused only +/// where it reads as an SSN or an EIN; a ZIP+4 is kept in an address; every +/// other field of a party is still read strictly (WB-partner-15). +#[test] +fn a_phone_is_kept_and_a_printed_tax_id_in_one_is_refused() { + let books = Books::new("tin-phone-field"); + let mut w = books.session("test"); + setup(&mut w); + answer_of(&w.call("books.add_customer", json!({"name": "Harbor Coffee"}))).unwrap(); + let party = answer_of(&w.call("books.party", json!({"party": "Harbor Coffee"}))).unwrap() + ["party"]["party_id"] + .to_string(); + let party = party.trim_matches('"').to_string(); + for phone in [ + "2065550142", + "206-555-0142", + "(206) 555-0142", + "+1 206 555 0142", + "+44 20 7946 0958", + "206-555-0142 x1234", + "612345678", + ] { + let out = answer_of(&w.call( + "books.update_party", + json!({"party": party, "phone": phone, "contact": "Ana Reyes", + "billing_address": "400 Pine St\nSeattle, WA 98101-1234"}), + )) + .unwrap_or_else(|e| panic!("{phone}: {e}")); + assert_eq!(out["phone"], json!(phone), "{out}"); + let invoice = answer_of(&w.call( + "books.create_invoice", + json!({"customer": "Harbor Coffee", "date": "2026-03-01", "terms": "Net 30", + "lines": [{"description": "Work", "amount": "10.00"}], + "bill_to": {"phone": phone, "shipping_address": "9 Dock Rd, Seattle WA 98101-1234"}, + "confirmed": true}), + )) + .unwrap_or_else(|e| panic!("{phone}: {e}")); + assert!( + invoice["invoice_id"].is_u64() || invoice["total"].is_string(), + "{invoice}" + ); + } + let before = books.journal_raw(); + for (tool, args, field) in [ + ( + "books.update_party", + json!({"party": party, "phone": SSN}), + "the phone of books.update_party", + ), + ( + "books.update_party", + json!({"party": party, "phone": format!("fax {EIN}")}), + "the phone of books.update_party", + ), + ( + "books.create_invoice", + json!({"customer": "Harbor Coffee", "date": "2026-03-01", "terms": "Net 30", + "lines": [{"description": "Work", "amount": "10.00"}], + "bill_to": {"phone": SSN}, "confirmed": true}), + "the bill_to.phone of books.create_invoice", + ), + ] { + let why = answer_of(&w.call(tool, args)).unwrap_err(); + assert!(why.contains(field), "{tool}: {why}"); + assert!(!why.contains("0000"), "never the number: {why}"); + assert_eq!( + books.journal_raw(), + before, + "{tool}: a refusal writes nothing" + ); + } + // The rest of a party is strict: nine digits in a contact, a note or an address. + for (key, value) in [ + ("contact", "Ana 123456789"), + ("notes", "tax id 123456789"), + ("address", "1 Main St 123456789"), + ] { + let why = answer_of(&w.call("books.update_party", json!({"party": party, key: value}))) + .unwrap_err(); + assert!(why.contains(key), "{key}: {why}"); + assert!(!why.contains("123456789"), "never the number: {why}"); + } + assert_eq!(books.journal_raw(), before, "a refusal writes nothing"); +} diff --git a/crates/ledger-core/src/arap.rs b/crates/ledger-core/src/arap.rs index 3c7674dd..48ed98fb 100644 --- a/crates/ledger-core/src/arap.rs +++ b/crates/ledger-core/src/arap.rs @@ -1285,35 +1285,64 @@ pub fn check_document_text( } /// 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). +/// fields: strict, no run of nine digits, [`crate::parties::check_text`]; +/// an address allows a ZIP+4, [`crate::parties::check_address`]; a phone +/// is refused only in a tax id's printed shapes, +/// [`crate::parties::check_phone`]) and the seller's (the company's own, +/// free text: no tax id's shape; its phone as any phone). pub fn check_snapshots( bill_to: Option<&PartySnapshot>, seller: Option<&PartySnapshot>, ) -> Result<(), LedgerError> { - let fields = |s: &'_ PartySnapshot| -> [(&'static str, Option); 8] { + /// How a field of a snapshot is read. + #[derive(Clone, Copy, PartialEq)] + enum Kind { + Plain, + Address, + Phone, + } + let fields = |s: &'_ PartySnapshot| -> [(&'static str, Kind, 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()), + ("the bill-to name", Kind::Plain, Some(s.name.clone())), + ("the bill-to address", Kind::Address, s.address.clone()), + ("the bill-to email", Kind::Plain, s.email.clone()), + ("the bill-to phone", Kind::Phone, s.phone.clone()), + ("the bill-to contact", Kind::Plain, s.contact.clone()), + ( + "the billing address", + Kind::Address, + s.billing_address.clone(), + ), + ( + "the shipping address", + Kind::Address, + s.shipping_address.clone(), + ), + ("the billing email", Kind::Plain, s.billing_email.clone()), ] }; if let Some(s) = bill_to { - for (field, text) in fields(s) { + for (field, kind, text) in fields(s) { if let Some(t) = text { - crate::parties::check_text(field, &t).map_err(LedgerError::InvalidParty)?; + match kind { + Kind::Plain => crate::parties::check_text(field, &t), + Kind::Address => crate::parties::check_address(field, &t), + Kind::Phone => crate::parties::check_phone(field, &t), + } + .map_err(LedgerError::InvalidParty)?; } } } if let Some(s) = seller { - for (field, text) in fields(s) { + for (field, kind, text) in fields(s) { if let Some(t) = text { - LedgerError::free_text(&field.replace("bill-to", "seller"), &t)?; + let field = field.replace("bill-to", "seller"); + if kind == Kind::Phone { + crate::settings::check_phone_text(&field, &t) + .map_err(LedgerError::FreeTextHoldsTin)?; + } else { + LedgerError::free_text(&field, &t)?; + } } } } diff --git a/crates/ledger-core/src/ledger.rs b/crates/ledger-core/src/ledger.rs index 7fe12abd..382a0fab 100644 --- a/crates/ledger-core/src/ledger.rs +++ b/crates/ledger-core/src/ledger.rs @@ -5070,6 +5070,16 @@ impl Ledger { Some(t) => crate::parties::check_text(f, t).map_err(LedgerError::InvalidParty), None => Ok(()), }; + // A postal address allows a ZIP+4; a phone or fax number is refused + // only in a tax id's printed shapes (WB-partner-15). + let address = |f: &str, v: &Option| match v { + Some(t) => crate::parties::check_address(f, t).map_err(LedgerError::InvalidParty), + None => Ok(()), + }; + let phone = |f: &str, v: &Option| match v { + Some(t) => crate::parties::check_phone(f, t).map_err(LedgerError::InvalidParty), + None => Ok(()), + }; match field { Name(n) => { if n.trim().is_empty() { @@ -5087,7 +5097,7 @@ impl Ledger { } DisplayName(v) => text("display_name", v)?, Website(v) => text("website", v)?, - Address(v) => text("address", v)?, + Address(v) => address("address", v)?, Notes(v) => text("notes", v)?, Archived(false) => { if let Some(other) = self.party_by_name(&p.name) @@ -5105,12 +5115,13 @@ impl Ledger { crate::parties::check_email("email", e).map_err(LedgerError::InvalidParty)?; } } - // The D-55 contact block: two addresses and a phone like any - // other text (no full TIN), the billing email an address. - Phone(v) => text("phone", v)?, + // The D-55 contact block: two addresses (a ZIP+4 allowed) and a + // phone (refused only in a tax id's printed shapes), the billing + // email an address. + Phone(v) => phone("phone", v)?, Contact(v) => text("contact", v)?, - BillingAddress(v) => text("billing_address", v)?, - ShippingAddress(v) => text("shipping_address", v)?, + BillingAddress(v) => address("billing_address", v)?, + ShippingAddress(v) => address("shipping_address", v)?, BillingEmail(v) => { if let Some(e) = v { crate::parties::check_email("billing_email", e) diff --git a/crates/ledger-core/src/parties.rs b/crates/ledger-core/src/parties.rs index b1316efd..426b6a71 100644 --- a/crates/ledger-core/src/parties.rs +++ b/crates/ledger-core/src/parties.rs @@ -717,6 +717,50 @@ pub fn check_text(field: &str, text: &str) -> Result<(), String> { Ok(()) } +/// [`has_full_tin`] for a postal address: the same strict reading, except +/// that a ZIP+4 (five digits, a hyphen, four digits, standing alone: +/// `98101-1234`) is a postal code, not a tax id, though it is nine digits. +pub fn has_full_tin_in_address(text: &str) -> bool { + let chars: Vec = text.chars().collect(); + let runs = if REPLAYING.with(std::cell::Cell::get) { + journaled_tin_runs(&chars) + } else { + full_tin_runs(&chars) + }; + runs.iter().any(|&(first, last)| { + let run = &chars[first..=last]; + let zip_plus_4 = run.len() == 10 + && run[5] == '-' + && run + .iter() + .enumerate() + .all(|(i, c)| i == 5 || c.is_ascii_digit()); + !zip_plus_4 + }) +} + +/// [`check_text`] for a postal address: a ZIP+4 is allowed +/// ([`has_full_tin_in_address`]); every other run of nine digits is refused. +pub fn check_address(field: &str, text: &str) -> Result<(), String> { + if has_full_tin_in_address(text) { + return Err(format!( + "{field} looks like it holds a full taxpayer identification number; \ + the books keep only its last four digits (the full number belongs in the vault)" + )); + } + // The length and control-character bounds are the other text's. + check_note_form(field, text) +} + +/// Check a telephone or fax number: not a tax id's printed shapes (an SSN's +/// 3-2-4, an EIN's 2-7: [`crate::settings::check_phone_text`]); every other +/// number is a phone's, whatever its digits or grouping. At most 500 +/// characters, no control characters except newline. +pub fn check_phone(field: &str, text: &str) -> Result<(), String> { + crate::settings::check_phone_text(field, text)?; + check_note_form(field, text) +} + /// 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 diff --git a/crates/ledger-core/src/settings.rs b/crates/ledger-core/src/settings.rs index 8eb6346d..b1b6097d 100644 --- a/crates/ledger-core/src/settings.rs +++ b/crates/ledger-core/src/settings.rs @@ -759,6 +759,19 @@ pub fn holds_printed_tin_in_reference(text: &str) -> bool { !printed_tin_spans(text, Reading::Reference).1.is_empty() } +/// [`holds_printed_tin`] for a telephone or fax number: only the printed +/// SSN (3-2-4) and EIN (2-7) forms count. A phone number is ten digits or +/// more (a country code and an area code), and a national number of nine +/// is ordinary in many countries, so a run of nine or more digits proves +/// nothing there; `206-555-0142`, `(206) 555-0142`, `+1 206 555 0142`, +/// `+44 20 7946 0958` and an extension are all kept (WB-partner-15). It +/// reads as a reference does; it has its own name so that the fields that +/// hold a phone (a party's, a bill-to's, the tools' table, the audit's +/// keys) say so, and one change here moves them all. +pub fn holds_printed_tin_in_phone(text: &str) -> bool { + holds_printed_tin_in_reference(text) +} + /// [`holds_printed_tin`] for a web address: the printed SSN (3-2-4) and /// EIN (2-7) forms count as there, but a bare run of nine digits joined /// to a letter or to the URL punctuation `/ = ? & #` does not: it is an @@ -1012,6 +1025,16 @@ pub fn check_reference_text(field: &str, text: &str) -> Result<(), String> { Ok(()) } +/// A telephone or fax number that may be kept: not a tax id's printed +/// shapes ([`holds_printed_tin_in_phone`]). Returns why not, in +/// [`tin_refusal`]'s words. Never refuses during a replay (BS-entry-4). +pub fn check_phone_text(field: &str, text: &str) -> Result<(), String> { + if !crate::parties::is_replaying() && holds_printed_tin_in_phone(text) { + return Err(tin_refusal(field)); + } + Ok(()) +} + fn no_tin(what: &str, s: &str) -> Result<(), String> { if holds_printed_tin(s) { return Err(format!( @@ -1287,7 +1310,14 @@ pub fn check(key: &Key, v: &Value) -> Result { let name = key.name; match key.kind { Kind::Text => { - let text = line_text(name, want_str(name, v)?, MAX_TEXT)?; + // The state's entity number is a registration number (a + // Washington UBI is nine digits): a reference, refused only in + // a tax id's printed shapes (WB-partner-15). + let text = if name == "company.state_entity_number" { + reference_line_text(name, want_str(name, v)?, MAX_TEXT)? + } else { + line_text(name, want_str(name, v)?, MAX_TEXT)? + }; // One key's own bound: an invoice number's prefix is short and // visible (a space or a control character would break the // number's reading, and the file's). diff --git a/crates/ledger-core/tests/phone_text.rs b/crates/ledger-core/tests/phone_text.rs new file mode 100644 index 00000000..ef1bceda --- /dev/null +++ b/crates/ledger-core/tests/phone_text.rs @@ -0,0 +1,293 @@ +//! A telephone or fax number is kept, and a tax id's printed shapes are not +//! (BS-partner-2, WB-partner-15; docs/spec/claims/partner.md, the CHOICE on +//! BS-partner-2 as amended 2026-11-21). +//! +//! Oracle: what a phone number is. It is ten digits or more with a country +//! and an area code, so the strict reading of a party's fields (any run of +//! nine digits) refused every phone number there was; a phone field +//! refuses only what reads as a Social Security number (3-2-4) or an EIN +//! (2-7). A postal address likewise keeps a ZIP+4, which is nine digits and +//! no tax id. The fake ids are `000-00-0000` and `00-0000000`; no real one +//! appears here. + +use ledger_core::arap::{DocumentLine, InvoiceFields, PartySnapshot}; +use ledger_core::parties::{check_address, check_phone, has_full_tin, has_full_tin_in_address}; +use ledger_core::{Currency, Ledger, LedgerError, PartyField}; +use proptest::prelude::*; +use rust_decimal::Decimal; + +/// What a phone number looks like in the world. +const PHONES: &[&str] = &[ + "2065550142", + "206-555-0142", + "206.555.0142", + "206 555 0142", + "(206) 555-0142", + "(206)555-0142", + "+1 206 555 0142", + "+1 (206) 555-0142", + "+1-206-555-0142", + "1-800-555-0142", + "+44 20 7946 0958", + "+44 (0)20 7946 0958", + "020 7946 0958", + "+49 30 12345678", + "+33 1 23 45 67 89", + "+81 3-1234-5678", + "+91 98765 43210", + "612345678", + "206-555-0142 x1234", + "206-555-0142 ext. 12", + "(206) 555-0142, ext 7", + "503-555-0100", + "555-0142", + "", +]; + +const SSN: &str = "000-00-0000"; +const EIN: &str = "00-0000000"; + +#[test] +fn an_ordinary_phone_number_is_kept() { + for p in PHONES { + assert_eq!(check_phone("phone", p), Ok(()), "{p:?}"); + } +} + +#[test] +fn an_ssn_or_an_ein_in_a_phone_field_is_refused_in_words_that_never_say_the_number() { + for t in [ + SSN, + EIN, + "000 00 0000", + "000.00.0000", + "ssn 000-00-0000", + "206-555-0142 / 000-00-0000", + "fax 00-0000000", + "\u{ff10}\u{ff10}\u{ff10}-\u{ff10}\u{ff10}-\u{ff10}\u{ff10}\u{ff10}\u{ff10}", + ] { + let why = check_phone("the bill-to phone", t).unwrap_err(); + assert!( + why.starts_with("the bill-to phone looks like it holds a tax id"), + "{t:?}: {why}" + ); + assert!(!why.contains("0000"), "{why}"); + } +} + +#[test] +fn a_phone_field_keeps_a_phone_a_party_s_other_fields_would_refuse() { + // The strict reading of the other party fields still refuses these. + for p in ["206-555-0142", "+1 206 555 0142", "2065550142", "612345678"] { + assert!(has_full_tin(p), "{p}: strict"); + assert!(check_phone("phone", p).is_ok(), "{p}: phone"); + } +} + +#[test] +fn a_zip_plus_4_is_kept_in_an_address_and_a_tax_id_is_not() { + for a in [ + "98101-1234", + "400 Pine St\nSeattle, WA 98101-1234", + "400 Pine St, Seattle WA 98101-1234, USA", + "Suite 100, 84101", + "PO Box 12, Salt Lake City UT 84101-0012", + "98101-1234\n84047-1234", + ] { + assert_eq!(check_address("address", a), Ok(()), "{a:?}"); + } + for a in [ + SSN, + EIN, + "400 Pine St 123456789", + "123 456 789", + "98101-12345", // six digits after: nine, then one more + "198101-1234", // six before + "98101-1234 5678", // a longer run + "98101 1234", // not a ZIP+4's hyphen + "400 Pine St 000-00-0000, Seattle", + ] { + assert!(check_address("address", a).is_err(), "{a:?}"); + assert!(has_full_tin_in_address(a), "{a:?}"); + } +} + +/// A phone field and an address on the party, through the engine. +#[test] +fn a_party_keeps_any_phone_and_a_zip_plus_4_and_stays_strict_elsewhere() { + let mut l = Ledger::new(Currency::USD); + let party = l.add_party("Harbor Coffee", &[]).unwrap(); + for p in PHONES { + l.update_party(party, PartyField::Phone(Some((*p).to_string()))) + .unwrap(); + } + l.update_party( + party, + PartyField::BillingAddress(Some("1 Main St, Seattle WA 98101-1234".into())), + ) + .unwrap(); + l.update_party( + party, + PartyField::ShippingAddress(Some("2 Dock Rd, Seattle WA 98101-1234".into())), + ) + .unwrap(); + l.update_party( + party, + PartyField::Address(Some("3 Pier St, Seattle WA 98101-1234".into())), + ) + .unwrap(); + for bad in [SSN, EIN] { + let before = l.clone(); + let r = l.update_party(party, PartyField::Phone(Some(bad.into()))); + assert!(matches!(r, Err(LedgerError::InvalidParty(_))), "{r:?}"); + assert_eq!(l, before, "a refusal changes nothing"); + } + // Every other field of a party is still strict. + for f in [ + PartyField::Contact(Some("Ana 123456789".into())), + PartyField::Notes(Some("tax id 123456789".into())), + PartyField::Address(Some("1 Main St 123456789".into())), + PartyField::Email(Some("123456789@example.com".into())), + ] { + let r = l.update_party(party, f.clone()); + assert!( + matches!(r, Err(LedgerError::InvalidParty(_))), + "{f:?}: {r:?}" + ); + } +} + +fn snap(phone: &str) -> PartySnapshot { + PartySnapshot { + name: "Harbor Coffee Roasters, Inc.".into(), + address: Some("455 Wharf Street\nPortland, OR 97209-1234".into()), + email: None, + phone: Some(phone.into()), + contact: None, + billing_address: None, + shipping_address: None, + billing_email: None, + } +} + +fn invoice_with( + l: &mut Ledger, + bill_to: PartySnapshot, + seller: PartySnapshot, +) -> Result<(), LedgerError> { + let c = l.add_customer("Harbor Coffee").unwrap(); + let d = chrono::NaiveDate::from_ymd_opt(2026, 3, 1).unwrap(); + l.create_invoice_with( + c, + d, + d, + vec![DocumentLine { + description: "Consulting".into(), + amount: Decimal::from(10), + class_id: None, + account: None, + quantity: None, + unit_price: None, + }], + InvoiceFields { + bill_to: Some(bill_to), + seller: Some(seller), + ..Default::default() + }, + ) + .map(|_| ()) +} + +/// The invoice's bill-to and seller snapshots, through the engine. +#[test] +fn an_invoice_prints_any_phone_and_refuses_a_tax_id_in_one() { + for p in PHONES.iter().filter(|p| !p.is_empty()) { + let mut l = Ledger::new(Currency::USD); + let r = invoice_with(&mut l, snap(p), snap(p)); + assert!(r.is_ok(), "{p:?}: {r:?}"); + } + for bad in [SSN, EIN] { + let mut l = Ledger::new(Currency::USD); + let r = invoice_with(&mut l, snap(bad), snap("206-555-0142")); + assert!( + matches!(r, Err(LedgerError::InvalidParty(_))), + "{bad}: {r:?}" + ); + let mut l = Ledger::new(Currency::USD); + let r = invoice_with(&mut l, snap("206-555-0142"), snap(bad)); + assert!( + matches!(r, Err(LedgerError::FreeTextHoldsTin(_))), + "{bad}: {r:?}" + ); + } +} + +proptest! { + /// Any phone built of a country code, an area code and a subscriber + /// number, in any of the usual groupings, is kept unless it is itself + /// an SSN's 3-2-4 or an EIN's 2-7 (which a phone's groups never are). + #[test] + fn a_phone_of_any_usual_grouping_is_kept( + cc in "[1-9][0-9]{0,2}", + area in "[2-9][0-9]{2}", + ex in "[2-9][0-9]{2}", + sub in "[0-9]{4}", + sep in prop::sample::select(vec!["-", " ", ".", ""]), + shape in 0usize..4, + ) { + let p = match shape { + 0 => format!("+{cc} {area}{sep}{ex}{sep}{sub}"), + 1 => format!("({area}) {ex}{sep}{sub}"), + 2 => format!("{area}{sep}{ex}{sep}{sub} x{cc}"), + _ => format!("+{cc}-{area}{ex}{sub}"), + }; + prop_assert!(check_phone("phone", &p).is_ok(), "{p}"); + } + + /// An SSN's 3-2-4 and an EIN's 2-7, with any separator, are refused + /// in a phone field, alone or among words. + #[test] + fn a_printed_ssn_or_ein_is_refused_in_a_phone_field( + a in "[0-9]{3}", b in "[0-9]{2}", c in "[0-9]{4}", + e in "[0-9]{2}", f in "[0-9]{7}", + sep in prop::sample::select(vec!["-", " ", "\u{2013}", " - "]), + pre in prop::sample::select(vec!["", "ssn ", "(", "fax: "]), + post in prop::sample::select(vec!["", " x12", ")", " thanks"]), + ) { + let ssn = format!("{pre}{a}{sep}{b}{sep}{c}{post}"); + let ein = format!("{pre}{e}{sep}{f}{post}"); + prop_assert!(check_phone("phone", &ssn).is_err(), "{ssn}"); + prop_assert!(check_phone("phone", &ein).is_err(), "{ein}"); + } + + /// A ZIP+4 anywhere in an address is kept. + #[test] + fn a_zip_plus_4_is_kept_wherever_it_stands( + z in "[0-9]{5}", p in "[0-9]{4}", + pre in prop::sample::select(vec!["", "Seattle, WA ", "1 Main St\nSeattle WA ", "Unit 4, "]), + post in prop::sample::select(vec!["", ", USA", "\nUSA"]), + ) { + let a = format!("{pre}{z}-{p}{post}"); + prop_assert!(check_address("address", &a).is_ok(), "{a}"); + } +} + +/// The formation state's entity number is a registration number: a +/// Washington UBI is nine digits, so a bare nine digits is kept, and a +/// printed SSN or EIN is not (every other text setting is free text). +#[test] +fn the_state_entity_number_keeps_nine_digits_and_refuses_a_printed_tax_id() { + let key = ledger_core::settings::key("company.state_entity_number").unwrap(); + for ok in ["603123456", "603 123 456", "14745117-0160", "5012345"] { + assert!( + ledger_core::settings::check(key, &serde_json::json!(ok)).is_ok(), + "{ok}" + ); + } + for bad in [SSN, EIN] { + assert!(ledger_core::settings::check(key, &serde_json::json!(bad)).is_err()); + } + // Another text setting stays free text: a bare nine digits is refused. + let agent = ledger_core::settings::key("company.registered_agent").unwrap(); + assert!(ledger_core::settings::check(agent, &serde_json::json!("123456789")).is_err()); +} diff --git a/crates/ledger-mcp/src/text_fields.rs b/crates/ledger-mcp/src/text_fields.rs index 5f2efc02..da144a48 100644 --- a/crates/ledger-mcp/src/text_fields.rs +++ b/crates/ledger-mcp/src/text_fields.rs @@ -25,7 +25,12 @@ //! 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. +//! refuses it. A PHONE (a party's or a bill-to's telephone or fax) is +//! refused only in a tax id's printed shapes, an SSN's 3-2-4 and an +//! EIN's 2-7 (`ledger_core::settings::holds_printed_tin_in_phone`): +//! a phone number is ten digits or more, so a run of digits proves +//! nothing there. An ADDRESS is read as STRICT, except that a ZIP+4 +//! is no tax id (`ledger_core::parties::has_full_tin_in_address`). //! 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, @@ -100,6 +105,13 @@ pub(crate) enum Class { /// A party's own field (or a name that becomes one): refused at any /// run of nine digits. Strict, + /// A telephone or fax number: refused only in a tax id's printed shapes + /// (an SSN's 3-2-4, an EIN's 2-7), as a reference is; every other number + /// is a phone's (`ledger_core::settings::holds_printed_tin_in_phone`). + Phone, + /// A party's postal address: strict, except that a ZIP+4 (`98101-1234`, + /// nine digits) is a postal code (`ledger_core::parties::has_full_tin_in_address`). + Address, /// Not checked, for the reason named. Exempt(Why), } @@ -107,6 +119,8 @@ pub(crate) enum Class { const FREE: Class = Class::Free; const REFERENCE: Class = Class::Reference; const STRICT: Class = Class::Strict; +const PHONE: Class = Class::Phone; +const ADDRESS: Class = Class::Address; const VAULT: Class = Class::Exempt(Why::Vault); const LOOKUP: Class = Class::Exempt(Why::Lookup); const ID: Class = Class::Exempt(Why::Id); @@ -273,14 +287,14 @@ pub(crate) const TABLE: &[(&str, &[(&str, Class)])] = &[ ( "books.create_invoice", &[ - ("bill_to.address", STRICT), - ("bill_to.billing_address", STRICT), + ("bill_to.address", ADDRESS), + ("bill_to.billing_address", ADDRESS), ("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), + ("bill_to.phone", PHONE), + ("bill_to.shipping_address", ADDRESS), ("customer", LOOKUP), ("customer_ref", REFERENCE), ("date", DATE), @@ -736,8 +750,8 @@ pub(crate) const TABLE: &[(&str, &[(&str, Class)])] = &[ ( "books.update_party", &[ - ("address", STRICT), - ("billing_address", STRICT), + ("address", ADDRESS), + ("billing_address", ADDRESS), ("billing_email", STRICT), ("contact", STRICT), ("creditor_of[]", LOOKUP), @@ -748,8 +762,8 @@ pub(crate) const TABLE: &[(&str, &[(&str, Class)])] = &[ ("name", STRICT), ("notes", STRICT), ("party", LOOKUP), - ("phone", STRICT), - ("shipping_address", STRICT), + ("phone", PHONE), + ("shipping_address", ADDRESS), ("website", STRICT), ], ), @@ -814,6 +828,8 @@ fn looks_like_a_tax_id(class: Class, text: &str) -> bool { 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::Phone => ledger_core::settings::holds_printed_tin_in_phone(text), + Class::Address => ledger_core::parties::has_full_tin_in_address(text), Class::Exempt(_) => false, } } @@ -1139,12 +1155,38 @@ mod tests { ("books.add_vendor", "name"), ("books.add_party", "name"), ("books.update_party", "notes"), - ("books.create_invoice", "bill_to.address"), + ("books.create_invoice", "bill_to.contact"), + ("books.update_party", "contact"), ("books.add_account", "name"), ("books.mark_sent", "recipients[]"), ] { assert_eq!(class(tool, path), Class::Strict, "{tool} {path}"); } + for (tool, path) in [ + ("books.create_invoice", "bill_to.address"), + ("books.create_invoice", "bill_to.billing_address"), + ("books.create_invoice", "bill_to.shipping_address"), + ("books.update_party", "address"), + ("books.update_party", "billing_address"), + ("books.update_party", "shipping_address"), + ] { + assert_eq!(class(tool, path), Class::Address, "{tool} {path}"); + } + for (tool, path) in [ + ("books.create_invoice", "bill_to.phone"), + ("books.update_party", "phone"), + ] { + assert_eq!(class(tool, path), Class::Phone, "{tool} {path}"); + } + // Any string named for a phone or a fax is a PHONE, wherever it is. + for (tool, rows) in TABLE { + for (path, c) in *rows { + let last = path.rsplit('.').next().unwrap_or(path); + if last.contains("phone") || last.contains("fax") { + assert_eq!(*c, Class::Phone, "{tool} {path}"); + } + } + } // Identifiers by nature: a bare nine digits is a number there. for (tool, path) in [ ("books.add_account", "code"), diff --git a/crates/ledger-mcp/src/tools/documents.rs b/crates/ledger-mcp/src/tools/documents.rs index daa98659..24ef379d 100644 --- a/crates/ledger-mcp/src/tools/documents.rs +++ b/crates/ledger-mcp/src/tools/documents.rs @@ -279,19 +279,21 @@ fn customer_snapshot( } } ledger_core::parties::check_text("the bill-to name", &snapshot.name)?; - if let Some(a) = &snapshot.address { - ledger_core::parties::check_text("the bill-to address", a)?; - } for (field, value) in [ - ("the bill-to contact", &snapshot.contact), - ("the bill-to phone", &snapshot.phone), + ("the bill-to address", &snapshot.address), ("the billing address", &snapshot.billing_address), ("the shipping address", &snapshot.shipping_address), ] { if let Some(v) = value { - ledger_core::parties::check_text(field, v)?; + ledger_core::parties::check_address(field, v)?; } } + if let Some(v) = &snapshot.contact { + ledger_core::parties::check_text("the bill-to contact", v)?; + } + if let Some(v) = &snapshot.phone { + ledger_core::parties::check_phone("the bill-to phone", v)?; + } for (field, value) in [ ("the bill-to email", &snapshot.email), ("the billing email", &snapshot.billing_email), diff --git a/crates/ledger-store/src/audit.rs b/crates/ledger-store/src/audit.rs index 107e7887..ecd68272 100644 --- a/crates/ledger-store/src/audit.rs +++ b/crates/ledger-store/src/audit.rs @@ -159,6 +159,9 @@ enum TextClass { /// account code): only the grouped shapes are found, a bare nine digits /// being a legitimate number there (WB-partner-15). Reference, + /// A telephone or fax number: read as a reference is (only the grouped + /// shapes), by its own name so that a phone is never read as words. + Phone, } /// The journal fields that hold words someone wrote (never an id, a digest @@ -197,6 +200,8 @@ const TEXT_KEYS: &[(&str, TextClass)] = &[ ("display_name", TextClass::Free), ("address", TextClass::Free), ("contact", TextClass::Free), + ("phone", TextClass::Phone), + ("fax", TextClass::Phone), ("kept_at", TextClass::Reference), ("approver", TextClass::Free), ]; @@ -566,6 +571,7 @@ impl Store { TextClass::Reference => { ledger_core::settings::holds_printed_tin_in_reference(&text) } + TextClass::Phone => ledger_core::settings::holds_printed_tin_in_phone(&text), }; if looks { out.push(found( diff --git a/crates/ledger-store/tests/free_text_old_books.rs b/crates/ledger-store/tests/free_text_old_books.rs index e54f955b..b73a6094 100644 --- a/crates/ledger-store/tests/free_text_old_books.rs +++ b/crates/ledger-store/tests/free_text_old_books.rs @@ -286,3 +286,92 @@ fn the_audit_reads_a_reference_as_a_reference() { "{fields:?}" ); } + +/// The audit reads a telephone or fax number as a phone: ordinary numbers +/// (ten digits, dashes, a country code, an extension) are no finding, and +/// an SSN's or an EIN's printed shape in one is (WB-partner-15). +#[test] +fn the_audit_reads_a_phone_as_a_phone() { + use ledger_core::arap::{InvoiceFields, PartySnapshot}; + 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 phones = [ + "2065550142", + "206-555-0142", + "(206) 555-0142", + "+1 206 555 0142", + "+44 20 7946 0958", + "206-555-0142 x1234", + "612345678", + ]; + for phone in phones { + store + .create_invoice_with( + 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, + }], + InvoiceFields { + bill_to: Some(PartySnapshot { + name: "Acme".into(), + address: Some("1 Main St, Seattle WA 98101-1234".into()), + email: None, + phone: Some(phone.into()), + contact: None, + billing_address: None, + shipping_address: None, + billing_email: None, + }), + ..Default::default() + }, + ) + .unwrap(); + } + let findings = |store: &Store| -> Vec { + store + .integrity_findings() + .into_iter() + .filter(|f| f.code == "tax_id_in_journal") + .map(|f| f.message) + .collect() + }; + assert!(findings(&store).is_empty(), "{:?}", findings(&store)); + // A line an earlier version wrote with an SSN or an EIN in a phone or + // fax is a finding, naming the field and never the number. + 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(); + drop(store); + let mut w = JournalWriter::open(&dir.path().join(JOURNAL_FILE)).unwrap(); + w.append( + "asset.tagged", + json!({"asset_id": asset, "tag": "T1", "previous_tag": null, + "phone": "000-00-0000", "fax": "00-0000000"}), + ) + .unwrap(); + drop(w); + let store = Store::open(dir.path()).unwrap(); + let found = findings(&store); + assert_eq!(found.len(), 2, "{found:?}"); + assert!(found.iter().any(|m| m.contains("`phone`")), "{found:?}"); + assert!(found.iter().any(|m| m.contains("`fax`")), "{found:?}"); + assert!(found.iter().all(|m| !m.contains("0000")), "{found:?}"); +} diff --git a/docs/mcp-interface.md b/docs/mcp-interface.md index 784659c6..c94da9d4 100644 --- a/docs/mcp-interface.md +++ b/docs/mcp-interface.md @@ -760,7 +760,7 @@ What the books keep of a call, and what a repeat is told: **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 +strings in 78 tools; 109 free text, 18 reference, 2 phone, 6 address, 19 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 @@ -773,15 +773,20 @@ 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 +lead decided it within it); a *phone* (a party's `phone`, the bill-to's +`phone`) is read the same way, so `2065550142`, `206-555-0142`, +`(206) 555-0142`, `+1 206 555 0142` and `+44 20 7946 0958` pass and an SSN's +or an EIN's printed shape does not; an *address* (a party's `address`, +`billing_address` and `shipping_address`, the bill-to's) is a party field +except that a ZIP+4 (`98101-1234`) is kept; a *party's own field* +(a party's or a customer's or vendor's name, the bill-to's name, contact and +email, 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 +checks (`company.ein`, `company.state_entity_number`, which may be nine digits, +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 @@ -1631,7 +1636,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; free text such as a memo or a +single spaces or hyphens allowed between them; but a phone or fax number is +read by a tax id's printed shapes only, and an address keeps a ZIP+4; 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; diff --git a/docs/spec/claims/partner.md b/docs/spec/claims/partner.md index 4e0cdc0d..bc763c0c 100644 --- a/docs/spec/claims/partner.md +++ b/docs/spec/claims/partner.md @@ -129,7 +129,19 @@ 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. +accepted. And on 2026-11-21, after the strict reading refused every phone +number in a party's or an invoice's bill-to (a phone is ten digits or more), +the lead decided, within the same choice, that a *phone field* (a telephone +or fax number) is read as a reference is, by its own name +(`settings::holds_printed_tin_in_phone`): only the printed 3-2-4 and 2-7 +shapes are refused. Why not strict: a phone number is not a tax id's shape +by length, and nothing about its digits proves anything; why not a new +reading: a national number of nine digits is ordinary (Spain, France), so +the reference reading, which allows a bare nine digits, is the right one. A +postal *address* keeps the strict reading but for a ZIP+4 (`98101-1234`, nine +digits), which is a postal code (`parties::has_full_tin_in_address`). The +downside: a national phone number written 3-2-4 or 2-7 (`912 34 5678`) reads +as a tax id and is refused; write it another way. **Enforced:** `crate::parties` (has_full_tin, check_text, W9Facts::check, @@ -347,10 +359,28 @@ text two ways, on purpose: 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 phone field* (a party's `phone`, the bill-to's `phone`, the company's + own as the seller's) is refused only in the printed SSN and EIN shapes + (`settings::holds_printed_tin_in_phone`, the reference reading by its + own name, `parties::check_phone`): `2065550142`, `206-555-0142`, + `(206) 555-0142`, `+1 206 555 0142`, `+44 20 7946 0958` and an extension + pass. The tools' table has a class for it, and a test fails when a string + named for a phone or a fax is in any other. +- *A postal address* (a party's `address`, `billing_address` and + `shipping_address`, the bill-to's) is a party's own field read strictly, + except that a ZIP+4 is no tax id (`parties::has_full_tin_in_address`, + `parties::check_address`). +- *A registration number* (`company.state_entity_number`, which may be nine + digits: a Washington UBI) is a reference. No VAT or other foreign + registration-number field exists in a party or an invoice; `company.duns` + is a nine-digit number by its kind. - *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`). + digits (`has_full_tin`), but for the phone and the address above. Their + downsides: an email with nine digits in it (`123456789@example.com`), a + note or website with a nine-digit number, and a street number or a PO box + next to a postal code are refused. - *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 @@ -383,7 +413,7 @@ 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 +table that classes each string as free text, a reference, a phone, an address, 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 @@ -398,7 +428,9 @@ 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`, +`settings::check_reference_text`, `settings::holds_printed_tin_in_phone`, +`settings::check_phone_text`, `parties::check_phone`, `parties::check_address`, +`parties::has_full_tin_in_address`, `parties::check_note`, `parties::check_reference_note`, `PaymentDetails::check`, `PaymentDetails::description`, `Ledger::try_create_entry`, `Ledger::reverse_entry`, `Ledger::create_invoice_with`, @@ -410,7 +442,10 @@ warning, and never the number. `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` +**Checked:** `ledger-core` `tests/phone_text.rs` (phone formats of every country pass, +an SSN's and an EIN's shapes are refused in a phone field, a ZIP+4 passes, a +party and an invoice keep them, a state entity number may be nine digits); +`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 @@ -424,9 +459,10 @@ takes is classed) and `a_call_with_a_tax_id_in_free_text_is_refused_unrun_and_wr 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` +one and a phone as a phone); `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). +a reference is kept, a phone 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