From 548901ce7da6126d661bb01d3c493683bd307f73 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 14:51:47 -0700 Subject: [PATCH] feat(core): the engine refuses free text that looks like a tax id Entry and reversal descriptions, write-off and void reasons, document memos, references, duplicate reasons and line descriptions, asset descriptions, serials and tags, period names, account codes, schedule and recurring descriptions and payroll employee names now meet the one free-text detector in the Ledger command itself (FreeTextHoldsTin), so a caller other than the MCP layer cannot journal a tax id (BS-partner-2). Replay never refuses (BS-entry-4). Draft notes, discard reasons, no-party reasons and send references and notes move from the strict nine-digit reading to the shapes (parties::check_note), as the owner chose on 2026-11-21; party fields, names and recipients keep the strict reading. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-core/src/arap.rs | 58 ++++++++++++++++++++++++ crates/ledger-core/src/error.rs | 17 +++++++ crates/ledger-core/src/ledger.rs | 49 ++++++++++++++------ crates/ledger-core/src/parties.rs | 16 +++++++ crates/ledger-core/src/payroll.rs | 1 + crates/ledger-core/src/schedules.rs | 2 + crates/ledger-mcp/src/tools/documents.rs | 8 ++-- crates/ledger-mcp/src/tools/parties.rs | 2 +- crates/ledger-store/src/store.rs | 1 + 9 files changed, 136 insertions(+), 18 deletions(-) diff --git a/crates/ledger-core/src/arap.rs b/crates/ledger-core/src/arap.rs index 48ce38d2..9bedd331 100644 --- a/crates/ledger-core/src/arap.rs +++ b/crates/ledger-core/src/arap.rs @@ -1253,6 +1253,63 @@ 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 reference", reference), + ("the memo", memo), + ("the duplicate reason", duplicate_reason), + ] { + if let Some(t) = text { + LedgerError::free_text(field, 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 +1319,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..67fcc8c8 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,16 @@ 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) + } +} + /// 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/ledger.rs b/crates/ledger-core/src/ledger.rs index eae6a1b4..17cbe094 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::free_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::free_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::free_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::free_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,12 @@ 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 +6045,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 +6224,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_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) @@ -7262,6 +7283,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 +7395,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); diff --git a/crates/ledger-core/src/parties.rs b/crates/ledger-core/src/parties.rs index 194019cc..5e9c0ab7 100644 --- a/crates/ledger-core/src/parties.rs +++ b/crates/ledger-core/src/parties.rs @@ -717,6 +717,22 @@ 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, a reason or a reference; 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)?; + 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). 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-mcp/src/tools/documents.rs b/crates/ledger-mcp/src/tools/documents.rs index 3b615d72..f31b9561 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_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/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-store/src/store.rs b/crates/ledger-store/src/store.rs index c2791b03..0f7b1161 100644 --- a/crates/ledger-store/src/store.rs +++ b/crates/ledger-store/src/store.rs @@ -1801,6 +1801,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