Merge branch 'main' into t3/k-u3-kernel-shares

This commit is contained in:
swaits committed 2026-11-09 01:05:05 -07:00
commit 73879044b2
44 files changed
+3908 -241

No files matched your search

+3 -1
View File
@@ -133,7 +133,9 @@ So the bar, for every agent, every change:
`verify/lean` — wanderbooks requires that package and holds no copy of
it. Laws about the books over time are theorems about `Reachable`
states. A new `Ledger` command is a new `Step` constructor, with its
preservation proof. No `sorry`, ever; `Audit.lean` lists every theorem.
preservation proof. No `sorry`, ever; bookspec's `lean/Audit.lean`
lists every theorem, and `just prove` audits that file from the pinned
package (wanderbooks keeps no copy of it).
After landing a law in bookspec, move wanderbooks' pin to that rev in
`verify/lean/lakefile.toml` and `lake-manifest.json` **and** in the
crates' `Cargo.toml` (the checker and the Lean must be the same spec
Generated
+2 -2
View File
@@ -788,7 +788,7 @@ dependencies = [
[[package]]
name = "bookspec-checker"
version = "0.1.0"
source = "git+https://git.swaits.com/swaits/bookspec?rev=51375ecd529b3189af7f6316b0347d4ec6134cf1#51375ecd529b3189af7f6316b0347d4ec6134cf1"
source = "git+https://git.swaits.com/swaits/bookspec?rev=00b7c541d784696961a760f0486e2fe7a5e7c003#00b7c541d784696961a760f0486e2fe7a5e7c003"
dependencies = [
"chrono",
"include_dir",
@@ -801,7 +801,7 @@ dependencies = [
[[package]]
name = "bookspec-runner"
version = "0.1.0"
source = "git+https://git.swaits.com/swaits/bookspec?rev=51375ecd529b3189af7f6316b0347d4ec6134cf1#51375ecd529b3189af7f6316b0347d4ec6134cf1"
source = "git+https://git.swaits.com/swaits/bookspec?rev=00b7c541d784696961a760f0486e2fe7a5e7c003#00b7c541d784696961a760f0486e2fe7a5e7c003"
dependencies = [
"bookspec-checker",
"serde_json",
+62
View File
@@ -496,6 +496,68 @@ fn terms_fall_back_in_order() {
assert_eq!(bill["terms"], "Net 10", "{bill}");
}
/// BS-arap-3 statement 1 through the tool: terms "Due 2026-11-15", from
/// the caller or from a party's defaults, make an invoice or a bill due on
/// the 15th, not on the document's own date; a document dated after the
/// agreed day is refused and writes nothing.
#[test]
fn custom_terms_are_due_on_the_date_they_give() {
let books = Books::new("documents-custom-terms");
let mut m = Mcp::spawn(&books);
let harbor = m.customer("Harbor Coffee");
let line = json!([{"description": "Work", "amount": "100.00"}]);
let invoice = |date: &str, extra: Value| {
let mut args = json!({"customer": harbor.to_string(), "date": date,
"lines": line, "confirmed": true});
for (k, v) in extra.as_object().unwrap() {
args[k] = v.clone();
}
args
};
// Terms given.
let given = m.call(
"books.create_invoice",
invoice("2026-11-01", json!({"terms": "Due 2026-11-15"})),
);
assert_eq!(given["due_date"], "2026-11-15", "{given}");
assert_eq!(given["terms"], "Due 2026-11-15", "{given}");
// The customer's default terms.
let party = m.party_of("Harbor Coffee");
m.call(
"books.update_party",
json!({"party": party.to_string(), "default_terms_as_customer": "Due 2026-12-01"}),
);
let by_party = m.call("books.create_invoice", invoice("2026-11-02", json!({})));
assert_eq!(by_party["due_date"], "2026-12-01", "{by_party}");
assert_eq!(by_party["terms"], "Due 2026-12-01", "{by_party}");
// A bill, terms given.
let coast = m.vendor("Coastline Hosting");
m.expense("6500", "Hosting");
let file = m.upload(b"coastline", "coastline.pdf", "receipt");
let bill = m.call(
"books.create_bill",
json!({"vendor": coast.to_string(), "date": "2026-11-01", "vendor_ref": "CH-1",
"terms": "Due 2026-11-20",
"lines": [{"description": "Hosting", "amount": "100.00", "account": "6500"}],
"upload_id": file, "confirmed": true}),
);
assert_eq!(bill["due_date"], "2026-11-20", "{bill}");
// Dated after the agreed day: refused.
let before = books.journal();
let late = m
.try_call(
"books.create_invoice",
invoice("2026-11-16", json!({"terms": "Due 2026-11-15"})),
)
.unwrap_err();
assert!(late.contains("due"), "{late}");
assert_eq!(books.journal(), before, "a refusal writes nothing");
}
/// A customer given by id and by name is the same record (the old
/// `party_id` spelling is gone, P5); a number that is one record's id and
/// another's name is refused, never guessed.
+2 -2
View File
@@ -33,8 +33,8 @@ num-rational = "0.4"
toml = "1"
# The specification lives in its own repository (P13 step 6, D-34, D-65),
# pinned to a commit.
bookspec-checker = { git = "https://git.swaits.com/swaits/bookspec", rev = "51375ecd529b3189af7f6316b0347d4ec6134cf1" }
bookspec-runner = { git = "https://git.swaits.com/swaits/bookspec", rev = "51375ecd529b3189af7f6316b0347d4ec6134cf1" }
bookspec-checker = { git = "https://git.swaits.com/swaits/bookspec", rev = "00b7c541d784696961a760f0486e2fe7a5e7c003" }
bookspec-runner = { git = "https://git.swaits.com/swaits/bookspec", rev = "00b7c541d784696961a760f0486e2fe7a5e7c003" }
ledger-package = { path = "../ledger-package" }
ledger-import = { path = "../ledger-import" }
ledger-store = { path = "../ledger-store" }
+76 -14
View File
@@ -497,9 +497,9 @@ pub enum TermsKind {
/// Due `n` days after the last day of the document's month (Net n
/// EOM).
NetEom(u16),
/// Due on a date the parties agreed; the caller passes it to
/// [`Terms::due_date`], and [`Terms::describe`] carries it for
/// people.
/// Due on a date the parties agreed. The date lives in the [`Terms`]
/// ([`Terms::agreed_date`]); [`Terms::due_date`] returns it, and
/// [`Terms::describe`] prints it for people.
Custom,
}
@@ -523,7 +523,8 @@ pub struct EarlyDiscount {
/// goods; for services, the contract.
/// INVARIANTS:
/// 1. Net n = date + n; Net n EOM = the last day of date's month + n;
/// due on receipt = date; Custom = the given date. Every result is
/// due on receipt = date; Custom = the date the terms give (never
/// the document's own date). Every result is
/// >= the document date and in the calendar (calendar::check); n is
/// 0..=3650.
/// 2. discount_by = date + d, d < the net days; no discount with due on
@@ -532,6 +533,7 @@ pub struct EarlyDiscount {
/// canonical spellings, case-insensitively, and nothing else.
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "TermsWire")]
pub struct Terms {
/// How the due date counts.
kind: TermsKind,
@@ -541,6 +543,52 @@ pub struct Terms {
/// The canonical text: "Net 30", "Net 15 EOM", "2/10 net 30", "Due on
/// receipt", "Due 2026-11-15".
text: String,
/// The date custom terms give, and only custom terms: `Some` exactly
/// when `kind` is [`TermsKind::Custom`]. Terms stored before this field
/// existed carry the date only in their text; reading them fills it
/// from there ([`TermsWire`]).
#[serde(default, skip_serializing_if = "Option::is_none")]
agreed: Option<NaiveDate>,
}
/// Terms as stored. Reading is the one place a missing `agreed` is filled
/// from the canonical text ("Due 2026-11-15"), so a book written before
/// custom terms carried their date still reads, and a Custom without any
/// readable date is refused rather than invented.
#[derive(Deserialize)]
struct TermsWire {
kind: TermsKind,
#[serde(default)]
discount: Option<EarlyDiscount>,
text: String,
#[serde(default)]
agreed: Option<NaiveDate>,
}
impl TryFrom<TermsWire> for Terms {
type Error = String;
fn try_from(w: TermsWire) -> Result<Self, String> {
let agreed = match (w.kind, w.agreed) {
(TermsKind::Custom, Some(d)) => Some(d),
(TermsKind::Custom, None) => Some(
w.text
.trim()
.to_lowercase()
.strip_prefix("due ")
.and_then(|r| NaiveDate::parse_from_str(r.trim(), "%Y-%m-%d").ok())
.ok_or_else(|| format!("custom terms {:?} give no date", w.text))?,
),
(_, None) => None,
(_, Some(_)) => return Err("only custom terms carry an agreed date".into()),
};
Ok(Terms {
kind: w.kind,
discount: w.discount,
text: w.text,
agreed,
})
}
}
impl Terms {
@@ -579,18 +627,20 @@ impl Terms {
kind,
discount,
text: compose_terms_text(kind, discount),
agreed: None,
})
}
/// Custom terms due on `due`: the parties agreed a date rather than a
/// count of days. Its text carries the date for people; the document
/// stores the due date itself.
/// count of days. The terms keep the date ([`Terms::agreed_date`]) and
/// print it for people; [`Terms::due_date`] returns it.
pub fn custom(due: NaiveDate) -> Result<Self, LedgerError> {
crate::calendar::check(due)?;
Ok(Terms {
kind: TermsKind::Custom,
discount: None,
text: format!("Due {due}"),
agreed: Some(due),
})
}
@@ -599,6 +649,11 @@ impl Terms {
self.kind
}
/// The date custom terms give; `None` for every other kind.
pub fn agreed_date(&self) -> Option<NaiveDate> {
self.agreed
}
/// The early-payment discount, when there is one.
pub fn discount(&self) -> Option<EarlyDiscount> {
self.discount
@@ -611,17 +666,24 @@ impl Terms {
/// The date payment is due for a document dated `date`.
///
/// For [`TermsKind::Custom`] the caller passes the agreed date itself
/// (there is no count to derive it from); for every other kind `date`
/// is the document's date. The result is never before `date` and
/// always in the calendar: a due date past 9999-12-31 is refused
/// `date` is the document's date. Custom terms are due on the date
/// they give, whatever `date` is (BS-arap-3 statement 1); an agreed
/// date before `date` is refused like any due date before its
/// document ([`validate_due_date`]). The result is never before `date`
/// and always in the calendar: a due date past 9999-12-31 is refused
/// ([`LedgerError::DateOverflow`]), never a panic.
pub fn due_date(&self, date: NaiveDate) -> Result<NaiveDate, LedgerError> {
crate::calendar::check(date)?;
let due = match self.kind {
TermsKind::DueOnReceipt | TermsKind::Custom => date,
TermsKind::Net(n) => add_days(date, n)?,
TermsKind::NetEom(n) => add_days(last_day_of_month(date)?, n)?,
let due = match (self.kind, self.agreed) {
(TermsKind::Custom, Some(agreed)) => agreed,
(TermsKind::Custom, None) => {
return Err(LedgerError::TermsUnreadable(
"custom terms give no date".into(),
));
}
(TermsKind::DueOnReceipt, _) => date,
(TermsKind::Net(n), _) => add_days(date, n)?,
(TermsKind::NetEom(n), _) => add_days(last_day_of_month(date)?, n)?,
};
validate_due_date(date, due)?;
Ok(due)
+244 -4
View File
@@ -305,6 +305,15 @@ pub enum LineError<T> {
}
/// The other side.
///
/// ```text
/// GOAL: flipping a side names the opposite side, and nothing else.
/// SOURCE: BS-ledger-5 (a reversal flips every side; the two together net
/// every account to zero).
/// INVARIANTS:
/// 1. There are two sides, so flipping twice is the identity.
/// 2. Flipping changes the side: no side is its own opposite.
/// ```
pub fn flip(side: Side) -> Side {
match side {
Side::Debit => Side::Credit,
@@ -313,6 +322,17 @@ pub fn flip(side: Side) -> Side {
}
/// A line's signed amount: positive for a debit, negative for a credit.
///
/// ```text
/// GOAL: a line's amount is signed by its side, so a balance can be read
/// on its account's normal side.
/// SOURCE: BS-ledger-3 (a line on the normal side raises its account's
/// balance by the amount; the other side lowers it).
/// INVARIANTS:
/// 1. A debit signs its amount positive, a credit negative.
/// 2. Flipping the side negates the signed amount.
/// 3. None when the credit cannot be negated.
/// ```
pub fn signed<T: Amount>(side: Side, amount: T) -> Option<T> {
match side {
Side::Debit => Some(amount),
@@ -321,6 +341,16 @@ pub fn signed<T: Amount>(side: Side, amount: T) -> Option<T> {
}
/// Total debits and total credits of some lines.
///
/// ```text
/// GOAL: the two columns of an entry are exact sums of their lines.
/// SOURCE: BS-entry-3 (sums of in-range amounts are exact and never
/// overflow).
/// INVARIANTS:
/// 1. Some((debits, credits)): each is the exact sum of its side's
/// amounts, and debits − credits is the net.
/// 2. None the moment a running sum is not representable.
/// ```
pub fn totals<T: Amount>(lines: impl IntoIterator<Item = (Side, T)>) -> Option<(T, T)> {
let mut debits = T::ZERO;
let mut credits = T::ZERO;
@@ -334,6 +364,16 @@ pub fn totals<T: Amount>(lines: impl IntoIterator<Item = (Side, T)>) -> Option<(
}
/// The net of some lines: debits minus credits.
///
/// ```text
/// GOAL: an entry has one net movement, the exact debits less the credits.
/// SOURCE: BS-entry-3 (exact sums), BS-entry-1 (an accepted entry nets to
/// zero).
/// INVARIANTS:
/// 1. Some(n) gives n = debits − credits exactly.
/// 2. An accepted entry's net is zero.
/// 3. None the moment a running sum is not representable.
/// ```
pub fn net<T: Amount>(lines: impl IntoIterator<Item = (Side, T)>) -> Option<T> {
let mut total = T::ZERO;
for (side, amount) in lines {
@@ -488,6 +528,18 @@ pub fn deductible_amount<T: Amount>(shares: &[(T, T)]) -> Option<T> {
/// Check an entry's lines: two or more, every amount positive and within
/// line range, debits equal to credits. Accounts and currencies are the
/// caller's to check; this is the arithmetic.
///
/// ```text
/// GOAL: accept exactly the entries double entry accepts, and refuse the
/// rest with the reason.
/// SOURCE: BS-entry-1 (two or more lines, debits equal credits),
/// BS-entry-2 (every amount positive).
/// INVARIANTS:
/// 1. Ok exactly when there are two or more lines, every amount is
/// positive and within line range, and debits equal credits.
/// 2. Unbalanced carries the exact debits and credits.
/// 3. An out-of-range amount is refused, never summed.
/// ```
pub fn check_lines<T: Amount>(lines: &[(Side, T)]) -> Result<(), LineError<T>> {
if lines.len() < 2 {
return Err(LineError::TooFewLines);
@@ -512,6 +564,13 @@ pub fn check_lines<T: Amount>(lines: &[(Side, T)]) -> Result<(), LineError<T>> {
/// Net movement per account (debits minus credits), in order of first
/// appearance.
///
/// SOURCE: BS-entry-1 (law 3: grouping lines by account loses and invents
/// nothing; the movements sum to the net).
///
/// INVARIANTS:
/// 1. Each account appears once, with the net of its own lines.
/// 2. The movements sum to the entry's net (zero when accepted).
pub fn movements<K: Copy + Eq, T: Amount>(
lines: impl IntoIterator<Item = (K, Side, T)>,
) -> Option<Vec<(K, T)>> {
@@ -528,6 +587,16 @@ pub fn movements<K: Copy + Eq, T: Amount>(
/// [`movements`] into a caller's buffer, without allocating: returns how
/// many accounts it wrote, or `None` on overflow or if `out` is too small.
///
/// ```text
/// GOAL: group an entry's lines by account without allocating, so a model
/// checker can prove the grouping.
/// SOURCE: BS-entry-1 (law 3: the movements sum to the net).
/// INVARIANTS:
/// 1. Returns the number of accounts written.
/// 2. Each account appears once, with the net of its own lines.
/// 3. None on overflow, or when `out` cannot hold every account.
/// ```
pub fn movements_into<K: Copy + Eq, T: Amount>(
lines: &[(K, Side, T)],
out: &mut [(K, T)],
@@ -548,18 +617,43 @@ pub fn movements_into<K: Copy + Eq, T: Amount>(
/// The lines of a reversing entry: every side flipped, accounts and
/// amounts unchanged.
///
/// SOURCE: BS-ledger-5 (a reversal flips every side, so it is accepted
/// exactly when the original is and the two net every account to zero).
///
/// INVARIANTS:
/// 1. Every side flipped; account and amount unchanged.
/// 2. Reversing twice gives the original back.
pub fn reversal<K: Copy, T: Amount>(lines: &[(K, Side, T)]) -> Vec<(K, Side, T)> {
lines.iter().map(|&line| reverse_line(line)).collect()
}
/// One line of a reversing entry: the side flipped, account and amount
/// unchanged.
///
/// SOURCE: BS-ledger-5 (a line's reversal; the two together net the
/// account to zero).
///
/// INVARIANTS:
/// 1. The side is flipped; account and amount are unchanged.
/// 2. Reversing twice gives the original line back.
pub fn reverse_line<K, T: Amount>((account, side, amount): (K, Side, T)) -> (K, Side, T) {
(account, flip(side), amount)
}
/// An account's balance read on its normal side: positive is a normal
/// balance, negative a contra balance.
///
/// ```text
/// GOAL: an account's movement becomes its balance on the side it normally
/// carries, which is what makes the accounting equation hold.
/// SOURCE: BS-statement-2 (assets equal liabilities plus equity plus
/// revenue less expenses, always).
/// INVARIANTS:
/// 1. Assets and expenses move by their movement; liabilities, equity
/// and revenue by its negation.
/// 2. None when the negation is not representable.
/// ```
pub fn normal_balance<T: Amount>(account_type: AccountType, movement: T) -> Option<T> {
match account_type.normal_side() {
Side::Debit => Some(movement),
@@ -569,6 +663,17 @@ pub fn normal_balance<T: Amount>(account_type: AccountType, movement: T) -> Opti
/// A movement in trial-balance columns: `(debit, credit)`, one of them
/// zero, both non-negative.
///
/// ```text
/// GOAL: place each account's movement in exactly one trial-balance
/// column, so the columns balance exactly when the books do.
/// SOURCE: BS-statement-1 (the trial balance balances, and only if the
/// books net to zero).
/// INVARIANTS:
/// 1. One column is zero and both are non-negative.
/// 2. debit − credit is the movement, never a negative zero.
/// 3. The columns differ by the net of all movements.
/// ```
pub fn columns<T: Amount>(movement: T) -> Option<(T, T)> {
if movement > T::ZERO {
Some((movement, T::ZERO))
@@ -582,6 +687,17 @@ pub fn columns<T: Amount>(movement: T) -> Option<(T, T)> {
/// The line that zeroes an account with this movement: the opposite side,
/// for the same amount. `None` for a zero movement (nothing to close).
///
/// ```text
/// GOAL: closing an account takes the opposite side for its balance, so the
/// account ends at zero.
/// SOURCE: BS-period-1 (a closing entry zeroes every revenue and expense
/// account it closes).
/// INVARIANTS:
/// 1. The line is the opposite side for the same amount, always positive.
/// 2. Movement plus the line's signed amount is zero.
/// 3. None exactly for a zero movement.
/// ```
pub fn closing_line<T: Amount>(movement: T) -> Option<(Side, T)> {
if movement > T::ZERO {
Some((Side::Credit, movement))
@@ -595,6 +711,15 @@ pub fn closing_line<T: Amount>(movement: T) -> Option<(Side, T)> {
/// The line that credits `credit` to an account (a negative credit is a
/// debit). `None` for zero. This is [`closing_line`]: crediting `c` and
/// zeroing a movement of `c` are the same line.
///
/// ```text
/// GOAL: credit exactly what the close says, never more or less.
/// SOURCE: BS-period-1 (a close credits equity with exactly the period's
/// net income).
/// INVARIANTS:
/// 1. The line's signed amount is −credit (a negative credit debits).
/// 2. None exactly for zero.
/// ```
pub fn credit_line<T: Amount>(credit: T) -> Option<(Side, T)> {
closing_line(credit)
}
@@ -694,6 +819,17 @@ pub fn payment_bucket(role: PayRole, tag: Tag) -> Option<Bucket> {
/// What an entry paid, per bucket: credits minus debits of the lines in
/// each (a line in no bucket is not a payment line). `None` on overflow.
///
/// ```text
/// GOAL: split a payment into its buckets, never losing or counting a line
/// twice.
/// SOURCE: BS-1099-1 (a payment to a vendor is reported: its buckets are
/// the 1099, the card/network payment, and the unknown).
/// INVARIANTS:
/// 1. Each bucket is the exact credits minus debits of its own lines.
/// 2. The buckets together are the whole payment.
/// 3. None on overflow.
/// ```
pub fn split_payment<T: Amount>(lines: &[(Option<Bucket>, Side, T)]) -> Option<[T; 3]> {
let mut out = [T::ZERO; 3];
for &(bucket, side, amount) in lines {
@@ -758,6 +894,16 @@ pub fn net_buckets<T: Amount>(b: [T; 3]) -> Option<[T; 3]> {
/// Make rounded parts sum to the whole: the last part becomes `whole`
/// minus the others, absorbing every unit of rounding. Returns `None` on
/// overflow, leaving `parts` unchanged.
///
/// ```text
/// GOAL: an allocation's parts sum to the whole exactly, to the last unit.
/// SOURCE: BS-partner-1 (an allocation's parts sum to the whole exactly;
/// the largest remainder decides which part takes what).
/// INVARIANTS:
/// 1. On success the parts sum to `whole`.
/// 2. Only the last part changes.
/// 3. None on overflow, leaving the parts unchanged.
/// ```
pub fn plug_last<T: Amount>(whole: T, parts: &mut [T]) -> Option<()> {
let Some((last, rest)) = parts.split_last_mut() else {
return Some(());
@@ -940,6 +1086,17 @@ pub struct EntryFlows<T> {
/// a section moving against the cash takes any, and never more than its
/// own movement. Cash in (`remaining > 0`) settles credits (`movement <
/// 0`); cash out settles debits.
///
/// ```text
/// GOAL: a section takes only the cash that moved against it, never more
/// than it moved and never in the other direction.
/// SOURCE: BS-statement-3 (the cash-flow sections sum to the change in
/// cash; only the cash portion of a section counts).
/// INVARIANTS:
/// 1. Odd: take(−r, −m) = −take(r, m).
/// 2. Its sign is the cash's and the movement's opposite, or zero.
/// 3. Never more than the cash left or the movement.
/// ```
pub fn take<T: Amount>(remaining: T, movement: T) -> Option<T> {
let against = movement.checked_neg()?;
Some(if remaining > T::ZERO && movement < T::ZERO {
@@ -993,6 +1150,18 @@ pub fn apply_cash<T: Amount>(cash: T, movements: &[T], applied: &mut [T]) -> Opt
/// the lines don't net to zero (never for a posted entry) or on overflow.
/// It is [`entry_movements`] then [`flows_of`], so each is proved on its
/// own (docs/verification.md, law 10).
///
/// ```text
/// GOAL: an entry's cash flows foot: the sections' cash sums to the entry's
/// cash, and what no cash settled sums to zero.
/// SOURCE: BS-statement-3 (the cash-flow sections sum to the change in
/// cash, and net income reconciles to operating cash).
/// INVARIANTS:
/// 1. flows[0] + flows[1] + flows[2] = cash.
/// 2. noncash[0] + noncash[1] + noncash[2] = 0.
/// 3. flows[k] + noncash[k] is section k's movement.
/// 4. None when the lines do not net to zero, or on overflow.
/// ```
pub fn entry_flows<T: Amount>(lines: &[(Flow, Side, T)]) -> Option<EntryFlows<T>> {
let (cash, moved) = entry_movements(lines)?;
flows_of(cash, moved)
@@ -1001,6 +1170,14 @@ pub fn entry_flows<T: Amount>(lines: &[(Flow, Side, T)]) -> Option<EntryFlows<T>
/// An entry's net movement on its cash lines and on each section's,
/// `(cash, [operating, investing, financing])`, debit-positive. `None`
/// on overflow.
///
/// SOURCE: BS-statement-3 (law 10: a reversal's flows are its original's,
/// negated, part by part).
///
/// INVARIANTS:
/// 1. `cash` is the net of the cash lines, each section's the net of its
/// own, debit-positive.
/// 2. A reversal negates each figure.
pub fn entry_movements<T: Amount>(lines: &[(Flow, Side, T)]) -> Option<(T, [T; 3])> {
let mut cash = T::ZERO;
let mut moved = [T::ZERO; 3];
@@ -1020,6 +1197,16 @@ pub fn entry_movements<T: Amount>(lines: &[(Flow, Side, T)]) -> Option<(T, [T; 3
/// The cash flows of an entry whose cash lines moved `cash` and whose
/// sections moved `moved` ([`entry_flows`]). `None` when they don't net
/// to zero, or on overflow.
///
/// ```text
/// GOAL: split a balanced entry's cash among its sections, and say what no
/// cash settled, so a reversal mirrors it.
/// SOURCE: BS-statement-3 (the sections' cash sums to the change in cash;
/// a reversal's flows are the original's negated).
/// INVARIANTS:
/// 1. Odd: negated cash and movements give the negated flows and noncash.
/// 2. None unless the movements net to zero, or on overflow.
/// ```
pub fn flows_of<T: Amount>(cash: T, moved: [T; 3]) -> Option<EntryFlows<T>> {
// Balanced lines only: every part below rests on it.
let mut total = cash;
@@ -1070,6 +1257,12 @@ pub enum OnBehalf {
impl OnBehalf {
/// The other way: what an entry's reversal does.
///
/// SOURCE: BS-statement-3 rule 11 (what a member or lender paid or
/// received for the company is mirrored by its reversal).
///
/// INVARIANTS:
/// 1. Paid and Received swap; mirroring twice is the identity.
pub fn mirror(self) -> Self {
match self {
OnBehalf::Paid => OnBehalf::Received,
@@ -1138,6 +1331,17 @@ pub fn constructive<T: Amount>(
/// rule 11). Cash in settles credits and cash out settles debits; what's
/// left of the smaller side was exchanged:
/// `max(0, min(debits - outflow, credits - inflow))`.
///
/// ```text
/// GOAL: the part of an entry exchanged with no cash is the smaller side
/// left once the cash is applied, never negative.
/// SOURCE: BS-statement-3 (the sections sum to the change in cash; a
/// non-cash exchange is investing and financing, not a flow).
/// INVARIANTS:
/// 1. The result is max(0, min(debits − outflow, credits − inflow)).
/// 2. It is never more than either side.
/// 3. None on overflow.
/// ```
pub fn exchanged<T: Amount>(debits: T, credits: T, inflow: T, outflow: T) -> Option<T> {
let d = debits.checked_sub(outflow)?;
let c = credits.checked_sub(inflow)?;
@@ -1162,6 +1366,13 @@ pub enum Direction {
impl Direction {
/// The other way: paid and received swap; neither stays neither.
///
/// SOURCE: BS-partner-3 (a party's part carries the whole's sign; a
/// reversal swaps paid and received).
///
/// INVARIANTS:
/// 1. Paid and Received swap; Neither stays Neither.
/// 2. Flipping twice is the identity.
pub fn flip(self) -> Self {
match self {
Direction::Paid => Direction::Received,
@@ -1171,7 +1382,7 @@ impl Direction {
}
/// The direction of a signed amount: paid above zero, received below,
/// neither at zero.
/// neither at zero. SOURCE: BS-partner-3 (the party direction law).
pub fn of<T: Amount>(amount: T) -> Self {
if amount > T::ZERO {
Direction::Paid
@@ -1346,6 +1557,16 @@ pub fn party_target<T: Amount>(
/// correction is the opposite entry): every amount negated (never to a
/// negative zero), paid and received swapped. An involution. `None` past
/// the type's range.
///
/// SOURCE: BS-partner-3 (a party's part carries the whole's sign),
/// BS-ledger-5 (a reversal is the exact opposite, and reversing twice
/// gives the original back).
///
/// INVARIANTS:
/// 1. Every amount is negated (never a negative zero), the direction
/// flipped.
/// 2. Reversing twice gives the original back.
/// 3. None past the type's range.
pub fn reverse_target<T: Amount>(t: PartyTarget<T>) -> Option<PartyTarget<T>> {
let neg = |a: T| {
if a == T::ZERO {
@@ -1483,6 +1704,16 @@ impl MonthPart {
/// A part's weight in `MONTH_L`ths of a month: `days × (MONTH_L /
/// month_days)`, exactly. `None` for a part no month has.
///
/// ```text
/// GOAL: weigh a month part exactly, so proration by days needs no
/// fractions.
/// SOURCE: BS-asset-1, BS-prepaid-1 (proration by days; the weight is the
/// lemma laws 26-28 are computed from).
/// INVARIANTS:
/// 1. A valid part weighs days x MONTH_L / month_days, exactly.
/// 2. None for a part no calendar month has.
/// ```
pub fn part_weight<T: Units>(p: MonthPart) -> Option<T> {
if !p.is_valid() {
return None;
@@ -1669,10 +1900,10 @@ pub fn prorate_by_days<T: Units>(
/// ```text
/// GOAL: a skipped month is caught up in the month the run is made, and a
/// run never overtakes the schedule at a month end already posted.
/// SOURCE: plan/served.md P3 "Settled in design" (2026-10-20): a month of
/// SOURCE: BS-asset-1 (a catch-up run never overtakes the schedule);
/// plan/served.md P3 "Settled in design" (2026-10-20): a month of
/// depreciation skipped is caught up in the month the run is made
/// (an immaterial miss; a material one is restated, ASC 250);
/// BS-asset-1.
/// (an immaterial miss; a material one is restated, ASC 250).
/// INVARIANTS:
/// 1. The result is >= 0.
/// 2. Whenever every posted[i] <= scheduled[i], posted[i] + result <=
@@ -1703,6 +1934,15 @@ pub fn catch_up<T: Amount>(scheduled: &[T], posted: &[T]) -> Option<T> {
/// end, O(n), so a viewer can say of every month of a long life whether
/// anything is due for it. `None` when the slices differ in length, or on
/// overflow.
///
/// ```text
/// GOAL: say what every month end's run would catch up, in one pass.
/// SOURCE: BS-asset-1 (law 29: a catch-up run posts everything due through
/// its month, never past the schedule).
/// INVARIANTS:
/// 1. out[i] is the catch-up of the suffix from i, at least zero.
/// 2. None when the slices differ in length, or on overflow.
/// ```
pub fn catch_ups<T: Amount>(scheduled: &[T], posted: &[T], out: &mut [T]) -> Option<()> {
if scheduled.len() != posted.len() || out.len() != scheduled.len() {
return None;
+10
View File
@@ -106,6 +106,16 @@ pub fn fx_booked<T: Amount>(foreign: T, rate: T, step: T, mode: Rounding) -> Opt
/// computation's: `round_places` keeps an amount already at or under
/// the minor places unchanged, and otherwise carries exactly the minor
/// places (a booked 1.50 prints "1.50", never "1.5000").
///
/// SOURCE: BS-ledger-1 (law 41: a foreign amount booked at the
/// transaction-date rate is the exact product rounded once to the base
/// currency's smallest unit).
///
/// INVARIANTS:
/// 1. It is `fx_booked` at the currency's minor unit, and keeps that
/// function's scale.
/// 2. A currency with no minor unit books the exact product.
/// 3. None exactly when `fx_booked` refuses, or on overflow.
pub fn fx_booked_minor(
foreign: Decimal,
rate: Decimal,
+20
View File
@@ -69,6 +69,19 @@ pub fn round_step<T: Amount>(amount: T, step: T, mode: Rounding) -> Option<T> {
/// result carries exactly `places` places. This is the behaviour-preserving
/// wrapper the call sites use while U2 proves `round_step` underneath
/// them; it is not a second rounding rule.
///
/// ```text
/// GOAL: round to a number of decimal places through the one kernel rule,
/// so no call site keeps a second definition.
/// SOURCE: BS-ledger-1 (law 40: rounding is a whole multiple of the step,
/// each tie by its own rule).
/// INVARIANTS:
/// 1. The value is `round_step` at 10^(−places); an amount no finer
/// than `places` is unchanged.
/// 2. A non-zero result carries exactly `places` places; zero is never a
/// negative zero.
/// 3. None on overflow.
/// ```
pub fn round_places(amount: Decimal, places: u32, mode: Rounding) -> Option<Decimal> {
if amount.is_zero() {
// Keep round_dp's scale, but never its negative zero.
@@ -97,6 +110,13 @@ pub fn round_places(amount: Decimal, places: u32, mode: Rounding) -> Option<Deci
/// USD, whole yen for JPY, thousandths for KWD. A currency ISO 4217 gives
/// no minor unit (gold, SDRs) is returned exactly, as the FX booking rule
/// has always done (BS-ledger-1).
///
/// SOURCE: BS-ledger-1 (law 40; a currency's smallest unit is the step).
///
/// INVARIANTS:
/// 1. It is `round_places` at the currency's minor unit, or the amount
/// itself when the currency has none.
/// 2. None on overflow.
pub fn round_minor(amount: Decimal, currency: Currency, mode: Rounding) -> Option<Decimal> {
match currency.minor_units() {
Some(places) => round_places(amount, places, mode),
+42 -2
View File
@@ -1288,7 +1288,7 @@ fn constructive_mirrors() {
let (mut fa, mut ta) = ([0i64; M], [0i64; M]);
let (mut fb, mut tb) = ([0i64; M], [0i64; M]);
let a = kernel::constructive(way, &s, &u, &mut fa, &mut ta);
let b = kernel::constructive(way.mirror(), &ns, &nu, &mut fb, &mut tb);
let b = kernel::constructive(kernel::OnBehalf::mirror(way), &ns, &nu, &mut fb, &mut tb);
assert_eq!(a.is_some(), b.is_some());
if a.is_some() {
for k in 0..M {
@@ -1374,6 +1374,25 @@ fn party_target_direction_is_its_sign() {
);
}
/// BS-partner-3: the direction of a signed amount is its sign: paid above
/// zero, received below zero, and neither exactly at zero. This is the
/// classification `party_target` builds its four items on (law 23).
#[kani::proof]
fn direction_of_is_the_sign() {
let amount: i64 = kani::any();
let direction = kernel::Direction::of(amount);
if amount > 0 {
assert_eq!(direction, kernel::Direction::Paid);
} else if amount < 0 {
assert_eq!(direction, kernel::Direction::Received);
} else {
assert_eq!(direction, kernel::Direction::Neither);
}
kani::cover!(amount > 0, "a paid amount");
kani::cover!(amount < 0, "a received amount");
kani::cover!(amount == 0, "nothing moved");
}
/// BS-partner-3 item 3 and BS-ledger-5: the target is odd. Negating the lines negates the
/// capital movement, the money net and the own-account movement, and the
/// property comes from the other side, so it keeps its size: the result
@@ -1426,7 +1445,7 @@ fn reverse_target_is_an_involution() {
};
match kernel::reverse_target(t) {
Some(r) => {
assert_eq!(r.direction, t.direction.flip());
assert_eq!(r.direction, kernel::Direction::flip(t.direction));
assert_eq!(r.amount, -t.amount);
assert_eq!(kernel::reverse_target(r), Some(t));
}
@@ -1475,6 +1494,27 @@ fn any_proration() -> (i64, u32, [MonthPart; PR], usize, i64) {
(total, months, parts, n, unit)
}
/// BS-asset-1 and BS-prepaid-1: a part's weight is its days times the
/// month's share of `MONTH_L` (`days × MONTH_L / month_days`), exactly, and
/// a part no calendar month has is refused. The weight is what the
/// proration charges of laws 26-28 are computed from.
#[kani::proof]
fn part_weight_is_days_of_the_month() {
let days: u32 = kani::any();
let month_days: u32 = kani::any();
kani::assume(days <= 40 && month_days <= 40);
let part = MonthPart { days, month_days };
let got: Option<i64> = kernel::part_weight(part);
if part.is_valid() {
assert_eq!(got, Some(i64::from(days) * i64::from(MONTH_L / month_days)));
} else {
assert_eq!(got, None);
}
kani::cover!(part.is_valid() && days < month_days, "a partial month");
kani::cover!(part.is_valid() && days == month_days, "a whole month");
kani::cover!(!part.is_valid(), "a part no month has");
}
/// The weight of parts, in MONTH_L-ths of a month.
fn weight(parts: &[MonthPart]) -> i64 {
parts
@@ -38,6 +38,8 @@ pub(crate) fn check(b: &Books<'_>, x: &Expect) -> Option<&'static str> {
);
only(x.basis.is_some(), "basis", &["party_totals"]);
only(x.payee.is_some(), "payee", &["vendor_1099"]);
only(x.document.is_some(), "document", &["document_dates"]);
only(x.of.is_some(), "of", &["aging"]);
only(
x.code.is_some(),
"code",
@@ -101,6 +103,8 @@ pub(crate) fn check(b: &Books<'_>, x: &Expect) -> Option<&'static str> {
"party_totals" => check_party_totals(b, x),
"party_tin_last4" => check_party_tin_last4(b, x),
"project" => check_project(b, x),
"aging" => check_aging(b, x),
"document_dates" => check_document_dates(b, x),
q => {
let &(_, by) = FORMAT_QUERIES
.iter()
@@ -143,6 +143,7 @@ pub(crate) fn refusal(e: &LedgerError) -> String {
LedgerError::InvalidDepreciationPeriod(_) => "invalid_depreciation_period",
LedgerError::InvalidSchedule(_) => "invalid_schedule",
LedgerError::UntaggedControlLine { .. } => "untagged_control_line",
LedgerError::PaymentBeforeDocument { .. } => "payment_before_document",
LedgerError::UnbalancedEntry { .. } => "unbalanced",
LedgerError::TooFewLines => "too_few_lines",
LedgerError::NegativeAmountLine => "negative_amount",
@@ -41,6 +41,25 @@ impl Engine for Books<'_> {
}
}
/// Why wanderbooks does not run `ex`: it is an example for an option of a
/// CHOICE rule (`under`) that wanderbooks did not pick (`PICKS`). The
/// runner skips such an example for the same reason; the loader tests do
/// it with this.
pub(crate) fn unpicked_option(ex: &Example) -> Option<String> {
ex.under.iter().find_map(|u| {
let rule = RuleId::parse(&u.rule).ok()?;
let &(_, _, pick) = PICKS
.iter()
.find(|&&(area, n, _)| RuleId::new(area, n) == rule)?;
(pick != u.option).then(|| {
format!(
"for {} under {}; wanderbooks picks {pick}",
u.rule, u.option
)
})
})
}
/// The option wanderbooks picks for each CHOICE record split out of an
/// embedded choice (P14 unit S-C7); each is recorded in
/// `docs/spec/claims/<area>.md` as `**Pick (BS-<area>-<n>):**`.
+88 -5
View File
@@ -13,6 +13,7 @@ impl Books<'_> {
("bill", e.bill.is_some()),
("invoice", e.invoice.is_some()),
("write_off", e.write_off.is_some()),
("payment", e.payment.is_some()),
("run_depreciation", e.run_depreciation.is_some()),
("dispose_asset", e.dispose_asset.is_some()),
("run_schedules", e.run_schedules.is_some()),
@@ -21,7 +22,7 @@ impl Books<'_> {
match kinds.iter().filter(|(_, given)| *given).collect::<Vec<_>>()[..] {
[(kind, _)] => kind,
_ => panic!(
"{} event {n}: an event is one of lines, reverses, close, bill, invoice, write_off, run_depreciation, dispose_asset, run_schedules or register_schedule",
"{} event {n}: an event is one of lines, reverses, close, bill, invoice, write_off, payment, run_depreciation, dispose_asset, run_schedules or register_schedule",
self.ex.id
),
}
@@ -35,7 +36,7 @@ impl Books<'_> {
// disposal is dated; the other commands date their own entries,
// and every command describes its own.
let own = matches!(kind, "lines" | "reverses" | "close" | "bill" | "invoice");
let dated = own || matches!(kind, "dispose_asset" | "write_off");
let dated = own || matches!(kind, "dispose_asset" | "write_off" | "payment");
assert_eq!(
e.date.is_some(),
dated,
@@ -84,6 +85,10 @@ impl Books<'_> {
e.write_off.is_none() || kind == "write_off",
"{ex} event {n}: a write_off is its own event"
);
assert!(
e.payment.is_none() || kind == "payment",
"{ex} event {n}: a payment is its own event"
);
}
/// Take event `n` as the books take it, keep what it posted and tag it
@@ -192,11 +197,39 @@ impl Books<'_> {
"{what}: entry {id}, which it made, is posted"
);
}
if (own || kind == "write_off") && e.refused.is_none() {
if (own || matches!(kind, "write_off" | "payment")) && e.refused.is_none() {
assert_eq!(posted.len(), 1, "{what}: {kind} posts one entry");
}
}
/// The terms a document's example gives, and the due date the books take
/// them to (BS-arap-3): the engine's own `Terms::due_date` for every
/// kind, a date the parties agreed ("Due 2026-11-15") included. The
/// example's spelling is the canonical one, so the engine must print it
/// back as written. Nothing of the date is read out of the text here:
/// the example can only pass if the engine computes it. Without terms a
/// document is due on its own date.
pub(crate) fn terms_due(
&self,
terms: Option<&str>,
date: NaiveDate,
what: &str,
) -> (NaiveDate, Option<Terms>) {
let Some(text) = terms else {
return (date, None);
};
let parsed = Terms::parse(text).unwrap_or_else(|e| panic!("{what}: terms {text:?}: {e}"));
assert_eq!(
parsed.describe(),
text,
"{what}: the engine prints terms {text:?} back as written"
);
let due = parsed
.due_date(date)
.unwrap_or_else(|e| panic!("{what}: terms {text:?} on {date}: {e}"));
(due, Some(parsed))
}
/// An invoice's or bill's lines: `amount` (one line, described as the
/// event) or `lines`, exactly one; each project a `setup.projects`
/// name.
@@ -368,8 +401,18 @@ impl Books<'_> {
v
}
};
let (due, terms) = self.terms_due(b.terms.as_deref(), day(), what);
self.store
.create_bill(vendor, day(), day(), lines)
.create_bill_with(
vendor,
day(),
due,
lines,
BillFields {
terms,
..BillFields::default()
},
)
.map(|_| ())
}
"invoice" => {
@@ -383,8 +426,18 @@ impl Books<'_> {
c
}
};
let (due, terms) = self.terms_due(i.terms.as_deref(), day(), what);
self.store
.create_invoice(customer, day(), day(), lines)
.create_invoice_with(
customer,
day(),
due,
lines,
InvoiceFields {
terms,
..InvoiceFields::default()
},
)
.map(|_| ())
}
"write_off" => {
@@ -432,6 +485,36 @@ impl Books<'_> {
)
.map(drop)
}
"payment" => {
let p = e.payment.as_ref().expect("checked: a payment");
let entry = self.entry_of(p.document, what);
let amount = money(&p.amount);
let cash = self.id(&p.account);
let invoice = self
.store
.ledger()
.invoices()
.into_iter()
.find(|i| i.entry_id == entry)
.map(|i| i.id);
let bill = self
.store
.ledger()
.bills()
.into_iter()
.find(|b| b.entry_id == entry)
.map(|b| b.id);
match (invoice, bill) {
(Some(invoice), _) => self
.store
.receive_payment(invoice, day(), amount, cash)
.map(drop),
(None, Some(bill)) => self.store.pay_bill(bill, day(), amount, cash).map(drop),
(None, None) => {
panic!("{what}: event {} posted no invoice or bill", p.document)
}
}
}
"run_depreciation" => {
let r = e.run_depreciation.as_ref().expect("checked: a run");
let asset = self.asset(&r.asset, what);
@@ -1,3 +1,4 @@
use crate::engine::unpicked_option;
use crate::*;
/// The `Engine` adapter over `Store` runs every example through the
@@ -17,6 +18,40 @@ pub(crate) fn the_runner_reports_every_claimed_rule_green() {
"the runner is not green:\n{}",
report.failures().join("\n")
);
// An example for an option wanderbooks did not pick is not run; every
// other one is, and passes.
let skipped = report.skipped();
let unpicked: Vec<&str> = examples
.iter()
.filter(|ex| unpicked_option(ex).is_some())
.map(|ex| ex.id.as_str())
.collect();
assert_eq!(
skipped.len(),
unpicked.len(),
"the runner skips exactly the examples for unpicked options: {skipped:?}"
);
for id in &unpicked {
assert!(
skipped.iter().any(|s| s.starts_with(&format!("{id}:"))),
"{id} is skipped"
);
}
let ran = report.examples.len() - skipped.len();
let passed = report
.examples
.iter()
.filter(|e| e.skipped.is_none() && e.failure.is_none())
.count();
eprintln!(
"bookspec runner: {} examples, {ran} run, {passed} passed, {} skipped (an option wanderbooks did not pick)",
report.examples.len(),
skipped.len()
);
for s in &skipped {
eprintln!(" skipped {s}");
}
assert_eq!(ran, passed, "every example run passed");
for rule in bookspec_checker::covered_rules() {
assert_eq!(
report.rules.get(&rule.id),
@@ -39,6 +74,7 @@ pub(crate) fn every_bookspec_example_holds() {
let files = bookspec_checker::examples();
let mut ids = BTreeSet::new();
let mut checked: BTreeMap<String, usize> = BTreeMap::new();
let mut skipped = Vec::new();
for (name, text) in &files {
let ex = Example::from_toml(text).unwrap_or_else(|e| panic!("{name}: {e}"));
let stem = name.strip_suffix(".toml").unwrap();
@@ -57,6 +93,12 @@ pub(crate) fn every_bookspec_example_holds() {
);
assert!(!ex.sources.is_empty(), "{}: every rule is sourced", ex.id);
assert!(!ex.expect.is_empty(), "{}: something to expect", ex.id);
// The examples for an option wanderbooks did not pick are for
// another engine; they are read (above) and not run.
if let Some(why) = unpicked_option(&ex) {
skipped.push(format!("{} {why}", ex.id));
continue;
}
for (q, by) in run(&ex) {
if let Some(by) = by {
eprintln!("{}: {q} is checked by {by}", ex.id);
@@ -102,8 +144,24 @@ pub(crate) fn every_bookspec_example_holds() {
("k1_tax_basis", 4),
("k1_reconciliation", 2),
("project", 6),
("aging", 4),
("document_dates", 8),
] {
let n = checked.get(q).copied().unwrap_or(0);
assert!(n >= at_least, "{q} ran {n} times, fewer than {at_least}");
}
eprintln!(
"bookspec examples: {} files, {} run, {} skipped (an option wanderbooks did not pick): {skipped:?}",
files.len(),
files.len() - skipped.len(),
skipped.len()
);
// The examples for an option wanderbooks did not pick: the other option
// of BS-arap-7, -8 and -9, BS-prepaid-2's equal-months and BS-ledger-20's
// refuse (each option's example, so no allow-list grows).
assert_eq!(
skipped.len(),
5,
"the five unpicked-option examples: {skipped:?}"
);
}
+9 -7
View File
@@ -50,13 +50,13 @@ pub(crate) use ledger_core::parties::{Basis, MoneyAccounts};
pub(crate) use ledger_core::settings::{Company, Source};
pub(crate) use ledger_core::tax_capital::TaxCapitalRow;
pub(crate) use ledger_core::{
AccountType, AssetId, CashFlowParams, CashFlowSection, CashFlowStatement, CloseTo, Currency,
Dated1099, Decision1099, DocumentLine, EntryId, EntryStatus, ExemptReason, Form1099,
InstrumentId, InstrumentKind, Ledger, LedgerError, MemberCapital, MemberClose, Money, NewAsset,
NewSchedule, PartyId, PartyMember, PartyShare, PaymentAccounts, ReconcilingKind, Role,
ScheduleConvention, ScheduleId, ScheduleKind, Share, Side, TinFacts, TinType, VendorId,
W9Facts, cash_flow, members_equity, profit_and_loss_for_period, trial_balance_as_of,
vendor_1099_report,
AccountType, AssetId, BillFields, CashFlowParams, CashFlowSection, CashFlowStatement, CloseTo,
Currency, Dated1099, Decision1099, DocumentLine, EntryId, EntryStatus, ExemptReason, Form1099,
InstrumentId, InstrumentKind, InvoiceFields, Ledger, LedgerError, MemberCapital, MemberClose,
Money, NewAsset, NewSchedule, PartyId, PartyMember, PartyShare, PaymentAccounts,
ReconcilingKind, Role, ScheduleConvention, ScheduleId, ScheduleKind, Share, Side, Terms,
TinFacts, TinType, VendorId, W9Facts, cash_flow, members_equity, profit_and_loss_for_period,
trial_balance_as_of, vendor_1099_report,
};
pub(crate) use ledger_store::{DepreciationRun, DisposalPreview, Store, StoreError};
pub(crate) use rust_decimal::Decimal;
@@ -75,6 +75,7 @@ pub(crate) use common::*;
pub(crate) use queries::assets::*;
pub(crate) use queries::commands::*;
pub(crate) use queries::dates::*;
pub(crate) use queries::documents::*;
pub(crate) use queries::formats::*;
pub(crate) use queries::parties::*;
pub(crate) use queries::statements::*;
@@ -95,3 +96,4 @@ mod rules_md;
mod run;
mod source_refs;
mod sources;
mod traceability;
@@ -0,0 +1,98 @@
use crate::*;
/// The buckets of an aging, as the examples key them (BS-arap-1), beside
/// the engine's `AgingRow` fields they read.
const BUCKETS: [&str; 5] = ["current", "1-30", "31-60", "61-90", "90+"];
impl Books<'_> {
/// The engine's `ar_aging` or `ap_aging` as of the day (BS-arap-1): the
/// buckets in total, `total`, and each party's buckets, read straight
/// from the engine's rows, never recomputed here.
pub(crate) fn answer_aging(&self, q: &Query) -> Result<Value, Refusal> {
let as_of = self.q_day(q)?;
let rows = match q.of.as_deref() {
Some("receivables") => self.l().ar_aging(as_of),
Some("payables") => self.l().ap_aging(as_of),
_ => return Err(self.missing("receivables or payables")),
}
.map_err(|e| engine_refusal(RuleId::new(Area::Arap, 1), e))?;
let mut m = JsonMap::new();
let mut totals = [Decimal::ZERO; 5];
for row in &rows {
let buckets = [
row.current,
row.days_30,
row.days_60,
row.days_90,
row.days_90_plus,
];
for ((name, owed), total) in BUCKETS.iter().zip(buckets).zip(totals.iter_mut()) {
m.insert(format!("{}.{name}", row.name), Value::String(figure(owed)));
*total += owed;
}
}
for (name, total) in BUCKETS.iter().zip(totals) {
m.insert(name.to_string(), Value::String(figure(total)));
}
m.insert(
"total".to_string(),
Value::String(figure(totals.iter().copied().sum())),
);
Ok(Value::Object(m))
}
/// The due date and discount date the document event's terms give
/// (BS-arap-3), as the engine stored the document and its terms.
pub(crate) fn answer_document_dates(&self, q: &Query) -> Result<Value, Refusal> {
let n = q.document.ok_or_else(|| self.missing("document"))?;
let entry = self.entry_or_refuse(n)?;
let l = self.l();
let (date, due, terms) = match (
l.invoices().into_iter().find(|i| i.entry_id == entry),
l.bills().into_iter().find(|b| b.entry_id == entry),
) {
(Some(i), _) => (i.date, i.due_date, i.terms.clone()),
(None, Some(b)) => (b.date, b.due_date, b.terms.clone()),
(None, None) => return Err(self.missing("invoice or bill")),
};
let discount_by = terms
.and_then(|t| t.discount_by(date))
.map_or_else(|| "none".to_string(), |d| d.to_string());
Ok(json_figures([
("due".to_string(), due.to_string()),
("discount_by".to_string(), discount_by),
]))
}
}
/// Check an `aging` expectation: every figure the engine gives, and no
/// other (the example lists everything it covers).
pub(crate) fn check_aging(b: &Books<'_>, x: &Expect) {
check_figures(b, x, b.answer_aging(&x.query()));
}
/// Check a `document_dates` expectation: `due` and `discount_by`, both
/// given.
pub(crate) fn check_document_dates(b: &Books<'_>, x: &Expect) {
check_figures(b, x, b.answer_document_dates(&x.query()));
}
fn check_figures(b: &Books<'_>, x: &Expect, answer: Result<Value, Refusal>) {
let ex = b.ex;
let Value::Object(got) =
answer.unwrap_or_else(|r| panic!("{}: {}: {}", ex.id, x.query, r.reason))
else {
panic!("{}: {} answers a table", ex.id, x.query)
};
let keys: BTreeSet<String> = got.keys().cloned().collect();
exactly(ex, x, &keys);
for (key, want) in x.figures(&ex.id) {
assert_eq!(
got[key].as_str(),
Some(want.as_str()),
"{}: {} {key}",
ex.id,
x.query
);
}
}
@@ -3,6 +3,7 @@ use crate::*;
pub(crate) mod assets;
pub(crate) mod commands;
pub(crate) mod dates;
pub(crate) mod documents;
pub(crate) mod formats;
pub(crate) mod parties;
pub(crate) mod statements;
@@ -84,6 +85,8 @@ impl Books<'_> {
"party_totals" => self.answer_party_totals(q),
"party_tin_last4" => self.answer_party_tin_last4(q),
"project" => self.answer_project(q),
"aging" => self.answer_aging(q),
"document_dates" => self.answer_document_dates(q),
"run" => self.answer_run(q),
"disposal" => self.answer_disposal(q),
"depreciation_schedule" => self.answer_depreciation_schedule(q),
File diff suppressed because it is too large. Load diff
@@ -1,4 +1,42 @@
//! U8 bridge properties: control and aging (kernel sweep).
//!
//! Empty in U0: the unit adds its `Decimal`-vs-integer properties here,
//! beside `main.rs` and the other units.
//! `kernel::running_bounds` and `kernel::bounds_kept` at `i64` cents (what
//! Kani proves, law 34) against the same on `Decimal` (what the engine
//! runs), on random documents.
use super::{arb_cents, dec};
use ledger_core::kernel;
use proptest::prelude::*;
proptest! {
#![proptest_config(ProptestConfig::with_cases(1000))]
/// The same running balances are within bounds, or leave them at the
/// same step, at both types.
#[test]
fn running_bounds_agree(
total in arb_cents(),
deltas in prop::collection::vec(arb_cents(), 0..7),
) {
let wide: Vec<_> = deltas.iter().map(|&c| dec(c)).collect();
prop_assert_eq!(
kernel::running_bounds(total, &deltas),
kernel::running_bounds(dec(total), &wide)
);
}
/// The same step keeps (or breaks) a document's bounds at both types.
#[test]
fn bounds_kept_agree(
total in arb_cents(),
before in prop::collection::vec(arb_cents(), 0..7),
after in prop::collection::vec(arb_cents(), 0..7),
) {
let wide_before: Vec<_> = before.iter().map(|&c| dec(c)).collect();
let wide_after: Vec<_> = after.iter().map(|&c| dec(c)).collect();
prop_assert_eq!(
kernel::bounds_kept(total, &before, &after),
kernel::bounds_kept(dec(total), &wide_before, &wide_after)
);
}
}
@@ -0,0 +1,199 @@
//! Entries bridge properties: the small amount-generic pieces the
//! statement of cash flows builds on.
//!
//! `kernel::take`, `entry_movements` and `flows_of` at `i64` cents (what
//! Kani proves, law 10) against the same on `Decimal` (what the engine
//! runs), on random lines.
use super::{arb_cents, dec};
use ledger_core::Side;
use ledger_core::kernel::{self, Flow};
use proptest::prelude::*;
fn arb_flow() -> impl Strategy<Value = Flow> {
prop_oneof![
Just(Flow::Cash),
Just(Flow::Operating),
Just(Flow::Investing),
Just(Flow::Financing),
]
}
fn arb_side() -> impl Strategy<Value = Side> {
prop_oneof![Just(Side::Debit), Just(Side::Credit)]
}
fn arb_flow_lines() -> impl Strategy<Value = Vec<(Flow, Side, i64)>> {
prop::collection::vec((arb_flow(), arb_side(), arb_cents()), 0..6)
}
fn to_dec(lines: &[(Flow, Side, i64)]) -> Vec<(Flow, Side, rust_decimal::Decimal)> {
lines.iter().map(|&(f, s, a)| (f, s, dec(a))).collect()
}
fn arb_direction() -> impl Strategy<Value = kernel::Direction> {
prop_oneof![
Just(kernel::Direction::Paid),
Just(kernel::Direction::Received),
Just(kernel::Direction::Neither),
]
}
/// Cents, plus the `i64` range's edges: [`arb_cents`] is bounded to ±2^40
/// (what a journal line may carry), so it never reaches the negation that
/// overflows, and the refusal path would go untested.
fn arb_edge_cents() -> impl Strategy<Value = i64> {
prop_oneof![arb_cents(), Just(i64::MIN), Just(i64::MAX)]
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(1000))]
/// `kernel::take` takes the same part of a movement at both types.
#[test]
fn take_agrees(remaining in arb_cents(), movement in arb_cents()) {
prop_assert_eq!(
kernel::take(remaining, movement).map(dec),
kernel::take(dec(remaining), dec(movement))
);
}
/// `kernel::entry_movements` nets the cash and each section the same.
#[test]
fn entry_movements_agree(lines in arb_flow_lines()) {
let i = kernel::entry_movements(&lines)
.map(|(cash, moved)| (dec(cash), moved.map(dec)));
let d = kernel::entry_movements(&to_dec(&lines));
prop_assert_eq!(i, d);
}
/// `kernel::flows_of` splits the cash the same, and refuses the same
/// lines that do not net to zero.
#[test]
fn flows_of_agree(
cash in arb_cents(),
moved in (arb_cents(), arb_cents(), arb_cents())
.prop_map(|(a, b, c)| [a, b, c]),
) {
let i = kernel::flows_of(cash, moved);
let d = kernel::flows_of(dec(cash), moved.map(dec));
prop_assert_eq!(
i.map(|f| (dec(f.cash), f.flows.map(dec), f.noncash.map(dec))),
d.map(|f| (f.cash, f.flows, f.noncash))
);
}
/// `kernel::catch_ups` gives every suffix's catch-up at both types.
#[test]
fn catch_ups_agree(
pairs in prop::collection::vec((arb_cents(), arb_cents()), 0..6),
) {
let scheduled: Vec<i64> = pairs.iter().map(|&(s, _)| s).collect();
let posted: Vec<i64> = pairs.iter().map(|&(_, p)| p).collect();
let mut i = vec![0i64; scheduled.len()];
let mut d = vec![dec(0); scheduled.len()];
let ri = kernel::catch_ups(&scheduled, &posted, &mut i);
let rd = kernel::catch_ups(
&scheduled.iter().map(|&c| dec(c)).collect::<Vec<_>>(),
&posted.iter().map(|&c| dec(c)).collect::<Vec<_>>(),
&mut d,
);
prop_assert_eq!(ri, rd);
prop_assert_eq!(i.into_iter().map(dec).collect::<Vec<_>>(), d);
}
/// `kernel::unrecovered_cost` is the same shortfall at both types.
#[test]
fn unrecovered_cost_agree(revenue in arb_cents(), expenses in arb_cents()) {
prop_assert_eq!(
kernel::unrecovered_cost(revenue, expenses).map(dec),
kernel::unrecovered_cost(dec(revenue), dec(expenses))
);
}
/// `kernel::Direction::of` classifies the same sign at both types, and
/// each case keeps its meaning (law 23).
#[test]
fn direction_of_agrees(cents in arb_cents()) {
let i = kernel::Direction::of(cents);
let d = kernel::Direction::of(dec(cents));
prop_assert_eq!(i, d);
if cents > 0 {
prop_assert_eq!(i, kernel::Direction::Paid);
} else if cents < 0 {
prop_assert_eq!(i, kernel::Direction::Received);
} else {
prop_assert_eq!(i, kernel::Direction::Neither);
}
}
/// `kernel::reverse_target` is the exact opposite at both types, and
/// `i64` refuses its range's edge (`i64::MIN`, which no negation can
/// hold): the edge strategy reaches that arm, and Decimal, which can
/// hold the negation, answers the opposite (law 24). The refusal is
/// the integer proof model's bound, not the law's.
#[test]
fn reverse_target_agrees(
amount in arb_edge_cents(),
cash in arb_edge_cents(),
in_kind in arb_edge_cents(),
direction in arb_direction(),
) {
let t = kernel::PartyTarget {
amount,
direction,
cash,
in_kind,
};
let d = kernel::PartyTarget {
amount: dec(amount),
direction,
cash: dec(cash),
in_kind: dec(in_kind),
};
let as_dec = |r: kernel::PartyTarget<i64>| kernel::PartyTarget {
amount: dec(r.amount),
direction: r.direction,
cash: dec(r.cash),
in_kind: dec(r.in_kind),
};
match kernel::reverse_target(t) {
Some(r) => prop_assert_eq!(Some(as_dec(r)), kernel::reverse_target(d)),
None => {
prop_assert!(
amount == i64::MIN || cash == i64::MIN || in_kind == i64::MIN,
"reverse_target refused an in-range target"
);
prop_assert_eq!(
kernel::reverse_target(d),
Some(kernel::PartyTarget {
amount: -dec(amount),
direction: direction.flip(),
cash: -dec(cash),
in_kind: -dec(in_kind),
})
);
}
}
}
/// `kernel::part_weight` is the same weight at i32, i64 and i128, and
/// `None` exactly for a part no calendar month has (laws 26-28).
#[test]
fn part_weight_agrees(month_days in 0u32..=40, days in 0u32..=40) {
let part = kernel::MonthPart { days, month_days };
let w32: Option<i32> = kernel::part_weight(part);
let w64: Option<i64> = kernel::part_weight(part);
let w128: Option<i128> = kernel::part_weight(part);
prop_assert_eq!(w64, w32.map(i64::from));
prop_assert_eq!(w128, w64.map(i128::from));
if part.is_valid() {
prop_assert_eq!(
w64,
Some(i64::from(days) * i64::from(kernel::MONTH_L / month_days))
);
} else {
prop_assert_eq!(w64, None);
}
}
}
@@ -9,6 +9,7 @@
// One file per kernel-sweep unit; the properties above stay here.
mod allocate;
mod control;
mod entries;
mod fx;
mod payroll;
mod ratio;
@@ -1637,6 +1637,60 @@ fn doc_line(
}
}
/// BS-arap-3 statement 1: custom terms are due on the date they give, not
/// on the document's own date. A document dated 2026-11-01 on "Due
/// 2026-11-15" is due on the 15th (through Terms::due_date and through the
/// stored document); an agreed date before the document's is refused like
/// any due date before its document; terms read back from storage (even
/// written before they carried the date) keep the date.
#[test]
fn custom_terms_are_due_on_the_date_they_give() {
let on = d(2026, 11, 1);
let agreed = d(2026, 11, 15);
let terms = Terms::parse("Due 2026-11-15").unwrap();
assert_eq!(terms.agreed_date(), Some(agreed));
assert_eq!(terms.due_date(on).unwrap(), agreed);
// The same, whichever day the document is dated (up to the 15th).
assert_eq!(terms.due_date(d(2026, 11, 15)).unwrap(), agreed);
assert_eq!(terms.due_date(d(2026, 1, 3)).unwrap(), agreed);
// Dated after the agreed day, the terms contradict the document.
assert!(terms.due_date(d(2026, 11, 16)).is_err());
// Other kinds give no agreed date.
assert_eq!(Terms::parse("Net 30").unwrap().agreed_date(), None);
// Through the engine: an invoice and a bill on those terms.
let mut b = books();
let invoice =
b.l.create_invoice_with(
b.customer,
on,
terms.due_date(on).unwrap(),
line("Work", 10_000),
InvoiceFields {
terms: Some(terms.clone()),
..InvoiceFields::default()
},
)
.unwrap();
let stored = b.l.get_invoice(invoice).unwrap();
assert_eq!(stored.due_date, agreed);
assert_eq!(stored.terms.as_ref().unwrap().describe(), "Due 2026-11-15");
// Storage round-trips the date; an older stored form, which had the
// text only, reads back with the date from its text.
let json = serde_json::to_value(&terms).unwrap();
assert_eq!(json["agreed"], "2026-11-15");
assert_eq!(serde_json::from_value::<Terms>(json).unwrap(), terms);
let old = serde_json::json!({"kind": "custom", "text": "Due 2026-11-15"});
assert_eq!(serde_json::from_value::<Terms>(old).unwrap(), terms);
// Custom terms with no readable date are refused, not invented.
let none = serde_json::json!({"kind": "custom", "text": "Due"});
assert!(serde_json::from_value::<Terms>(none).is_err());
// A date on any other kind is refused.
let stray = serde_json::json!({"kind": {"net": 30}, "text": "Net 30", "agreed": "2026-11-15"});
assert!(serde_json::from_value::<Terms>(stray).is_err());
}
/// BS-arap-3 SCENARIOS: Net 30, Net 15 EOM, a leap day, due on receipt, a
/// custom date, and the 9999-12 bound refused instead of panicking.
#[test]
+1 -1
View File
@@ -21,7 +21,7 @@ zip = "9.0.1"
workspace = true
[dev-dependencies]
bookspec-checker = { git = "https://git.swaits.com/swaits/bookspec", rev = "51375ecd529b3189af7f6316b0347d4ec6134cf1" }
bookspec-checker = { git = "https://git.swaits.com/swaits/bookspec", rev = "00b7c541d784696961a760f0486e2fe7a5e7c003" }
proptest = "1"
tempfile = "3"
toml = "1"
+26 -4
View File
@@ -19,13 +19,35 @@ instead:
Lean theorem it added;
- anything the solver could not do, and what carries it instead (Lean
at any size, a bridge property, an exhaustive unit test).
- **Workers do not edit `docs/verification.md` or `verify/lean/Audit.lean`.**
The integrator folds the unit notes into `verification.md`'s tables and
prose, and adds the `#print axioms` lines to `Audit.lean` in one place,
in one edit per batch, after the batch's merges.
- **Workers do not edit `docs/verification.md`.** The integrator folds
the unit notes into its tables and prose in one edit per batch, after
the batch's merges.
- **A unit's Lean theorems go into bookspec**, on the unit's bookspec
branch: the theorem in `lean/Bookspec/`, its `#print axioms` line in
bookspec's `lean/Audit.lean`. Wanderbooks keeps no audit list of its
own; `just prove` audits bookspec's, from the pinned package (D-69).
- A unit's note lands in the same commit as its harnesses, so the proof
and its description are never apart in history.
## The harness-to-law table (machine-readable)
The traceability gate
(`crates/ledger-core/tests/bookspec/traceability.rs`) reads every note here
for a table pairing each Kani harness with the bookspec law it proves:
| Harness | Law |
|---|---|
| `round_step_is_multiple` | 40 |
The first cell must be the harness name in backticks and the second a bare
integer (the number in bookspec's `spec/laws.md`); extra columns are allowed
after them (bounds, time, verification). The gate fails:
- a kernel `pub fn` whose harnesses have no such row ("lacks a law");
- a harness listed twice with different law numbers;
- a law whose Rules column shares no `BS-` id with the function's own
`SOURCE:` line, when the function has one.
`just prove` finds the harnesses by scanning `crates/ledger-core/src/proofs/`
(`mod.rs` plus every `<unit>.rs`), not one file; `just prove-list` prints
each harness, its module path, and whether it runs in `prove` or
+58
View File
@@ -0,0 +1,58 @@
# Entries: the party direction and a part's weight
Status: landed 2026-11-08 with the traceability gate's review fixes. Two
kernel functions that had no proof of their own now have one; both were on
the exception list before.
## The functions
| Function | Meaning |
|---|---|
| `kernel::Direction::of` | the direction of a signed amount: paid above zero, received below zero, neither at zero (BS-partner-3) |
| `kernel::part_weight` | a month part's weight in `MONTH_L`ths: `days × MONTH_L / month_days`, exactly; `None` for a part no calendar month has (BS-asset-1, BS-prepaid-1) |
## Kani harnesses (`crates/ledger-core/src/proofs/mod.rs`)
| Harness | Law | Bounds |
|---|---|---|
| `direction_of_is_the_sign` | 23 | any `i64` amount; all three signs covered |
| `part_weight_is_days_of_the_month` | 27 | `days` and `month_days` 0..=40; valid, partial, whole and invalid parts covered |
`part_weight_is_days_of_the_month` proves the weight formula a proration
charge is computed from, which is law 27's statement (each part but the
last is its days times the monthly rate); it is a lemma for laws 26-28,
not a restatement of law 26 (that the parts sum to the total, which is
`prorate_parts_sum_to_total` below).
The bookspec law each harness proves (machine-readable for the
traceability gate, `crates/ledger-core/tests/bookspec/traceability.rs`):
| Harness | Law |
|---|---|
| `direction_of_is_the_sign` | 23 |
| `part_weight_is_days_of_the_month` | 27 |
Times: measured alone with
`cargo kani -p ledger-core --exact --harness proofs::<name>` on 2026-11-08:
`direction_of_is_the_sign` 18 s wall (0.06 s verification, 3 covers, build
included); `part_weight_is_days_of_the_month` 11 s wall (0.49 s
verification, 3 covers, build included).
## Bridge (`crates/ledger-core/tests/kernel_bridge/entries.rs`)
- `direction_of_agrees`: `Direction::of` classifies the same sign at `i64`
and `Decimal`, and each case keeps its meaning (law 23).
- `part_weight_agrees`: `part_weight` is the same weight at `i32`, `i64`
and `i128`, and `None` exactly for a part no month has (laws 26-28).
- `reverse_target_agrees`: `reverse_target` is the exact opposite at both
types. The edge strategy reaches `i64::MIN`, which `i64` refuses because
no negation can hold it; `Decimal` can hold the negation, so the property
compares its answer there (the exact opposite). The refusal is the
integer proof model's bound, not the law's. The earlier bridge only
passed it to `and_then`, which is a mention, not a call; this property
calls it.
Why these laws: `Direction::of` is the sign classification the party
direction law (23) is stated over, and `part_weight` is the weight the
proration charges of laws 26-28 are computed from, its harness numbered
for the law it restates most closely (27).
+10
View File
@@ -88,6 +88,16 @@ carries the same laws to every `Decimal` step, and Lean to any step.
| `fx_booked_positive_for_positive` | positive inputs book non-negative, positive once the product reaches half a unit | 3.2 s (2 covers) |
| `fx_booked_refuses_overflow` | an overflowing product and a non-positive rate are `None`, never a panic | 2.6 s (2 covers) |
The bookspec law each harness proves (machine-readable for the
traceability gate, `crates/ledger-core/tests/bookspec/traceability.rs`):
| Harness | Law |
|---|---|
| `fx_booked_is_whole_unit` | 41 |
| `fx_booked_within_half_unit` | 41 |
| `fx_booked_positive_for_positive` | 41 |
| `fx_booked_refuses_overflow` | 41 |
What the harnesses do and do not prove, stated plainly:
- `fx_booked_refuses_overflow` proves **two concrete overflow cases**
+15
View File
@@ -54,6 +54,21 @@ bookspec's Lean proves them for any step.
| `round_step_sign_preserved` | every mode: `0 <= x` gives `0 <= r`, `x <= 0` gives `r <= 0` | 13 s wall incl. build (3 covers) |
| `round_step_refuses_nonpositive_step` | a step of zero or less is `None` | 8 s total (1 cover) |
The bookspec law each harness proves (machine-readable for the
traceability gate, `crates/ledger-core/tests/bookspec/traceability.rs`):
| Harness | Law |
|---|---|
| `round_step_is_multiple` | 40 |
| `round_step_is_nearest` | 40 |
| `round_step_ties` | 40 |
| `round_step_is_idempotent` | 40 |
| `round_step_never_negative_zero` | 40 |
| `round_step_toward_zero_bounds` | 40 |
| `round_step_toward_neg_inf_is_floor` | 40 |
| `round_step_sign_preserved` | 40 |
| `round_step_refuses_nonpositive_step` | 40 |
The three directed-mode harnesses were added after review: the spec block's
invariants 3, 4 and 6 had no proof of their own (Lean had the ties, Kani
checked these two modes only at exact ties). Demonstrated: with
+12
View File
@@ -34,6 +34,18 @@ model-checking/kani#4904), each with `kani::cover!`.
| `total_try_is_map_sum` | `total_try` of differences is the sum of the differences; a failing map fails the total | 0..=4 pairs, in-range | 5.3 s |
| `total_overflow_is_none` | for two arbitrary `i64`s, `total` is `Some` exactly when the true sum fits; both overflow directions covered | all `i64` pairs | 0.5 s |
The bookspec law each harness proves (machine-readable for the
traceability gate, `crates/ledger-core/tests/bookspec/traceability.rs`):
| Harness | Law |
|---|---|
| `total_empty_is_zero` | 4 |
| `total_append` | 4 |
| `total_is_sound` | 4 |
| `total_of_is_map_sum` | 4 |
| `total_try_is_map_sum` | 4 |
| `total_overflow_is_none` | 4 |
Times: alone, `cargo kani --exact --harness`, the shared dev machine under
`nice -n 10`, 2026-11-08. `total_append` was 115 s at runs of up to 4 and
was reduced to up to 3 (the same law; 60 s) to keep `just prove` fast. A
+1 -1
View File
@@ -73,7 +73,7 @@ and no one owes), leaving out payroll runs, entries marked as having no
counterparty, entries naming only parties with no 1099 role, and entries
reversed in the year: one count, the entries when ten or fewer, and the
tool to tag them.
*Enforced:* `form1099::Vendor1099Report::untagged`, `books.vendor_1099`,
*Enforced:* `form1099::untagged_payments`, `books.vendor_1099`,
`books.set_entry_vendor`; the digest and Needs attention.
*Checked:* `the_untagged_note_counts_only_money_out`,
`the_other_receipts_note_says_what_each_entry_did` (ledger-package).
+19 -4
View File
@@ -27,6 +27,17 @@ Rules: B-18, B-38, B-39, B-40, B-41, B-42.
`a_payment_never_predates_its_document`, `aging_as_of_ignores_a_later_reversal`,
`a_voided_invoice_never_ages`, `status_is_a_function_of_journal_and_date`.
**Bookspec examples:** `arap-aging-buckets` (BS-arap-1);
`arap-a-document-due-today-is-current` (BS-arap-7);
`arap-an-aging-shows-what-stood-on-its-day` (BS-arap-8);
`arap-a-payment-before-its-invoice-is-refused` (BS-arap-9), run by the
adapter through `Ledger::{ar_aging, ap_aging, receive_payment, pay_bill}`
(`tests/bookspec/queries/documents.rs`). The examples for the options
wanderbooks did not pick (`arap-a-document-due-today-is-one-day-past-due`,
`arap-an-aging-shows-what-stands-today`,
`arap-a-payment-before-its-invoice-is-accepted`) name the option they rest
on, and the runner skips them for the pick above.
## B-38 A document's figures are its ledger lines that stand; a control account is its documents
**bookspec:** `BS-arap-2`
@@ -65,7 +76,7 @@ Lean `Documents.control_agrees`, `Documents.Step.document_unattached`,
(through role assignments and releases),
`Documents.Reachable.control_is_documents`. The model's limits: it
starts from empty books (legacy lines are covered by the identity
`control_agrees` alone), it names documents by one id space (an injective
`Documents.control_agrees` alone), it names documents by one id space (an injective
coding of `DocRef`), and an account becoming a control account by its
first document, holding lines from before, is outside it (those lines are
listed as unattached).
@@ -137,7 +148,10 @@ check_void_document}`, the control guard). **Checked:**
**Enforced:** `ledger_core::Terms` (`new`, `parse`, `due_date`,
`discount_by`, `describe`), `kernel::discount_max`, `kernel::line_amount`,
`Ledger::check_document_line_account`.
**Checked:** `ledger-core` `tests/spec_documents.rs`
**Checked:** bookspec example `arap-terms-give-due-and-discount-dates`
(the adapter takes each due date from `Terms::due_date`, but for a date
the parties agreed, which that call leaves to its caller, and each discount
date from `Terms::discount_by`); `ledger-core` `tests/spec_documents.rs`
(`terms_derive_due_dates`, `discount_bounds_and_late_reason`,
`terms_describe_and_parse_round_trip`, `qty_times_price_must_equal_amount`,
`document_line_account_refuses_roles_cash_and_placeholders`,
@@ -311,8 +325,9 @@ check_discount}`, `arap::{Application, Fee, SettleParams, SettlementRow}`,
(`a_settlement_names_its_lines_and_replays`, `settlement_waits_for_documents_v2`,
`legacy_payment_events_keep_the_positional_rule`), `tests/arap_props.rs`;
`ledger-cli` `tests/documents.rs`; `ledger-package`'s aging tie-out test.
The Lean step is `Documents.Step.document` with every control line tagged
(`Documents.settle_unattached`); no new `Step` constructor.
The Lean step is the document constructor of the Lean documents model, with
every control line tagged (`Documents.settle_unattached`); no new step
constructor.
### Product rules
+5 -5
View File
@@ -87,7 +87,7 @@ those dates say. (That depreciation starts on the in-service date and that
the register holds the asset from the acquired date are `BS-asset-1`
rules 23-24.)
*Enforced:* `set_asset_acquisition` / `replay_set_asset_acquisition`,
`Ledger::asset_acquired_date`, `dispose_asset`, `Asset::set_entry`.
`Ledger::asset_acquired_date`, `dispose_asset`, `Ledger::set_asset_acquisition`.
*Checked:* `ledger-core` `tests/spec_asset_basis.rs` (each bound and its
replay pair); `ledger-store` `tests/bounds.rs`.
@@ -103,7 +103,7 @@ run again and that run reversed is the month's run.
**bookspec:** `BS-asset-2`
**Claims:** partly (the books' own AGENTS.md follows it; the engine enforces nothing)
**Claims:** no (no engine enforcement exists: the policy is the books' own AGENTS.md, and the de minimis and 12-month elections are made on the return)
**Pick:** none (AUTHORITY; procedural). The books' own AGENTS.md sets the policy; the de minimis and 12-month elections are made on the return.
@@ -124,11 +124,11 @@ None.
**Pick:** `tag-and-never-reuse`: CHOICE (the owner, 2026-10-15): each asset may carry one tag, generated `PREFIX-0001` or the human's own, unique ignoring case and never reused, and the register reconciles to the cost and accumulated depreciation accounts.
**Enforced:** `Ledger::set_asset_tag` / `check_asset_tag_for` /
`check_asset_tag` (`tag_in_use`, the retag keeping the old tag reserved),
`check_asset_tag` (the tag already taken is refused, the retag keeping the old tag reserved),
`Ledger::set_asset_serial` / `check_asset_serial`, `assets::check_asset_tag`,
`assets::check_serial`, `reports::fixed_asset_register`.
**Checked:** `ledger-core` `tests/spec_asset_tags.rs`; `ledger-store`
`tests/asset_tags.rs` (`a_tag_is_unique_ignoring_case`,
`tests/asset_tags.rs` (`a_journaled_tag_taken_by_another_asset_is_refused_on_open`,
`a_retagged_assets_old_tag_is_never_reused`);
`ledger-cli` `tests/spec_assets.rs`.
@@ -184,7 +184,7 @@ and Needs attention asks for the value.
*Enforced:* `replay_set_asset_tax_basis`, `AssetBasis::check_legacy_journaled`;
`ledger-gui` Needs attention.
*Checked:* `ledger-core` `tests/spec_asset_basis.rs`
(`a_legacy_basis_record_reads_its_book_cost`); `ledger-store`
(`legacy_tax_basis_set_lines_replay_to_todays_figures`); `ledger-store`
`tests/asset_tags.rs`.
**WB-asset-5** The tool surface never assumes a contributed property's
+2 -2
View File
@@ -178,7 +178,7 @@ open, never a panic.
*Enforced:* derived: `Invoice::total`/`balance`,
`Bill::total`/`balance`, `AgingRow::total`, `ar_aging`, `ap_aging`,
`PayrollLine::net_pay`, `payroll_entry_plan`, `parties::entry_flow`,
`shares::share_target`, `shares::resolve`, `fixed_asset_register`,
`shares::target`, `shares::resolve`, `fixed_asset_register`,
`schedules::amortization_plan`, `month_end`, `depreciation_schedule`,
`analysis::intervals`, `form1099::vendor_part`, `k1::share_property`,
`ReceiptPolicy::entry_debits`.
@@ -203,7 +203,7 @@ pinned; every tool over every old book).
`Ledger::{set_draft_state, discard_draft, posted_seq}`,
`Store::{set_draft_state, discard_draft, post_entry_checked}` (the gate the server posts a hand draft by; `Store::post_entry` stays the primitive commands and fixtures post through); events
`entry.draft_state_set`, `entry.draft_discarded` (feature `drafts_v2`).
**Checked:** Lean `Step.discard`, `Step.discard_keeps_books`,
**Checked:** Lean `Step.discard_keeps_books`,
`Step.discard_unblocks_close`; `ledger-core` `tests/invariants.rs`
(`discard_unblocks_close`); `ledger-store` `tests/store.rs`
(`draft_states_replay_and_project`, `drafts_v2_waits_for_the_upgrade`,
+2 -2
View File
@@ -12,7 +12,7 @@ Rules: B-27, B-34.
## B-27 The journal format gate: newer is not corrupt
**bookspec:** `BS-format-1`
**retired bookspec:** `BS-format-1`
**Claims:** no (retired 2026-11-08, D-71: wholly wanderbooks'); its one
engine-independent sentence — a reader that does not know a record's format
@@ -161,7 +161,7 @@ the W-9 when the vendor's W-9 flag follows it. A value in a line of a known
type that only a newer version writes (a 1099 decision or reason kind, a
payment method's kind) is newer, never corrupt.
*Enforced:* `ledger_store::format` (`JournalFormat::declared`, `require_format`, `require_feature`), `Store::ensure_feature`, `Store::declare_journal_format`, `StoreError::FormatUpgradePending`, `format::setting_feature`, `format::tax_category_feature`.
*Enforced:* `ledger_store::format` (`format::declared`, `require_format`, `require_feature`), `Store::ensure_feature`, `Store::declare_journal_format`, `StoreError::FormatUpgradePending`, `format::setting_feature`, `format::tax_category_feature`.
*Checked:* `ledger-store` `tests/settings.rs` (`a_change_needs_journal_format_2`), `tests/format_upgrade.rs` (`a_write_waiting_for_the_upgrade_journals_nothing`, a newer feature still refused); `tests/p2_compat.rs` (every P3 setting key and tax category needs a feature); the unit tests in `format.rs`.
**WB-format-3 The other way round: the format upgrade, with the owner's
+30 -10
View File
@@ -84,8 +84,7 @@ None.
**Enforced:** posted entries immutable; `ledger_store::format`
(`JournalFormat::admit`, `gate`): a record in a format version this
version does not know is refused as newer, neither misread nor skipped,
and never called corrupt (statement 4). **Checked:** Lean `Step.extends`,
`Steps.extends`; property `prop_posted_entries_immutable`; `ledger-store`
and never called corrupt (statement 4). **Checked:** Lean `Steps.extends`; property `prop_posted_entries_immutable`; `ledger-store`
`tests/format.rs` (`old_reader_gets_newer_journal`,
`a_newer_line_the_next_line_chains_onto_is_newer_and_intact`,
`damaged_journals_are_still_corrupt`).
@@ -161,6 +160,11 @@ None.
**Pick:** a reversal's evidence is its original's (a reversal needs no evidence of its own): CHOICE D-47 (the owner, 2026-10-26; options: a reversal's evidence is its original's / a reversal needs its own). The rest is AUTHORITY; a procedural rule.
**Enforced:** the MCP receipt policy (not the engine; R-13).
**Checked:** `ledger-cli` `tests/drafts.rs`
(`a_draft_waits_for_its_receipt_and_posts`,
`a_reversal_needs_no_receipt_of_its_own`); `ledger-store`
`tests/store.rs` (`draft_states_replay_and_project`,
`drafts_v2_waits_for_the_upgrade`).
### Product rules
@@ -190,10 +194,13 @@ frees its code); the control guard and `Ledger::control_check` (B-38).
*Enforced:* `Ledger::assign_role` / `check_assign_role`. *Checked:* `ledger-store` replay of `role.assigned`.
**WB-ledger-3** The account at a role's default code is the role's control account only once a document posts there (or the role is assigned to it): before that, a chart's own 1200 Equipment or a card at 2000 is the chart's.
*Enforced and checked:* with B-23 above (`Ledger::check_controls`, the control guard, `Ledger::control_check`; `tests/spec_roles.rs`, `tests/spec_documents.rs`).
**Enforced:** `Ledger::check_controls`, the control guard, `Ledger::control_check`; `tests/spec_roles.rs`, `tests/spec_documents.rs`.
**Checked:** `tests/spec_roles.rs`, `tests/spec_documents.rs`.
**WB-ledger-4** Until the balance of a receivables or payables control account moves with its documents (plan P4b S7), a receivables or payables role whose control account holds a balance stays where it is, and the refusal says so: it names no hand entry, which the control guard would refuse.
*Enforced and checked:* with B-23 above (`Ledger::check_assign_role`, `Ledger::check_renumber_account`, the control guard; `tests/spec_roles.rs`, `tests/spec_documents.rs`).
**Enforced:** `Ledger::check_assign_role`, `Ledger::check_renumber_account`,
the control guard. **Checked:** `tests/spec_roles.rs`,
`tests/spec_documents.rs`.
## B-29 The books keep how they are kept
@@ -225,7 +232,10 @@ checked to change no figure or entry;
*Checked:* `ledger-config` `tests/codec_props.rs` (`exports_round_trip`) and codec unit tests; `ledger-store` `tests/settings.rs` (`books_written_under_p1_open_to_their_record`, fixture `old-books/p1_record`).
**WB-ledger-6** No setting, convention id, convention, decision, open item or approval holds a number that reads as a full TIN (nine digits standing alone, bare or printed 3-2-4 or 2-7 with a dash or a space), except the company's own EIN, shown masked everywhere but reports, packages and the viewer, and a D-U-N-S number in its own key.
*Enforced and checked:* with B-29 above (the settings and conventions checks and their tests).
**Enforced:** `ledger_core::settings::check` and the conventions checks
(`check_new`, `check_decision`, `check_open_item`).
**Checked:** `ledger-core` settings and conventions unit tests;
`ledger-store` `tests/settings.rs` (`settings_replay_is_pure`).
**WB-ledger-7** Books keep their own settings, and only `books.set_setting` changes them; old books bring their settings file in once, whole, as they are adopted (`wanderbooks books adopt`), and nothing reads one after.
*Enforced:* `Store::adopt_settings`; `ledger-mcp` adoption (`local.rs` `settings_to_move`: a settings file, whole, through `codec::import`).
@@ -269,7 +279,7 @@ which is journaled with its name trimmed too. **Checked:** `ledger-core`
`ledger-core` `tests/spec_ledger.rs`
(`a_new_name_is_one_trimmed_line_of_bounded_length`), `ledger-store`
`tests/store.rs` (`a_new_accounts_name_is_journaled_trimmed`); Lean
`Step.record` (a name is outside the model: `docs/verification.md` law 15);
`Step.record_changes_no_figure` (a name is outside the model: `docs/verification.md` law 15);
bookspec `examples/rename-changes-no-amount.toml`.
### Product rules
@@ -300,8 +310,8 @@ rounding). **Checked:** `ledger-core`
`a_category_rounds_once_across_different_percents`); Kani
`deductible_amount_rounds_once`, `deductible_amount_refuses_overflow`;
bridge `deductible_amount_agrees`; Lean `bookspec/lean/Bookspec/Deductible.lean`
(`Deductible.near`, `tie_away_pos`, `tie_away_neg`, `sign`, `neg`, `of_sum`,
`per_account_differs`, `scale_books`, `scale_percents`: the one rounding, at any
(`Deductible.near`, `Deductible.tie_away_pos`, `Deductible.tie_away_neg`, `Deductible.sign`, `Deductible.neg`, `Deductible.of_sum`,
`Deductible.per_account_differs`, `Deductible.scale_books`, `Deductible.scale_percents`: the one rounding, at any
number of accounts and any sizes); bookspec `examples/tax-category-required.toml`.
### Product rules
@@ -316,12 +326,17 @@ number of accounts and any sizes); bookspec `examples/tax-category-required.toml
## B-44 Evidence is read from the bytes, never trusted over them; identical files are kept once
**bookspec:** `BS-ledger-12`
**retired bookspec:** `BS-ledger-12`
**Claims:** yes (wholly a product rule: BS-ledger-12 is retired, D-71)
**Pick:** none (CONVENTION; Rev. Proc. 98-25 and Pub. 583 for the audit trail).
**Enforced:** the product rule below, `WB-ledger-15` (its *Enforced:*
paragraph names the import, store and attachment functions).
**Checked:** the product rule below, `WB-ledger-15` (its *Checked:*
paragraph names the import, store and CLI tests).
### Product rules
**WB-ledger-15** Evidence is read from the bytes, never trusted over them; identical files are kept once.
@@ -402,12 +417,17 @@ withdraw_attachment_duplicate}` and `Store::attach`'s dedup; feature
## B-45 An audit is deterministic over the books; an attestation is a claim by a named client
**bookspec:** `BS-ledger-13`
**retired bookspec:** `BS-ledger-13`
**Claims:** yes (wholly a product rule: BS-ledger-13 is retired, D-71)
**Pick:** CHOICE D-9 (owner-adopted recommendation, 2026-10-16): the attestation bar, and the CPA package waits for a counted audit unless given a reason. Otherwise CONVENTION (the SOURCE block below; Pub. 583 and Rev. Proc. 98-25 for the audit trail).
**Enforced:** the product rule below, `WB-ledger-16` (its *Enforced:*
paragraph names the audit and store functions).
**Checked:** the product rule below, `WB-ledger-16` (its *Checked:*
paragraph names the core, store, import and CLI tests).
### Product rules
**WB-ledger-16** An audit is deterministic over the books; an attestation is a claim by a named client.
+2 -2
View File
@@ -36,8 +36,8 @@ Rules: B-13, B-26, B-35, B-36.
`closePart_total`, `trueUp_total`, `trueUp_running`,
`closePart_eq_trueUp`, `cumulative_drift`, `statement_after_close`,
`statement_unmoved_by_close`, `Apportion.rem_pos_of_rank_lt`,
`apportion_drift`, `allocW_sum`, `allocW_drift`,
`allocW_cumulative_drift`, `allocW_cumulative_total`; properties
`Apportion.apportion_drift`, `Apportion.allocW_sum`, `Apportion.allocW_drift`,
`Apportion.allocW_cumulative_drift`, `Apportion.allocW_cumulative_total`; properties
`prop_split_*`, `each_members_capital_chains_across_statements`,
`each_member_stays_within_a_cent_of_their_share`,
`members_capital_never_drifts_a_cent_from_their_share`,
+6 -3
View File
@@ -59,8 +59,11 @@ schedules round to the currency's minor unit. Schedules an earlier
version took mid-month under equal months replay as they were. (The
engine change is unit K-U5's; this note records the claim.)
**Enforced:** `schedules` replay (`amortization_plan`),
`Ledger::schedule_month_hold`. **Checked:**
`defect9_legacy_schedules_stay_monthly_even`,
**Claims:** partly (the replay half is implemented; moving new monthly-even
schedules to the currency's minor unit is K-U5, not landed)
**Enforced:** `schedules::amortization_plan` (the cent rule, kept for
replay), `Ledger::replay_register_schedule`, `Ledger::schedule_month_hold`.
**Checked:** `defect9_legacy_schedules_stay_monthly_even`,
`prop_monthly_even_plan_is_unchanged`,
`a_schedule_month_posted_again_waits_for_month_reposting_and_replays`.
+5
View File
@@ -22,6 +22,11 @@ Lean `trial_balance_iff`, `Reachable.trial_balance`,
**Claims:** yes
**Enforced:** every posted entry obeys B-1, so `kernel::check_lines`
refuses an unbalanced one; `Ledger::post_entry` applies it to every
posting, and `kernel::normal_balance` reads each account by its type, so
`reports::balance_sheet` and `reports::trial_balance` present the same
assets and liabilities-plus-equity at every date.
**Checked:** Kani `accounting_equation`; Lean `accounting_equation`,
`Reachable.accounting_equation[_through]`; property
`prop_balance_sheet_balances`.
+4 -3
View File
@@ -49,9 +49,10 @@ payroll, U8 control, U9 display) each get files of their own:
`total`, `schedule`, `ratio`, `payroll`, `control`; `proofs/mod.rs` holds
the original harnesses and each unit adds `proofs/<unit>.rs`. A unit
writes its proof note in `docs/proofs/<unit>.md`; the integrator folds the
notes into this file and the `#print axioms` lines into
`verify/lean/Audit.lean` in one edit per batch. Workers do not edit this
file (see `docs/proofs/README.md`).
notes into this file in one edit per batch; a unit's Lean theorems and
their `#print axioms` lines go into bookspec (its `lean/Audit.lean`,
which `just prove` audits from the pinned package). Workers do not edit
this file (see `docs/proofs/README.md`).
## The laws
+3 -1
View File
@@ -74,7 +74,9 @@ prove: (_kani "fast")
set -euo pipefail
cd verify/lean
lake build
audit=$(lake env lean Audit.lean)
# The audit is bookspec's own, from the pinned package: the laws and
# their list live once there (D-69), so no copy here can fall behind.
audit=$(lake env lean .lake/packages/bookspec/lean/Audit.lean)
if grep -v -E "depends on axioms: \[(propext|Quot.sound|Classical.choice)(, (propext|Quot.sound|Classical.choice))*\]$|does not depend on any axioms" <<<"$audit"; then
echo "Lean audit: a theorem rests on something beyond the standard axioms" >&2
exit 1
+2 -1
View File
@@ -74,6 +74,7 @@ workers have been faster).
| **L-G2, G4** | Documents in the executable model; more queries (closes to members, proration, cash flow last) | L-G3 | bookspec `lean/Exec/**` | L |
| **X-H0** | Split the 4,647-line adapter `crates/ledger-core/tests/bookspec.rs` into modules, no behaviour change | none | `crates/ledger-core/tests/bookspec/**` | S-M |
| **X-H1** | Schema additions for the missing examples (balance sheet, general ledger, tax summary, 1099 worksheet, aging, payments, drafts and evidence, refused input); and examples for every CHOICE record on `rules/allow-no-example.txt` (the EM, 2026-11-08, revised: every embedded CHOICE becomes its own record now so an engine can declare a pick for it; a record's examples must genuinely exercise it, an example is never linked to a choice it doesn't depend on, so the CHOICEs no example can show yet go on the allow-list, whose cap is raised once for them, from 9, and only shrinks after; X-H1/X-H2 work it down. Among them, from S-C7b's `s-c7b-noexample`: partner prepaid-contract, shares-in-force, prepaid basis; asset §704(c) method; 1099 payee's share; arap due-today, as-of reading, payment before its document, vendor reference compare, recovery form, gross discount, gross fee, discount apportioning; format closing entries, the customer/vendor NAME, the two-A/R refusal; and from S-C7a the records no example exercises: BS-entry-6..8, BS-ledger-14, -17, -18, -19, -21, BS-period-4, BS-prepaid-4, subject to its review) | S-A, X-H0 | bookspec `checker/src/schema.rs`; the adapter | L |
| **X-H1a..e** | X-H1 in five slices, run one after another (each adds to bookspec's `schema.rs`, `derive.rs`, `lean/Exec.lean` and the adapter): **a** A/R and A/P reading: a payment event, the aging and due-date queries (BS-arap-1, -3, -7, -8, -9); **b** settlements, recoveries, vendor references, invoice numbers (BS-arap-4, -6, -10..14); **c** drafts and evidence (BS-entry-5, -6, BS-ledger-17); **d** refused input spelled in the schema (BS-entry-4, -7, BS-period-4, BS-ledger-19, BS-format-10, BS-1099-2, BS-partner-8); **e** the rest (BS-partner-15..17, BS-asset-3, -9, BS-1099-5, BS-ledger-9, -18, -21, BS-statement-9, BS-format-8, -9, BS-prepaid-4, BS-revenue-1), and BS-prepaid-2's examples made to depend on its pick: today every schedule event names its convention, so no schedule example depends on the engine's method, and for whole months from the 1st the two methods agree; a schedule that takes the engine's method, with a mid-month start, does (the X-H1a re-check, 2026-11-08). Each slice: the schema, its derivation, Lean runs it or skips it with a reason, examples per rule and per option, both allow-lists shrink (the EM, 2026-11-08) | X-H1's needs | as X-H1 | M each |
| **X-H2** | Examples from the 2026-11-07 goldens, each from its worksheet | X-H1 (4 need nothing) | bookspec `examples/*.toml` | M |
| **X-I** | Per-rule coverage in the runner with a floor (stated rules with an example never decrease); a CI step, like `scripts/parity-floor.sh`, that fails when `rules/ids-issued.txt` loses a line or the allow-list grows against the base commit (the in-tree checks can't see a record and its ids-issued line deleted together) | S-A, X-H2 | bookspec `runner/`, `checker/tests/coverage.rs` | S-M |
| **X-J** | wanderbooks traceability gate: every claimed BS id has an enforcement site and a test, every law a Lean theorem, every CHOICE a declared pick, every kernel function a Kani harness, a bridge property and a law | S-D, S-E, L-F2 | `crates/ledger-core/tests/traceability.rs`, `docs/spec/claims/**` | M |
@@ -82,7 +83,7 @@ workers have been faster).
| **K-U0** | Kernel and proofs into modules (`kernel/`, `proofs/`, `tests/kernel_bridge/`), `_kani` updated, `just prove` unchanged | none | `crates/ledger-core/src/{kernel,proofs}/**`, `tests/kernel_bridge/**`, `justfile` | S |
| **K-U1..U9** | The sweep (`plan/kernel-sweep-audit.md` section 3), in value order: U1 FX, U3 shares (six copies to one; legacy replay policies only named, never changed), U2 rounding, U5 schedules (D-72), U4 totals (the raw-operator panic class), U6 ratios, U7 payroll, U8 control and aging, U9 display rounding. Each: kernel functions, Kani, bridge, its law in bookspec's Lean, its rule cited by BS id | K-U0; Lean laws after L-F2 | its own `kernel/<unit>.rs`, `proofs/<unit>.rs`, bridge module, call sites | S-M each |
| **S-E2** | The 13 rule citations S-E kept in program output move to BS ids together: the eight B-43 evidence-source strings in `ledger.rs`, the two lines recording them in `ledger-store/tests/golden/draft_states_and_evidence_gate.json` (a string-only golden edit, verified by hand and explained in the commit), `ledger-package/src/package.rs` (CPA package text), `ledger-mcp/src/tools/settlements.rs` (a tool description), and the GUI `CONTRIBUTION_NOTE` (`rules.md B-37 item 7`). First establish whether any of these strings is stored in a journal or the store (then old books must still read: replay keeps the old text, new writes the new); then shrink `source_refs.rs`'s kept-string allow-list to zero (S-E review, 2026-11-08) | S-E merged | those six files, the golden, `tests/bookspec/source_refs.rs` | S |
| **K-U10** | `impl Amount for Decimal`'s `checked_add` and `checked_mul` exact or None (BS-ledger-1: a product the arithmetic can't hold MUST be refused; BS-entry-4): `checked_mul` rounds a product whose mantissa passes 96 bits (K-U1's fix, 2026-11-08: `1050000010.0000000001 × 9.9999999999` books 10500000099.90 for an exact 10500000099.8949…, both inputs within D-75's ten places; pinned by `the_mantissa_edge_is_outside_the_precondition_and_pinned`), and `checked_add`: `rust_decimal` rounds dust away within one unit of `Decimal::MAX` (`MAX + 0.4` gives `Some(MAX)`), breaking the kernel's exact-or-None contract (found by K-U4, 2026-11-08; pinned by the canary `finding_decimal_add_rounds_dust_at_the_edge`): refuse a sum whose result scale fell below the operands'; after the sweep units merge (the file is shared) | K-U4 merged | `kernel/entries.rs`, the canary, the bridge | S |
| **K-U10** | `impl Amount for Decimal`'s `checked_add` and `checked_mul` exact or None (BS-ledger-1: a product the arithmetic can't hold MUST be refused; BS-entry-4): `checked_mul` rounds a product whose mantissa passes 96 bits (K-U1's fix, 2026-11-08: `1050000010.0000000001 × 9.9999999999` books 10500000099.90 for an exact 10500000099.8949…, both inputs within D-75's ten places; pinned by `the_mantissa_edge_is_outside_the_precondition_and_pinned`), and `checked_add`: `rust_decimal` rounds dust away within one unit of `Decimal::MAX` (`MAX + 0.4` gives `Some(MAX)`), breaking the kernel's exact-or-None contract (found by K-U4, 2026-11-08; pinned by the canary `finding_decimal_add_rounds_dust_at_the_edge`): refuse a sum whose result scale fell below the operands'; after the sweep units merge (the file is shared). Also from K-U3's review (2026-11-09): `split_by_weights_into` ranks remainders by Decimal's rounded quotient, so an exact tie is decided by the 28th digit, not given to the earlier part as the docs and the Lean model say (20.00 by 4/1/1 gives 13.33, 3.34, 3.33 where exact ranking gives 13.34, 3.33, 3.33); the pre-U3 sites did the same, and K-U3 kept it and pinned both cases. Ranking by the exact integer remainder (`whole x w - part x total`, as `share_floor_with` does) moves a cent between parties in reports recomputed for past periods: an owner decision, put with the cents it moves before it lands | K-U4 merged | `kernel/entries.rs`, the canary, the bridge | S |
| **V-D** | Coverage report and floor; `rust_decimal` checked against exact rationals (task D) | none | in flight 2026-11-08 | S |
| **V-D2** | Tests where coverage is thinnest (the V-D findings, `docs/coverage-floor.md`): `ledger-store` `reconcilable.rs` (0% from the store's own suite), `ledger-core` `evidence.rs` (34% lines, 9% branches from the core's suite), `ledger.rs`'s command steps (`mark_sent_steps`, `settle_steps`, `run_payroll_steps`, …) and refusal arms, `conventions.rs` and `settings.rs` validation refusals, `audit.rs` branches; each test encodes the rule it covers; the floor rises with them | V-D | the crates' tests | M |
-159
View File
@@ -1,159 +0,0 @@
import Bookspec
/-! `just prove` runs this file: each theorem's axioms are printed, and must
be only Lean's standard three (`propext`, `Quot.sound`, `Classical.choice`)
or fewer. No `sorryAx`, nothing assumed. The theorems are bookspec's: the
118 headline laws and the 33 named laws that cite them (D-69). -/
open Bookspec
#print axioms Accepted.net_zero
#print axioms sum_movements
#print axioms movement_with_reversal
#print axioms accepted_reversal_iff
#print axioms accounting_equation
#print axioms balance_after_line
#print axioms trial_balance_iff
#print axioms closingEntry_net
#print axioms closingEntry_zeroes
#print axioms closingEntry_accepted
#print axioms net_closings_is_net_income
#print axioms plugLast_total
#print axioms plugLast_keeps
#print axioms runPart_telescopes
#print axioms closePart_total
#print axioms trueUp_total
#print axioms trueUp_running
#print axioms closePart_eq_trueUp
#print axioms cumulative_drift
#print axioms statement_after_close
#print axioms statement_unmoved_by_close
#print axioms Reachable.inv
#print axioms Reachable.books_net_zero
#print axioms Reachable.trial_balance
#print axioms Reachable.trial_balance_through
#print axioms Reachable.accounting_equation
#print axioms Reachable.accounting_equation_through
#print axioms Steps.extends
#print axioms Steps.frozen
#print axioms close_zeroes
#print axioms close_credits_net_income
#print axioms statements_add_up
#print axioms Apportion.ranks_perm
#print axioms Apportion.apportion_sum
#print axioms Apportion.apportion_sum_of_shortfall
#print axioms Apportion.rem_pos_of_rank_lt
#print axioms Apportion.apportion_drift
#print axioms Apportion.allocW_sum
#print axioms Apportion.allocW_drift
#print axioms Apportion.allocW_cumulative_drift
#print axioms Apportion.allocW_cumulative_total
#print axioms Step.record_changes_no_figure
#print axioms Reachable.records
#print axioms net_splits_by_flow
#print axioms applyCash_conserves
#print axioms applyCash_exhausts
#print axioms applyCash_neg
#print axioms entry_flows_sum
#print axioms flows_reversal
#print axioms constructive_nets
#print axioms constructive_neg
#print axioms constructive_sections_net
#print axioms stmt_flows_sum
#print axioms stmt_flows_reversal
#print axioms cashflow_sections_sum_to_cash_change
#print axioms secNet_cash_is_movement
#print axioms operating_reconciliation_ties
#print axioms operating_reconciliation_ties_all
#print axioms cashflow_reversal_nets
#print axioms Reachable.cashflow_foots
#print axioms Reachable.cashflow_is_change_in_cash
#print axioms reverseTarget_involutive
#print axioms capitalTarget_odd
#print axioms partyTarget_odd
#print axioms sumOver_movement_reversal
#print axioms Prorate.cum_mono
#print axioms Prorate.cum_le
#print axioms Prorate.cum_full
#print axioms Prorate.parts_telescope
#print axioms Prorate.prorate_total
#print axioms Prorate.prorate_nonneg
#print axioms Prorate.part_within_a_unit
#print axioms Prorate.roundUnit_near
#print axioms Prorate.roundUnit_scale
#print axioms Prorate.cum_near
#print axioms Prorate.cum_dvd
#print axioms Prorate.part_near
#print axioms Prorate.chargeMid_eq_cum
#print axioms Prorate.chargeLast_eq_cum
#print axioms Prorate.chargeLast_start
#print axioms Prorate.chargeLast_mono
#print axioms Prorate.kernel_parts_total
#print axioms Prorate.kernel_parts_nonneg
#print axioms Documents.control_agrees
#print axioms Documents.control_agrees_through
#print axioms Documents.Step.document_unattached
#print axioms Documents.settle_posts_a_document_step
#print axioms Documents.settle_unattached
#print axioms Documents.Step.reverse_moves
#print axioms Documents.reverse_twice
#print axioms Documents.Step.markSent_changes_no_figure
#print axioms Documents.Reachable.unattached_zero
#print axioms Documents.Reachable.control_is_documents
#print axioms Documents.Step.writeOff_unattached
#print axioms Documents.writeOff_within_bounds
#print axioms Step.discard_keeps_books
#print axioms Step.discard_drafts
#print axioms Step.discard_unblocks_close
#print axioms Deductible.roundHA_near
#print axioms Deductible.roundHA_tie_pos
#print axioms Deductible.roundHA_tie_neg
#print axioms Deductible.roundHA_neg
#print axioms Deductible.roundHA_sign
#print axioms Deductible.roundHA_scale
#print axioms Deductible.near
#print axioms Deductible.tie_away_pos
#print axioms Deductible.tie_away_neg
#print axioms Deductible.sign
#print axioms Deductible.neg
#print axioms Deductible.of_sum
#print axioms Deductible.of_perm
#print axioms Deductible.append
#print axioms Deductible.split_percent
#print axioms Deductible.per_account_differs
#print axioms Deductible.per_account_differs_mixed
#print axioms Deductible.tie_example
#print axioms Deductible.scale_books
#print axioms Deductible.scale_percents
#print axioms law_debits_equal_credits
#print axioms law_accounting_equation
#print axioms law_trial_balance
#print axioms law_net_income_articulates
#print axioms law_cash_flow_is_change_in_cash
#print axioms law_acceptance_is_arithmetic
#print axioms law_accepted_entry_nets_to_zero
#print axioms law_movements_partition_the_net
#print axioms law_reversal_accepted_iff
#print axioms law_reversal_cancels
#print axioms law_normal_side
#print axioms law_trial_balance_is_complete
#print axioms law_period_statements_add_up
#print axioms law_invariant_holds
#print axioms law_posted_is_forever
#print axioms law_closed_periods_frozen
#print axioms law_record_changes_no_figure
#print axioms law_closing_entry_zeroes
#print axioms law_allocation_sums_to_the_whole
#print axioms law_member_run_telescopes
#print axioms law_cumulative_close_hands_out_its_net
#print axioms law_bounded_drift
#print axioms law_capital_unmoved_by_close
#print axioms law_reversal_is_the_exact_opposite
#print axioms law_proration_parts_sum_to_the_total
#print axioms law_proration_part_is_near
#print axioms law_proration_charge_never_falls
#print axioms law_control_account_is_its_documents
#print axioms law_send_changes_no_figure
#print axioms law_settlement_is_a_document_step
#print axioms law_write_off_within_bounds
#print axioms law_discard_moves_no_figure
#print axioms law_deductible_rounds_once
+2 -1
View File
@@ -6,7 +6,8 @@ import Bookspec
The laws live once, in bookspec's Lean (`bookspec/lean/Bookspec/`, namespace
`Bookspec`), and this project requires that package (D-69). This module is
the local target `lake build` builds: importing it builds and checks every
law, and `Audit.lean` prints their axioms.
law, and `just prove` prints their axioms with bookspec's own
`lean/Audit.lean` (from `.lake/packages/bookspec`; no copy here).
A law that changes is edited in bookspec, and this project moves its pin
(`lakefile.toml`, `lake-manifest.json`) to bookspec's new rev — the same rev
+2 -2
View File
@@ -5,10 +5,10 @@
"type": "git",
"subDir": "lean",
"scope": "",
"rev": "51375ecd529b3189af7f6316b0347d4ec6134cf1",
"rev": "00b7c541d784696961a760f0486e2fe7a5e7c003",
"name": "bookspec",
"manifestFile": "lake-manifest.json",
"inputRev": "51375ecd529b3189af7f6316b0347d4ec6134cf1",
"inputRev": "00b7c541d784696961a760f0486e2fe7a5e7c003",
"inherited": false,
"configFile": "lakefile.toml"}],
"name": "wanderbooks",
+1 -1
View File
@@ -9,7 +9,7 @@ packagesDir = ".lake/packages"
[[require]]
name = "bookspec"
git = "https://git.swaits.com/swaits/bookspec"
rev = "51375ecd529b3189af7f6316b0347d4ec6134cf1"
rev = "00b7c541d784696961a760f0486e2fe7a5e7c003"
subDir = "lean"
[[lean_lib]]