feat(arap)!: documents read their figures from standing lines; control accounts
check / check (push) Canceled after 0s

refuse hand entries (P4b S1, part A)

Plan P4b (D-45), slice S1, the engine half: rules.md B-38.

- ledger-core: every receivables or payables line carries its document
  (Ledger.line_docs: DocRef, Movement, DocTag), written by the document
  commands in the step that posts it, derived on replay from the existing
  document events (the role's account as it stood then; payments by the
  ordinal rule), copied onto a reversal's mirror. Ledger::stands_on;
  doc_state / invoice_state / bill_state (total, paid, outstanding,
  status Open/Partial/Paid/WrittenOff/Void, overdue days) as of any day;
  ar_aging / ap_aging read them, so reversed payments and voids are right.
  The control guard (add_line, add_line_fx, post_entry,
  register_recurring) refuses untagged lines on receivables/payables,
  exempting a reversal's mirror of a legacy line; replay never refuses.
  Bounds (kernel::running_bounds, bounds_kept) on payments and reversals;
  a document reversal never dated before its entry; deposit/payer accounts
  must be cash-like and hold no role. New API: receive_payment_with /
  pay_bill_with (PaymentDetails: instrument, reference), void_document /
  check_void_document, control_check, payments_recorded,
  standing_payments, replay_reverse_entry. Invoice.amount_paid/status
  remain only as derived caches for the MCP layer until part B.
  cashflow bill_splits reads payments from the tags.
- ledger-store: journal feature document_standing (D-39 gated) for a
  payment accepted only because an earlier one was reversed;
  receive_payment_with / pay_bill_with (instrument journaled as
  entry.instrument_set, reference in the description), void_document;
  replay uses replay_reverse_entry; schema 15 drops the projection's
  amount_paid/status. Fixture p4-arap-before + golden figures written by
  the version before S1, adjudicated in arap_standing.rs.
- ledger-gui: party card, cash "coming up" and company owed totals read
  doc_state as of today (late from the derived state).
- Lean Documents.lean (control_agrees and friends); Kani
  bounds_check_matches_definition,
bounds_kept_is_the_definition_on_books_in_bounds;
  rules B-38, B-18/B-23 amended; bookspec `older = true` for legacy hand
  lines; tests that hand-post to 1200/2000 post as replay or renumbered.

Review fixes (both reviews of part A):
- control_role_of guards only an account the role is assigned to or one
  holding its documents' lines (a chart's own 1200 Equipment or card at
  2000 is free until a document posts there); payment accounts check
  other roles by holds_role (type-checked). The MCP tests that failed on
  the guard (oracle_mcp, spec_projects) pass unchanged.
- standing_payments leaves out reversals (sorted, deduped); replayed
  tags match the movement's side; payments_recorded counts every payment
  event (tagged or not, Ledger.payment_events) and refuses overflow.
- The record caches settled (paid + discounted + written off) and owed
  (Invoice/Bill.owed, never serialized): a void never reads as paid.
- assign_role: receivables/payables refuse moving onto an account with
  untagged lines (RoleAccountHasHandLines) and, on their control account
  holding a balance, say DocumentRoleHoldsBalance (no hand entry named);
  B-23 reworded. The reversal-mirror exemption only takes a hand line
  off (even chain depth); putting it back is refused.
- DocStatus Overpaid and Unattached; aging leaves out credit balances;
  ControlCheck.attention lists out-of-bounds and unattached documents.
- stands_on counts a chain in order; indexes (doc_index, doc_accounts,
  order_pos, reversed_by) keep the derived figures linear.
- Viewer reads a post-dated document as of its own date; one state per
  row. bounds_kept's side-crossing documented as intended.
- Tests: ten new spec_documents scenarios, stronger proptests, store
  proptest arap_props (live = replay = snapshot at every date, closed
  months), fuzz ops void/payments with details, a GUI post-dated test;
  Lean Step.assign / Step.release with unattached_zero kept; model
  limits stated in docs/testing.md and B-38.
Review fixes (CPA and engineering lenses): only an assigned role's
account or one holding document lines is a control account (a chart's
own 1200 asset stays free); a role can't move onto untagged lines or off
document lines (Lean Step.assign); a void's cache never reads as paid;
no Decimal sum panics; per-document indexes keep figures linear; a
replayed tag matches its side; the feature gate counts payment events;
a payment's reversal is never listed as standing; an overpaid document
has its own status; the viewer keeps post-dated documents.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T3gXMVt7XJPi6ens1or9Dj
This commit is contained in:
swaitsandClaude Opus 5.5 committed 2026-10-24 09:17:42 -06:00
1 parent 7741e96eb3
commit d7fa16e974
54 files changed
+5997 -649

