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

+112
View File
@@ -1512,6 +1512,118 @@ pub fn unrecovered_cost<T: Amount>(revenue: T, expenses: T) -> Option<T> {
Some(if gap > T::ZERO { gap } else { T::ZERO })
}
/// Where a document's running balance first leaves `0 ..= total`, if it
/// ever does ([`running_bounds`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Bounds {
/// Every running balance is within `0 ..= total`.
Within,
/// After step `i` (0-based) the balance is below zero: more paid than
/// the document is for, or a void under a payment that stands.
Below(usize),
/// After step `i` the balance is above the total: more owed than the
/// document is for (a payment's reversal re-instating its document's
/// origin beside another).
Above(usize),
/// A running balance can't be represented exactly.
Overflow,
}
/// A document's bounds over time: `deltas` are what each date moves its
/// outstanding balance by, in date order (one per date, that date's
/// movements summed), starting from nothing owed.
///
/// ```text
/// GOAL: one definition of "a document is never overpaid and never owes
/// more than it is for", at every date, not only at the end.
/// SOURCE: docs/spec/rules.md B-38 INVARIANT 2 (0 <= outstanding(d, D)
/// <= total(d) at every D); plan/served.md P4b.3 (Bounds).
/// INVARIANTS:
/// 1. Within exactly when every prefix sum of `deltas` is within
/// 0 ..= total; else the first prefix that isn't: Below when it is
/// under zero, Above when it is over the total.
/// 2. NEVER wraps: Overflow when a prefix sum can't be represented.
/// 3. Empty `deltas` is Within (nothing owed, nothing paid).
/// ```
pub fn running_bounds<T: Amount>(total: T, deltas: &[T]) -> Bounds {
let mut running = T::ZERO;
for (i, &d) in deltas.iter().enumerate() {
running = match running.checked_add(d) {
Some(r) => r,
None => return Bounds::Overflow,
};
if running < T::ZERO {
return Bounds::Below(i);
}
if running > total {
return Bounds::Above(i);
}
}
Bounds::Within
}
/// How far a running balance is outside `0 ..= total` (zero inside), and
/// whether below; `None` when that can't be represented.
fn out_of_bounds<T: Amount>(total: T, running: T) -> Option<(T, bool)> {
if running < T::ZERO {
Some((running.checked_neg()?, true))
} else if running > total {
Some((running.checked_sub(total)?, false))
} else {
Some((T::ZERO, false))
}
}
/// Whether moving a document from `before` to `after` keeps its bounds:
/// both are its movements by date over the same dates (a date with
/// nothing moving is zero). At every date, `after` must be within
/// `0 ..= total`, or no further outside than `before` was there.
///
/// ```text
/// GOAL: a command never puts a document out of bounds, yet books an
/// earlier version left out of bounds (a void under a payment that
/// stands) take the step that mends them.
/// SOURCE: docs/spec/rules.md B-38 INVARIANT 2, B-28 (replay accepts what
/// was written; the bound is the commands'); plan/served.md
/// P4b.14 item 3 (the remedy: reverse the payment).
/// INVARIANTS:
/// 1. When `before` is within bounds at every date (running_bounds is
/// Within), the result is running_bounds(total, after): the
/// definition exactly.
/// 2. Within means no prefix of `after` is further outside 0 ..= total
/// than the same prefix of `before`; else the first prefix that is,
/// Below or Above by where it went. Only the distance counts, not
/// the side: books out of bounds below (overpaid by 5) may take a
/// step that leaves them above by 3 (over-owed), nearer the range.
/// Intended: any step that mends is taken, and these commands
/// never write a book out of bounds in the first place (INVARIANT 1).
/// 3. NEVER wraps: Overflow when a prefix can't be represented.
/// 4. Slices of different lengths: the missing movements are zero.
/// ```
pub fn bounds_kept<T: Amount>(total: T, before: &[T], after: &[T]) -> Bounds {
let (mut was, mut now) = (T::ZERO, T::ZERO);
for i in 0..before.len().max(after.len()) {
let step = |r: T, d: Option<&T>| r.checked_add(d.copied().unwrap_or(T::ZERO));
let (Some(w), Some(n)) = (step(was, before.get(i)), step(now, after.get(i))) else {
return Bounds::Overflow;
};
(was, now) = (w, n);
let (Some((by_was, _)), Some((by_now, below))) =
(out_of_bounds(total, was), out_of_bounds(total, now))
else {
return Bounds::Overflow;
};
if by_now > by_was {
return if below {
Bounds::Below(i)
} else {
Bounds::Above(i)
};
}
}
Bounds::Within
}
#[cfg(test)]
mod tests {
use super::*;