From 1d612d25b86e920eb545d4e75048c91672a6a4d3 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Tue, 10 Nov 2026 00:06:49 -0700 Subject: [PATCH] refactor(mcp): Decimal arithmetic goes through the kernel (K-U12) The raw-decimal-arith detector counted 19 places in ledger-mcp before and counts 0 after. No figure changes. Sides become signs through money::on_side and money::signed_amount (server delta, report movement, the P&L-by-class normal-side figure, which collapses two matches into one call); sums and differences of books figures through add_in_range and sub_in_range; the checked sums in helpers and documents through Amount::checked_add with their error handling untouched. The count of withdrawn attachments (a usize, not a Decimal) is the length of the flattened withdraw lists instead of an Iterator::sum of their lengths: the same number. Co-Authored-By: Claude --- crates/ledger-mcp/src/server.rs | 6 +--- crates/ledger-mcp/src/tools/assets.rs | 9 ++++-- crates/ledger-mcp/src/tools/documents.rs | 4 +-- crates/ledger-mcp/src/tools/evidence.rs | 2 +- crates/ledger-mcp/src/tools/helpers.rs | 7 +++-- crates/ledger-mcp/src/tools/reports.rs | 33 +++++++++------------- crates/ledger-mcp/src/tools/settlements.rs | 9 +++--- 7 files changed, 34 insertions(+), 36 deletions(-) diff --git a/crates/ledger-mcp/src/server.rs b/crates/ledger-mcp/src/server.rs index fe3a7e61..7e2d51f5 100644 --- a/crates/ledger-mcp/src/server.rs +++ b/crates/ledger-mcp/src/server.rs @@ -1343,11 +1343,7 @@ fn preview_lines_for( .account_balance(*account_id) .map_err(|e| e.to_string())?; let normal = account.account_type.normal_side(); - let delta = if *side == normal { - amount.amount - } else { - -amount.amount - }; + let delta = ledger_core::money::on_side(normal, *side, amount.amount); let after = ledger_core::money::add_exact(before, delta, "the account's balance after the line") .map_err(|e| e.to_string())?; diff --git a/crates/ledger-mcp/src/tools/assets.rs b/crates/ledger-mcp/src/tools/assets.rs index 1d14f8a4..e2c20988 100644 --- a/crates/ledger-mcp/src/tools/assets.rs +++ b/crates/ledger-mcp/src/tools/assets.rs @@ -150,7 +150,7 @@ fn basis_out(a: &ledger_core::Asset) -> Result, String> { sec704c_1c_note: loss.map(|l| { format!( "a built-in loss of {}: it counts only for the contributing member(s); for the others the basis is treated as the value at contribution (IRC ยง704(c)(1)(C))", - money(-l) + money(ledger_core::money::neg(l)) ) }), sec704c_method: b.sec704c_method.map(|m| m.key().to_string()), @@ -748,7 +748,10 @@ impl BooksServer { accumulated_posted: figure(|r| r.accumulated_posted), accumulated_scheduled_through: figure(|r| r.accumulated_scheduled), unposted_depreciation: figure(|r| { - r.accumulated_scheduled - r.accumulated_posted + ledger_core::money::sub_in_range( + r.accumulated_scheduled, + r.accumulated_posted, + ) }), book_value: figure(|r| r.book_value), schedule_error, @@ -930,7 +933,7 @@ impl BooksServer { proceeds.amount, preview.catch_up_depreciation, if preview.gain_loss < Decimal::ZERO { - -preview.gain_loss + ledger_core::money::neg(preview.gain_loss) } else { Decimal::ZERO }, diff --git a/crates/ledger-mcp/src/tools/documents.rs b/crates/ledger-mcp/src/tools/documents.rs index d6c61f54..3b615d72 100644 --- a/crates/ledger-mcp/src/tools/documents.rs +++ b/crates/ledger-mcp/src/tools/documents.rs @@ -7,6 +7,7 @@ use super::*; use ledger_core::Terms; use ledger_core::arap::{self, PartySnapshot}; +use ledger_core::kernel::Amount; /// A document's id. fn doc_id(doc: ledger_core::DocRef) -> u64 { @@ -934,8 +935,7 @@ impl BooksServer { if !keep { continue; } - owed = owed - .checked_add(st.outstanding) + owed = Amount::checked_add(owed, st.outstanding) .ok_or("the total is too large to compute")?; rows.push(( due, diff --git a/crates/ledger-mcp/src/tools/evidence.rs b/crates/ledger-mcp/src/tools/evidence.rs index ff33e10f..c6889dbd 100644 --- a/crates/ledger-mcp/src/tools/evidence.rs +++ b/crates/ledger-mcp/src/tools/evidence.rs @@ -330,7 +330,7 @@ impl BooksServer { links: g.link.iter().map(|s| subject_out(&store, *s)).collect(), }) .collect(); - let withdrawn = out_groups.iter().map(|g| g.withdraw.len()).sum(); + let withdrawn = out_groups.iter().flat_map(|g| g.withdraw.iter()).count(); let digest = self.preview_of( &store, "books.consolidate_duplicates", diff --git a/crates/ledger-mcp/src/tools/helpers.rs b/crates/ledger-mcp/src/tools/helpers.rs index 373314a2..f0d1006e 100644 --- a/crates/ledger-mcp/src/tools/helpers.rs +++ b/crates/ledger-mcp/src/tools/helpers.rs @@ -7,6 +7,7 @@ use super::*; use ledger_core::InstrumentId; +use ledger_core::kernel::Amount; use ledger_store::StoreError; /// The book's id, as the commands given to agents name it: its folder's @@ -462,7 +463,7 @@ pub(crate) fn checked_sum( ) -> Result { values.into_iter().try_fold(Decimal::ZERO, |sum, v| { let v = v.map_err(|e| e.to_string())?; - sum.checked_add(v).ok_or_else(|| { + Amount::checked_add(sum, v).ok_or_else(|| { ledger_core::LedgerError::TooLargeToCompute(what.to_string()).to_string() }) }) @@ -548,7 +549,9 @@ pub(crate) fn lines_settled(entry: &JournalEntry) -> bool { .lines() .iter() .filter(|l| l.side == s) - .try_fold(Decimal::ZERO, |sum, l| sum.checked_add(l.amount.amount)) + .try_fold(Decimal::ZERO, |sum, l| { + Amount::checked_add(sum, l.amount.amount) + }) }; match (side(Side::Debit), side(Side::Credit)) { (Some(debits), Some(credits)) => !entry.lines().is_empty() && debits == credits, diff --git a/crates/ledger-mcp/src/tools/reports.rs b/crates/ledger-mcp/src/tools/reports.rs index 59d0569d..8e411d63 100644 --- a/crates/ledger-mcp/src/tools/reports.rs +++ b/crates/ledger-mcp/src/tools/reports.rs @@ -4,6 +4,7 @@ //! Split whole out of `server.rs` (plan/served.md 8.2 U0a). use super::*; +use ledger_core::money::{add_in_range, sub_in_range}; /// What the digest lists from the control check: each line on a control /// account that is no document's, and each document needing attention. @@ -37,18 +38,15 @@ fn movement_over( .iter() .flat_map(|e| e.lines()) .filter(|l| l.account == account), - |l| match l.side { - Side::Debit => l.amount.amount, - Side::Credit => -l.amount.amount, - }, + |l| ledger_core::money::signed_amount(l.side, l.amount.amount), "an account's movement", ) .map_err(|e| e.to_string())?; let account = ledger.chart().get(account).expect("account exists"); - Ok(match account.account_type.normal_side() { - Side::Debit => movement, - Side::Credit => -movement, - }) + Ok(ledger_core::money::signed_amount( + account.account_type.normal_side(), + movement, + )) } fn lines_out(lines: &[ledger_core::StatementLine]) -> Vec { @@ -1057,19 +1055,16 @@ impl BooksServer { Some(a) => a, _ => continue, }; - let signed = match line.side { - Side::Debit => line.amount.amount, - Side::Credit => -line.amount.amount, - }; // Normal-side positive. - let normal = match account.account_type.normal_side() { - Side::Debit => signed, - Side::Credit => -signed, - }; + let normal = ledger_core::money::on_side( + account.account_type.normal_side(), + line.side, + line.amount.amount, + ); let acc = by_class.entry(line.class_id).or_default(); match account.account_type { - AccountType::Revenue => acc.revenue += normal, - AccountType::Expense => acc.expenses += normal, + AccountType::Revenue => acc.revenue = add_in_range(acc.revenue, normal), + AccountType::Expense => acc.expenses = add_in_range(acc.expenses, normal), _ => {} } } @@ -1099,7 +1094,7 @@ impl BooksServer { class, revenue: money(acc.revenue), expenses: money(acc.expenses), - net_income: money(acc.revenue - acc.expenses), + net_income: money(sub_in_range(acc.revenue, acc.expenses)), }) .collect(); Ok(Json(ProfitAndLossByClassOut { diff --git a/crates/ledger-mcp/src/tools/settlements.rs b/crates/ledger-mcp/src/tools/settlements.rs index 0efc010c..b6322280 100644 --- a/crates/ledger-mcp/src/tools/settlements.rs +++ b/crates/ledger-mcp/src/tools/settlements.rs @@ -6,6 +6,7 @@ //! there and this slice's do not collide (plan/served.md 8.2 P4b S6). use super::*; +use ledger_core::money::{add_in_range, sub_in_range}; /// A document as the payment tools and the agings name it ("invoice:7", /// "bill:12"). @@ -257,7 +258,7 @@ fn payment_out( let mut documents = Vec::with_capacity(params.applications.len()); let mut deposited = Decimal::ZERO; for app in ¶ms.applications { - deposited += app.cash; + deposited = add_in_range(deposited, app.cash); let st = ledger .doc_state(app.doc, chrono::NaiveDate::MAX) .map_err(|e| e.to_string())? @@ -270,7 +271,7 @@ fn payment_out( }); } let fee = params.fee.as_ref().map_or(Decimal::ZERO, |f| f.amount); - deposited -= fee; + deposited = sub_in_range(deposited, fee); let (remaining, status) = match documents.as_slice() { [one] => (Some(one.outstanding.clone()), Some(one.status.clone())), _ => (None, None), @@ -413,7 +414,7 @@ impl BooksServer { Some((by, max)) if by >= as_of => ( Some(by.to_string()), Some(money(max)), - Some(money(st.outstanding - max)), + Some(money(sub_in_range(st.outstanding, max))), ), _ => (None, None, None), }; @@ -438,7 +439,7 @@ impl BooksServer { let mut by_date = Vec::new(); let mut running = Decimal::ZERO; for (bill, owed) in &bills { - running += owed; + running = add_in_range(running, *owed); match by_date.last_mut() { Some(DueDateTotalOut { date, amount }) if *date == bill.due_date => { *amount = money(running);