No files matched your search

+56 -5
View File
@@ -179,9 +179,10 @@ pub fn period_month(period: &str) -> Option<(i32, u32)> {
/// 3. invoiced_ytd = Σ Invoice::total() over its customer record's
/// invoices dated in the year; billed_ytd the same for its vendor
/// record's bills.
/// 4. open_invoices = Σ Invoice::balance() over its customer record's
/// invoices; open_bills = Σ Bill::balance() over its vendor record's
/// bills (any date: what is still owed today).
/// 4. open_invoices = Σ what each of its customer record's invoices
/// owes today (Books::owed_today: read from the ledger lines tagged
/// with it, so a reversed payment or a void counts as it should,
/// rules.md B-38); open_bills the same for its vendor record's bills.
/// 4a. Each of 3 and 4 is None when it can't be summed exactly (a
/// document is restored as an earlier version journaled it, of any
/// size: rules.md B-28), never a wrong number.
@@ -1138,7 +1139,10 @@ impl Books {
.and_then(|p| out.get_mut(&p))
{
info.invoices.push(id);
add(&mut info.open_invoices, inv.balance());
add(
&mut info.open_invoices,
self.owed_today(ledger_core::DocRef::Invoice(id)),
);
if in_year(inv.date) {
add(&mut info.invoiced_ytd, inv.total());
}
@@ -1151,7 +1155,10 @@ impl Books {
.and_then(|p| out.get_mut(&p))
{
info.bills.push(id);
add(&mut info.open_bills, bill.balance());
add(
&mut info.open_bills,
self.owed_today(ledger_core::DocRef::Bill(id)),
);
if in_year(bill.date) {
add(&mut info.billed_ytd, bill.total());
}
@@ -1309,6 +1316,38 @@ impl Books {
.collect()
}
/// A document as of today: what it is, read from the ledger lines
/// tagged with it (ledger_core::Ledger::doc_state, rules.md B-38), the
/// figures books.ar_aging and books.party read. One dated after today
/// (a post-dated bill) is read as of its own date: what it will owe
/// when it is issued, so the forward-looking views keep it; it is
/// never late. `Ok(None)` only for an unknown document.
pub fn doc_today(
&self,
doc: ledger_core::DocRef,
) -> Result<Option<ledger_core::DocState>, ledger_core::LedgerError> {
let date = match doc {
ledger_core::DocRef::Invoice(id) => self.ledger.get_invoice(id).map(|i| i.date),
ledger_core::DocRef::Bill(id) => self.ledger.get_bill(id).map(|b| b.date),
};
let Some(date) = date else {
return Ok(None);
};
self.ledger.doc_state(doc, self.today.max(date))
}
/// What a document owes today ([`Self::doc_today`]: one dated after
/// today, what it will owe on its date); refused when it can't be
/// computed (shown as such, never as a wrong number).
pub fn owed_today(
&self,
doc: ledger_core::DocRef,
) -> Result<Decimal, ledger_core::LedgerError> {
Ok(self
.doc_today(doc)?
.map_or(Decimal::ZERO, |st| st.outstanding))
}
/// The subjects whose documents an entry's page shows: the entry, and
/// the invoice, bill, or payroll run it records (those have no page
/// of their own).
@@ -2193,6 +2232,18 @@ fn disposal_true_up(
.map_or(Decimal::ZERO, |t| t - runs)
}
/// What a document's state ([`Books::doc_today`]) says it owes, read once
/// for both the row and its flags: `None` when it can't be computed
/// (shown as such, never as a wrong number); nothing for an unknown one.
pub fn owed_of(
state: &Result<Option<ledger_core::DocState>, ledger_core::LedgerError>,
) -> Option<Decimal> {
match state {
Ok(st) => Some(st.map_or(Decimal::ZERO, |st| st.outstanding)),
Err(_) => None,
}
}
/// Entry ids a journal line refers to.
pub fn entry_refs(line: &JournalLine) -> Vec<EntryId> {
let p = &line.payload;
+7 -4
View File
@@ -328,7 +328,10 @@ fn coming_up(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
let Some(inv) = b.ledger.get_invoice(id) else {
continue;
};
let balance = inv.balance().ok();
// As of today, from the lines tagged with it (rules.md B-38): a
// reversed payment reopens it, a void closes it.
let state = b.doc_today(ledger_core::DocRef::Invoice(id));
let balance = crate::books::owed_of(&state);
if balance.is_some_and(|x| x.is_zero()) {
continue;
}
@@ -337,7 +340,7 @@ fn coming_up(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
.get_customer(inv.customer_id)
.map(|c| c.name.clone())
.unwrap_or_default();
let late = inv.due_date < b.today;
let late = matches!(state, Ok(Some(st)) if st.overdue_days > 0);
items.push(Upcoming {
date: inv.due_date,
label: format!(
@@ -352,7 +355,7 @@ fn coming_up(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
let Some(bill) = b.ledger.get_bill(id) else {
continue;
};
let balance = bill.balance().ok();
let balance = crate::books::owed_of(&b.doc_today(ledger_core::DocRef::Bill(id)));
if balance.is_some_and(|x| x.is_zero()) {
continue;
}
@@ -645,7 +648,7 @@ mod tests {
let mut b = Build::new("coming-up");
let (cash, capital, rent) = (b.cash, b.capital, b.rent);
let accrued =
b.s.add_account("2000", "Accrued", AccountType::Liability, None, false)
b.s.add_account("2100", "Accrued", AccountType::Liability, None, false)
.unwrap();
b.post(d(2026, 1, 2), cash, capital, 1_000_000);
let usd = |c: i64| Money::new(cents(c), Currency::USD);
+5 -1
View File
@@ -714,7 +714,11 @@ fn parties(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
let owed = (1..b.ledger.next_invoice_id())
.filter_map(|i| b.ledger.get_invoice(i))
.filter(|i| i.customer_id == c.id)
.try_fold(Decimal::ZERO, |t, i| t.checked_add(i.balance().ok()?));
.try_fold(Decimal::ZERO, |t, i| {
t.checked_add(
b.owed_today(ledger_core::DocRef::Invoice(i.id)).ok()?,
)
});
ui.horizontal_wrapped(|ui| {
name(ui, &c.name, b.ledger.party_of_customer(c.id));
ui.with_layout(
+22 -7
View File
@@ -1400,13 +1400,15 @@ fn documents_card(ui: &mut Ui, b: &Books, info: &PartyInfo, go: &mut Option<Rout
.iter()
.filter_map(|i| b.ledger.get_invoice(*i))
.map(|i| {
let state = b.doc_today(ledger_core::DocRef::Invoice(i.id));
let owed = crate::books::owed_of(&state);
(
format!("Invoice {}", i.id),
i.date,
i.due_date,
i.status,
state,
i.total().ok(),
i.balance().ok(),
owed,
i.entry_id,
)
});
@@ -1415,20 +1417,33 @@ fn documents_card(ui: &mut Ui, b: &Books, info: &PartyInfo, go: &mut Option<Rout
.iter()
.filter_map(|i| b.ledger.get_bill(*i))
.map(|i| {
let state = b.doc_today(ledger_core::DocRef::Bill(i.id));
let owed = crate::books::owed_of(&state);
(
format!("Bill {}", i.id),
i.date,
i.due_date,
i.status,
state,
i.total().ok(),
i.balance().ok(),
owed,
i.entry_id,
)
});
let mut docs: Vec<_> = invoices.chain(bills).collect();
docs.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
for (name, date, due, status, total, balance, entry) in docs {
let late = !balance.is_some_and(|x| x.is_zero()) && due < b.today;
for (name, date, due, state, total, balance, entry) in docs {
// Late and its status as of today, from the ledger
// lines tagged with it (rules.md B-38; P4b.2 gap 10):
// a reversed payment makes it owed again, a void
// never late.
let late = matches!(state, Ok(Some(st)) if st.overdue_days > 0);
let status = match state {
// Read as of its own date (Books::doc_today).
Ok(Some(_)) if date > b.today => "Dated ahead",
Ok(Some(st)) => st.status.label(),
Ok(None) => "Unknown",
Err(_) => "Can't compute",
};
let resp = row(
ui,
w,
@@ -1441,7 +1456,7 @@ fn documents_card(ui: &mut Ui, b: &Books, info: &PartyInfo, go: &mut Option<Rout
false,
if late { p.warning } else { p.text },
),
(fmt::words(&format!("{status:?}")), 90.0, false, p.muted),
(status.to_string(), 90.0, false, p.muted),
(fmt::money_or(total), amt, true, p.text),
(fmt::money_or(balance), amt, true, p.text),
],
+46
View File
@@ -2060,3 +2060,49 @@ fn the_journal_says_what_each_1099_record_did() {
]
);
}
/// A document dated after today is read as of its own date (Books::doc_today):
/// a post-dated bill still owes its total in the party's open bills (and
/// in Cash's "Coming up"), and is never late; one dated today or before
/// reads as of today (review of P4b S1: the viewer dropped post-dated
/// documents).
#[test]
fn a_post_dated_bill_still_shows_what_it_will_owe() {
let dir = TempDir::new("post-dated");
let data = dir.0.join("books-data");
let mut s = Store::create(&data, Currency::USD).unwrap();
let bank = s
.add_account("1000", "Checking", AccountType::Asset, None, false)
.unwrap();
let vendor = s.add_vendor("Tobin Harlow Supply").unwrap();
let later = s
.create_bill(vendor, d(2026, 11, 1), d(2026, 12, 1), doc(45_000))
.unwrap();
let now = s
.create_bill(vendor, d(2026, 9, 1), d(2026, 9, 30), doc(10_000))
.unwrap();
s.pay_bill(now, d(2026, 9, 10), cents(4_000), bank).unwrap();
drop(s);
let b = load(&dir.0);
let ahead = b
.doc_today(ledger_core::DocRef::Bill(later))
.unwrap()
.expect("read as of its own date");
assert_eq!((ahead.outstanding, ahead.overdue_days), (cents(45_000), 0));
let late = b
.doc_today(ledger_core::DocRef::Bill(now))
.unwrap()
.unwrap();
assert_eq!(late.outstanding, cents(6_000));
assert!(late.overdue_days > 0, "{late:?}");
let party = b
.ledger
.party_of_vendor(vendor)
.and_then(|p| b.party(p).cloned())
.unwrap();
assert_eq!(party.open_bills, Some(cents(51_000)));
assert_eq!(
b.owed_today(ledger_core::DocRef::Bill(later)),
Ok(cents(45_000))
);
}
+1 -1
View File
@@ -67,7 +67,7 @@ fn fixture(tag: &str) -> Fixture {
let mut s = Store::create(&data_dir, Currency::USD).unwrap();
let mut add = |code: &str, name: &str, ty| s.add_account(code, name, ty, None, false).unwrap();
let cash = add("1000", "Cash", AccountType::Asset);
let devices = add("1200", "Equipment", AccountType::Asset);
let devices = add("1500", "Equipment", AccountType::Asset);
let revenue = add("4000", "Design Services", AccountType::Revenue);
let contractors = add("6000", "Contractors", AccountType::Expense);
let rent = add("6200", "Rent", AccountType::Expense);
+13 -7
View File
@@ -82,13 +82,19 @@ fn build(plan: &Plan, tag: &str) -> (TestDir, Source, ledger_core::Ledger) {
.iter()
.map(|(c, n, t)| s.add_account(c, n, *t, None, false).unwrap())
.collect();
for &(back, dr, cr, cents) in &plan.entries {
let e = s.create_entry(plan.today - Days::new(back), "x").unwrap();
let m = Money::new(Decimal::new(cents, 2), Currency::USD);
s.add_line(e, ids[dr], Side::Debit, m).unwrap();
s.add_line(e, ids[cr], Side::Credit, m).unwrap();
s.post_entry(e).unwrap();
}
// As replay posts them: random lines land on receivables and payables
// by hand, as books an earlier version wrote can hold them (the
// control guard, rules.md B-38, refuses them as new work), and the
// overview must still read them.
ledger_core::parties::replaying(|| {
for &(back, dr, cr, cents) in &plan.entries {
let e = s.create_entry(plan.today - Days::new(back), "x").unwrap();
let m = Money::new(Decimal::new(cents, 2), Currency::USD);
s.add_line(e, ids[dr], Side::Debit, m).unwrap();
s.add_line(e, ids[cr], Side::Credit, m).unwrap();
s.post_entry(e).unwrap();
}
});
journal_settings(
&mut s,
&format!(