From 8dec2900ebe4b58c9b5cedff8dd76ae0e7b26408 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 20:13:40 -0700 Subject: [PATCH 01/26] fix(prove): audit bookspec's own theorem list, not a copy just prove audited verify/lean/Audit.lean, a copy of bookspec's list made when the laws moved there (L-F2). The laws then grew in bookspec (the FX law, the rounding primitive, the executable model's soundness and completeness, the empty close) and the copy did not: it audited 151 theorems of the 177 bookspec states, so 26 were proved but never checked for axioms on this side. Bookspec's CI audits them, so no theorem is known to rest on more than Lean's three; but the laws live once (D-69), and so must their list. just prove now runs bookspec's lean/Audit.lean from the pinned package, and the copy is gone: 177 theorems, standard axioms only. A unit's #print axioms line now goes in its bookspec branch with its theorem. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 4 +- docs/proofs/README.md | 11 ++- docs/verification.md | 7 +- justfile | 4 +- verify/lean/Audit.lean | 159 ----------------------------------- verify/lean/Wanderbooks.lean | 3 +- 6 files changed, 19 insertions(+), 169 deletions(-) delete mode 100644 verify/lean/Audit.lean diff --git a/AGENTS.md b/AGENTS.md index 22372b80..6ff2584d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 diff --git a/docs/proofs/README.md b/docs/proofs/README.md index 43f4700c..031f5bda 100644 --- a/docs/proofs/README.md +++ b/docs/proofs/README.md @@ -19,10 +19,13 @@ 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. diff --git a/docs/verification.md b/docs/verification.md index 6050cf87..715ff6b5 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -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/.rs`. A unit writes its proof note in `docs/proofs/.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 diff --git a/justfile b/justfile index 013171fb..845907e9 100644 --- a/justfile +++ b/justfile @@ -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 diff --git a/verify/lean/Audit.lean b/verify/lean/Audit.lean deleted file mode 100644 index 75ca3a4d..00000000 --- a/verify/lean/Audit.lean +++ /dev/null @@ -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 diff --git a/verify/lean/Wanderbooks.lean b/verify/lean/Wanderbooks.lean index 849d0e9e..a01031e1 100644 --- a/verify/lean/Wanderbooks.lean +++ b/verify/lean/Wanderbooks.lean @@ -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 From 71df823080876815135d963211d1db9acab72659 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 20:15:30 -0700 Subject: [PATCH 02/26] docs(plan): X-H1 in five slices, one after another Every slice adds to the same four files (the schema, its derivation, the Lean runner and the adapter), so they cannot run in parallel; split by what the schema must learn, A/R and A/P reading first (the most rules for one new event and two queries). Co-Authored-By: Claude Opus 5.5 --- plan/p14-bookspec.md | 1 + 1 file changed, 1 insertion(+) diff --git a/plan/p14-bookspec.md b/plan/p14-bookspec.md index e66c2ba1..bf2e8169 100644 --- a/plan/p14-bookspec.md +++ b/plan/p14-bookspec.md @@ -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). 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 | From 23e52de969c49685c11687b64c4d12c4846b456d Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 20:47:46 -0700 Subject: [PATCH 03/26] test(core): the adapter runs payments, aging and due dates The bookspec adapter learns the three things X-H1a's examples ask: a `payment` event (Store::receive_payment for an invoice, pay_bill for a bill, a payment dated before its document refused as `payment_before_document` from LedgerError::PaymentBeforeDocument, BS-arap-9); `terms` on a bill or invoice (the document is created with the engine's own Terms, its due date from Terms::due_date, and the engine must print the example's spelling back as written, BS-arap-3); and the `aging` and `document_dates` queries, read from Ledger::{ar_aging, ap_aging} and the stored document's due date and Terms::discount_by. Nothing of aging or terms is recomputed in the test. An example for an option wanderbooks did not pick (`under`, checked against PICKS) is read and not run, in the loader tests as in the runner, which reports it skipped; the 71 others pass: wanderbooks agrees with every example for the options it picks (BS-arap-7 due-today-is-current, BS-arap-8 as-of-the-day, BS-arap-9 refuse-a-payment-before-its-document). Run against bookspec branch x-h1a by patching the dependency; the pin does not move here. Claims for B-18 and B-39 name the new examples. Co-Authored-By: Claude Sonnet 5.5 --- crates/ledger-core/tests/bookspec/check.rs | 4 + crates/ledger-core/tests/bookspec/common.rs | 1 + crates/ledger-core/tests/bookspec/engine.rs | 19 ++++ crates/ledger-core/tests/bookspec/events.rs | 101 +++++++++++++++++- crates/ledger-core/tests/bookspec/examples.rs | 55 ++++++++++ crates/ledger-core/tests/bookspec/main.rs | 15 +-- .../tests/bookspec/queries/documents.rs | 98 +++++++++++++++++ .../ledger-core/tests/bookspec/queries/mod.rs | 3 + docs/spec/claims/arap.md | 16 ++- 9 files changed, 299 insertions(+), 13 deletions(-) create mode 100644 crates/ledger-core/tests/bookspec/queries/documents.rs diff --git a/crates/ledger-core/tests/bookspec/check.rs b/crates/ledger-core/tests/bookspec/check.rs index 9e0f6d83..194088fe 100644 --- a/crates/ledger-core/tests/bookspec/check.rs +++ b/crates/ledger-core/tests/bookspec/check.rs @@ -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() diff --git a/crates/ledger-core/tests/bookspec/common.rs b/crates/ledger-core/tests/bookspec/common.rs index dc57f41e..5befdcfc 100644 --- a/crates/ledger-core/tests/bookspec/common.rs +++ b/crates/ledger-core/tests/bookspec/common.rs @@ -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", diff --git a/crates/ledger-core/tests/bookspec/engine.rs b/crates/ledger-core/tests/bookspec/engine.rs index 636266a2..f9a4e9f3 100644 --- a/crates/ledger-core/tests/bookspec/engine.rs +++ b/crates/ledger-core/tests/bookspec/engine.rs @@ -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 { + 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/.md` as `**Pick (BS--):**`. diff --git a/crates/ledger-core/tests/bookspec/events.rs b/crates/ledger-core/tests/bookspec/events.rs index 96f478eb..4153c2e5 100644 --- a/crates/ledger-core/tests/bookspec/events.rs +++ b/crates/ledger-core/tests/bookspec/events.rs @@ -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::>()[..] { [(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,47 @@ 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`, except for a + /// date the parties agreed ("Due 2026-11-15"), which that call leaves to + /// its caller (the engine's contract: the caller passes the agreed date, + /// which the terms' canonical text carries). The example's spelling is + /// the canonical one, so the engine must print it back as written. + /// 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) { + 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 = match parsed.kind() { + TermsKind::Custom => { + let agreed = text.strip_prefix("Due ").unwrap_or_else(|| { + panic!("{what}: custom terms {text:?} carry their date after \"Due \"") + }); + crate::date(agreed, what) + } + _ => 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 +409,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 +434,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 +493,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); diff --git a/crates/ledger-core/tests/bookspec/examples.rs b/crates/ledger-core/tests/bookspec/examples.rs index 70c868a0..727aae7d 100644 --- a/crates/ledger-core/tests/bookspec/examples.rs +++ b/crates/ledger-core/tests/bookspec/examples.rs @@ -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 = 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,21 @@ 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() + ); + assert_eq!( + skipped.len(), + 3, + "the three unpicked-option examples: {skipped:?}" + ); } diff --git a/crates/ledger-core/tests/bookspec/main.rs b/crates/ledger-core/tests/bookspec/main.rs index 69fca17e..e0f9c456 100644 --- a/crates/ledger-core/tests/bookspec/main.rs +++ b/crates/ledger-core/tests/bookspec/main.rs @@ -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, + TermsKind, 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::*; diff --git a/crates/ledger-core/tests/bookspec/queries/documents.rs b/crates/ledger-core/tests/bookspec/queries/documents.rs new file mode 100644 index 00000000..ff40d161 --- /dev/null +++ b/crates/ledger-core/tests/bookspec/queries/documents.rs @@ -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 { + 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 { + 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) { + 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 = 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 + ); + } +} diff --git a/crates/ledger-core/tests/bookspec/queries/mod.rs b/crates/ledger-core/tests/bookspec/queries/mod.rs index a49400b2..a1e6a4aa 100644 --- a/crates/ledger-core/tests/bookspec/queries/mod.rs +++ b/crates/ledger-core/tests/bookspec/queries/mod.rs @@ -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), diff --git a/docs/spec/claims/arap.md b/docs/spec/claims/arap.md index 11ec2997..cc9ee638 100644 --- a/docs/spec/claims/arap.md +++ b/docs/spec/claims/arap.md @@ -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 them (`under`) 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` @@ -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`, From 67bf2280a812fa10af678120a18175597f0922f2 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 21:15:16 -0700 Subject: [PATCH 04/26] test(core): bridge the small cash-flow and bounds helpers The traceability gate asks every public kernel function for a bridge property. Three amount-generic helpers had none: take, entry_movements and flows_of (the statement of cash flows' split) and running_bounds and bounds_kept (a document's position against its total). The properties compare the i64 instantiation Kani proves with the Decimal one the engine runs, on random inputs, so law 10 and law 34 hold at both types. Co-Authored-By: DeepSeek V4.1 Flash --- .../tests/kernel_bridge/control.rs | 42 +++++++- .../tests/kernel_bridge/entries.rs | 98 +++++++++++++++++++ .../ledger-core/tests/kernel_bridge/main.rs | 1 + 3 files changed, 139 insertions(+), 2 deletions(-) create mode 100644 crates/ledger-core/tests/kernel_bridge/entries.rs diff --git a/crates/ledger-core/tests/kernel_bridge/control.rs b/crates/ledger-core/tests/kernel_bridge/control.rs index 537679dc..25566dd9 100644 --- a/crates/ledger-core/tests/kernel_bridge/control.rs +++ b/crates/ledger-core/tests/kernel_bridge/control.rs @@ -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) + ); + } +} diff --git a/crates/ledger-core/tests/kernel_bridge/entries.rs b/crates/ledger-core/tests/kernel_bridge/entries.rs new file mode 100644 index 00000000..08d6c671 --- /dev/null +++ b/crates/ledger-core/tests/kernel_bridge/entries.rs @@ -0,0 +1,98 @@ +//! 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 { + prop_oneof![ + Just(Flow::Cash), + Just(Flow::Operating), + Just(Flow::Investing), + Just(Flow::Financing), + ] +} + +fn arb_side() -> impl Strategy { + prop_oneof![Just(Side::Debit), Just(Side::Credit)] +} + +fn arb_flow_lines() -> impl Strategy> { + 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() +} + +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 = pairs.iter().map(|&(s, _)| s).collect(); + let posted: Vec = 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::>(), + &posted.iter().map(|&c| dec(c)).collect::>(), + &mut d, + ); + prop_assert_eq!(ri, rd); + prop_assert_eq!(i.into_iter().map(dec).collect::>(), 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)) + ); + } +} diff --git a/crates/ledger-core/tests/kernel_bridge/main.rs b/crates/ledger-core/tests/kernel_bridge/main.rs index f8a4ea80..e91c8b54 100644 --- a/crates/ledger-core/tests/kernel_bridge/main.rs +++ b/crates/ledger-core/tests/kernel_bridge/main.rs @@ -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; From 2ef945ae3f8054fe37e641eee58b63dbea0fa34a Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 21:15:16 -0700 Subject: [PATCH 05/26] docs(claims): name only live records and real items The traceability gate follows every backticked name a claimed rule's Enforced and Checked paragraphs carry, so the claims now name what exists: - B-22 claimed `partly` while stating the engine enforces nothing; it is `no` now, with the reason (the policy is the books' own AGENTS.md). - WB-prepaid-2 is `partly`: replay of old schedules is implemented and tested, while moving new monthly-even schedules to the currency's minor unit is K-U5 and not landed. - The stale names: Vendor1099Report::untagged is untagged_payments, Asset::set_entry is Ledger::set_asset_acquisition, shares::share_target is shares::target, tag_in_use is check_asset_tag's refusal, Step.extends and Step.record are the audited Steps.extends and Step.record_changes_no_figure, and two asset tests are named as they exist (a_journaled_tag_taken_by_another_asset_is_refused_on_open, legacy_tax_basis_set_lines_replay_to_todays_figures). - BS-format-1, BS-ledger-12 and BS-ledger-13 are retired; they are marked `retired bookspec:` so a live `bookspec:` id means a live record. - B-44 and B-45 are wholly product rules: their enforcement and checks are the WB rules they point at. - WB-ledger-3, -4 and -6 had one `Enforced and checked` marker; each now carries `Enforced` and `Checked` separately. Co-Authored-By: DeepSeek V4.1 Flash --- docs/spec/claims/1099.md | 2 +- docs/spec/claims/arap.md | 5 +++-- docs/spec/claims/asset.md | 10 +++++----- docs/spec/claims/entry.md | 2 +- docs/spec/claims/format.md | 2 +- docs/spec/claims/ledger.md | 36 +++++++++++++++++++++++++++-------- docs/spec/claims/prepaid.md | 8 ++++++++ docs/spec/claims/statement.md | 5 +++++ 8 files changed, 52 insertions(+), 18 deletions(-) diff --git a/docs/spec/claims/1099.md b/docs/spec/claims/1099.md index e7ea2c5a..c9bd6db5 100644 --- a/docs/spec/claims/1099.md +++ b/docs/spec/claims/1099.md @@ -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::Vendor1099Report::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). diff --git a/docs/spec/claims/arap.md b/docs/spec/claims/arap.md index 11ec2997..974e279c 100644 --- a/docs/spec/claims/arap.md +++ b/docs/spec/claims/arap.md @@ -311,8 +311,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 diff --git a/docs/spec/claims/asset.md b/docs/spec/claims/asset.md index 73f6ee4c..8c6cb606 100644 --- a/docs/spec/claims/asset.md +++ b/docs/spec/claims/asset.md @@ -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 diff --git a/docs/spec/claims/entry.md b/docs/spec/claims/entry.md index 1a065f0e..080f976e 100644 --- a/docs/spec/claims/entry.md +++ b/docs/spec/claims/entry.md @@ -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`. diff --git a/docs/spec/claims/format.md b/docs/spec/claims/format.md index 89956646..5d4f293e 100644 --- a/docs/spec/claims/format.md +++ b/docs/spec/claims/format.md @@ -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 diff --git a/docs/spec/claims/ledger.md b/docs/spec/claims/ledger.md index 1e957010..9b4c3ea9 100644 --- a/docs/spec/claims/ledger.md +++ b/docs/spec/claims/ledger.md @@ -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 @@ -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. diff --git a/docs/spec/claims/prepaid.md b/docs/spec/claims/prepaid.md index c41c9010..20ba1534 100644 --- a/docs/spec/claims/prepaid.md +++ b/docs/spec/claims/prepaid.md @@ -59,6 +59,14 @@ 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.) +**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`. +**Checked:** `defect9_legacy_schedules_stay_monthly_even`, +`prop_monthly_even_plan_is_unchanged`. + **Enforced:** `schedules` replay (`amortization_plan`), `Ledger::schedule_month_hold`. **Checked:** `defect9_legacy_schedules_stay_monthly_even`, diff --git a/docs/spec/claims/statement.md b/docs/spec/claims/statement.md index 85000e1e..ba360b74 100644 --- a/docs/spec/claims/statement.md +++ b/docs/spec/claims/statement.md @@ -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`. From 5703657957e53f37da53b9f2afb6fdc9ed34ec7d Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 21:15:16 -0700 Subject: [PATCH 06/26] docs(proofs): number each kernel-sweep harness's law The kernel sweep's proof notes described each harness's law in prose. The traceability gate needs the number to check it against a row of bookspec's spec/laws.md, so each note now carries a machine-readable Harness | Law table: fx_booked's harnesses law 41, round_step's law 40, and total's law 4 (the engine-bound law whose Lean row says why it has no theorem). The prose tables and times stay as they were. Co-Authored-By: DeepSeek V4.1 Flash --- docs/proofs/k-u1.md | 10 ++++++++++ docs/proofs/k-u2.md | 15 +++++++++++++++ docs/proofs/k-u4.md | 12 ++++++++++++ 3 files changed, 37 insertions(+) diff --git a/docs/proofs/k-u1.md b/docs/proofs/k-u1.md index 62c2dcdc..fae036f9 100644 --- a/docs/proofs/k-u1.md +++ b/docs/proofs/k-u1.md @@ -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** diff --git a/docs/proofs/k-u2.md b/docs/proofs/k-u2.md index 2065584f..28f59568 100644 --- a/docs/proofs/k-u2.md +++ b/docs/proofs/k-u2.md @@ -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 diff --git a/docs/proofs/k-u4.md b/docs/proofs/k-u4.md index 69292181..0f10b3e6 100644 --- a/docs/proofs/k-u4.md +++ b/docs/proofs/k-u4.md @@ -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 From 0a902901606173ed4da57fa13782a06c6fbf152f Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 21:15:16 -0700 Subject: [PATCH 07/26] test(core): the traceability gate A claim is worth what backs it. The new bookspec test module reads every claimed rule's Enforced and Checked paragraphs and follows each backticked name to a real Rust item, test, Kani harness, Lean theorem (checked against bookspec's embedded Audit.lean), path, rule id, or an explicitly classified value; it requires a live record behind every bookspec id and a unique WB id. It then walks every pub fn in the kernel and requires a harness that calls it, a bridge property that calls it, and a harness whose numbered law is a row of spec/laws.md; the wrappers and enum maps with no independent proof are named in a pinned exceptions list with why. Finally it checks every law row that cites a claimed rule names audited theorems or says why not. Floors on sections, tokens and kernel functions, and a made-up name that must fail, keep the gate from passing vacuously. Co-Authored-By: DeepSeek V4.1 Flash --- crates/ledger-core/tests/bookspec/main.rs | 1 + .../tests/bookspec/traceability.rs | 1926 +++++++++++++++++ 2 files changed, 1927 insertions(+) create mode 100644 crates/ledger-core/tests/bookspec/traceability.rs diff --git a/crates/ledger-core/tests/bookspec/main.rs b/crates/ledger-core/tests/bookspec/main.rs index 69fca17e..0ab321ef 100644 --- a/crates/ledger-core/tests/bookspec/main.rs +++ b/crates/ledger-core/tests/bookspec/main.rs @@ -95,3 +95,4 @@ mod rules_md; mod run; mod source_refs; mod sources; +mod traceability; diff --git a/crates/ledger-core/tests/bookspec/traceability.rs b/crates/ledger-core/tests/bookspec/traceability.rs new file mode 100644 index 00000000..b2b716cf --- /dev/null +++ b/crates/ledger-core/tests/bookspec/traceability.rs @@ -0,0 +1,1926 @@ +//! The traceability gate (P14 unit X-J). +//! +//! A claim is worth what backs it. This gate reads every section of +//! `docs/spec/claims/*.md` whose claim is `yes` or `partly` and follows +//! each backticked name in its **Enforced** and **Checked** paragraphs to +//! something real: +//! +//! The scanner below mirrors the grammar it reads (a `use` line, a +//! `proptest!` block, a markdown field), so its nested `if let` blocks are +//! kept for the shape they name rather than collapsed into one condition. +#![allow(clippy::collapsible_if)] +//! +//! - a Rust item defined under `crates/*/src` (a `fn`, method, type, +//! enum variant, field, `const`, `static`, module, trait or macro); +//! - a test function under `crates/*/tests` (or a `#[test]` / proptest +//! in `crates/*/src`), a fuzz target, or a `#[kani::proof]` harness; +//! - a Lean theorem in bookspec's `Audit.lean`; +//! - a path that exists; +//! - a bookspec rule or a wanderbooks product rule that exists. +//! +//! Tokens that are plainly values (a quoted option word, a setting value, +//! a journal event, a tool name, an illustrative amount) are classified by +//! narrow, explicit rules below and counted, so the gate says how much it +//! actually resolved. Every `**bookspec:**` id must be a live record (a +//! retired one is written `**retired bookspec:**`); every `WB-` id is +//! unique. +//! +//! It also checks every `pub fn` in `crates/ledger-core/src/kernel/*.rs`: +//! a Kani harness calls it, a bridge property in `tests/kernel_bridge/` +//! calls it, and one of its harnesses carries a numbered law that is a +//! row of bookspec's `spec/laws.md`. The functions that are wrappers or +//! enum maps with no independent harness, bridge or law are named in +//! [`EXCEPTIONS`], with what each lacks and why; its length is pinned so +//! the list changes only on purpose. +//! +//! Finally, every law row of `spec/laws.md` that cites a rule wanderbooks +//! claims names Lean theorems that are all audited, or says `none —` with +//! a reason. + +use crate::*; + +/// The classes a backticked token can resolve to. Reported by count. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum Class { + RustItem, + Test, + FuzzTarget, + KaniHarness, + LeanTheorem, + Path, + Crate, + RuleId, + ProductSurface, + StringValue, + OptionValue, + NonName, +} + +impl Class { + fn name(self) -> &'static str { + match self { + Class::RustItem => "rust item", + Class::Test => "test", + Class::FuzzTarget => "fuzz target", + Class::KaniHarness => "kani harness", + Class::LeanTheorem => "lean theorem", + Class::Path => "path", + Class::Crate => "crate", + Class::RuleId => "rule id", + Class::ProductSurface => "product surface", + Class::StringValue => "string value", + Class::OptionValue => "option/example value", + Class::NonName => "plainly not a name", + } + } +} + +const CLAIMS_FLOOR: usize = 120; +const TOKENS_FLOOR: usize = 1700; +const KERNEL_FLOOR: usize = 50; +const PROPTEST: [char; 9] = ['p', 'r', 'o', 'p', 't', 'e', 's', 't', '!']; + +fn repo_root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../..") +} + +fn read(path: &Path) -> String { + std::fs::read_to_string(path).unwrap_or_else(|error| panic!("{}: {error}", path.display())) +} + +fn walk(dir: &Path, ext: &str, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for entry in entries.flatten() { + let path = entry.path(); + let name = entry.file_name(); + let name = name.to_string_lossy(); + if name == "target" || name == ".git" { + continue; + } + if path.is_dir() { + walk(&path, ext, out); + } else if path.extension().is_some_and(|e| e == ext) { + out.push(path); + } + } +} + +/// The source with comments and string/char literals blanked, so a word in +/// a comment or a string is never mistaken for a definition. +fn strip_code(text: &str) -> String { + let chars: Vec = text.chars().collect(); + let mut out = String::with_capacity(text.len()); + let mut i = 0; + while i < chars.len() { + if chars[i] == '/' && chars.get(i + 1) == Some(&'/') { + while i < chars.len() && chars[i] != '\n' { + i += 1; + } + } else if chars[i] == '/' && chars.get(i + 1) == Some(&'*') { + i += 2; + let mut depth = 1usize; + while i < chars.len() && depth > 0 { + if chars[i] == '/' && chars.get(i + 1) == Some(&'*') { + depth += 1; + i += 2; + } else if chars[i] == '*' && chars.get(i + 1) == Some(&'/') { + depth -= 1; + i += 2; + } else { + i += 1; + } + } + } else if chars[i] == '"' { + i += 1; + while i < chars.len() { + if chars[i] == '\\' { + i += 2; + } else if chars[i] == '"' { + i += 1; + break; + } else { + i += 1; + } + } + } else if chars[i] == '\'' { + // A char literal or a lifetime; only skip a literal with a + // closing quote in the next few characters. + let close = chars + .iter() + .enumerate() + .skip(i + 1) + .take(4) + .find(|(_, c)| **c == '\''); + if let Some((j, _)) = close { + i = j + 1; + } else { + out.push(chars[i]); + i += 1; + } + } else { + out.push(chars[i]); + i += 1; + } + } + out +} + +/// The contents of every simple string literal. +fn literals(text: &str) -> Vec { + let chars: Vec = text.chars().collect(); + let mut out = Vec::new(); + let mut i = 0; + while i < chars.len() { + if chars[i] == '"' { + i += 1; + let mut s = String::new(); + while i < chars.len() { + if chars[i] == '\\' { + if let Some(c) = chars.get(i + 1) { + s.push(*c); + } + i += 2; + } else if chars[i] == '"' { + i += 1; + break; + } else { + s.push(chars[i]); + i += 1; + } + } + out.push(s); + } else { + i += 1; + } + } + out +} + +fn is_word_char(c: char) -> bool { + c.is_ascii_alphanumeric() || c == '_' +} + +fn word_at(chars: &[char], i: usize) -> Option<(String, usize)> { + if i >= chars.len() || !(chars[i].is_ascii_alphabetic() || chars[i] == '_') { + return None; + } + let mut j = i; + while j < chars.len() && is_word_char(chars[j]) { + j += 1; + } + Some((chars[i..j].iter().collect(), j)) +} + +fn skip_space(chars: &[char], mut i: usize) -> usize { + while i < chars.len() && chars[i].is_whitespace() { + i += 1; + } + i +} + +fn matching_brace(chars: &[char], open: usize, pair: (char, char)) -> Option { + let mut depth = 0usize; + let mut i = open; + while i < chars.len() { + if chars[i] == pair.0 { + depth += 1; + } else if chars[i] == pair.1 { + depth -= 1; + if depth == 0 { + return Some(i); + } + } + i += 1; + } + None +} + +/// `(start, end_inclusive, type name)` of every `impl` block. +fn impl_ranges(code: &str) -> Vec<(usize, usize, String)> { + let chars: Vec = code.chars().collect(); + let mut out = Vec::new(); + let mut i = 0; + while i < chars.len() { + if !(chars[i].is_ascii_alphabetic() || chars[i] == '_') { + i += 1; + continue; + } + let Some((word, end)) = word_at(&chars, i) else { + i += 1; + continue; + }; + if word != "impl" { + i = end; + continue; + } + // The type is the last identifier before the opening brace, and + // after `for` when it is a trait impl. + let mut j = end; + while j < chars.len() && chars[j] != '{' { + j += 1; + } + if j >= chars.len() { + break; + } + let header: String = chars[end..j].iter().collect(); + let segment = match header.rsplit_once(" for ") { + Some((_, after)) => after, + None => &header, + }; + let mut last = String::new(); + let mut k = 0; + while k < segment.len() { + let rest: Vec = segment[k..].chars().collect(); + match word_at(&rest, 0) { + Some((w, used)) => { + last = w; + k += segment[k..] + .chars() + .take(used) + .map(char::len_utf8) + .sum::(); + } + None => k += segment[k..].chars().next().map(char::len_utf8).unwrap_or(1), + } + } + if let Some(close) = matching_brace(&chars, j, ('{', '}')) { + let start = chars[..i].iter().map(|c| c.len_utf8()).sum::(); + let end = chars[..=close].iter().map(|c| c.len_utf8()).sum::(); + out.push((start, end, last)); + } + i = end; + } + out +} + +/// Every top-level item of a brace block, split on commas. +fn top_items(body: &str) -> Vec { + let chars: Vec = body.chars().collect(); + let mut out = Vec::new(); + let mut cur = String::new(); + let mut depth = 0i32; + for &c in &chars { + match c { + '(' | '[' | '{' | '<' => { + depth += 1; + cur.push(c); + } + ')' | ']' | '}' | '>' => { + depth -= 1; + cur.push(c); + } + ',' if depth == 0 => { + out.push(std::mem::take(&mut cur)); + } + _ => cur.push(c), + } + } + if !cur.trim().is_empty() { + out.push(cur); + } + out +} + +/// The leading identifier of an item, after any `pub(...)`. +fn leading_ident(item: &str) -> Option { + let chars: Vec = item.chars().collect(); + let mut i = 0; + loop { + i = skip_space(&chars, i); + if chars.get(i) == Some(&'#') { + let mut j = i + 1; + if chars.get(j) == Some(&'!') { + j += 1; + } + if chars.get(j) == Some(&'[') { + i = matching_brace(&chars, j, ('[', ']'))? + 1; + continue; + } + return None; + } + break; + } + let (first, end) = word_at(&chars, i)?; + if first == "pub" { + i = end; + if chars.get(i) == Some(&'(') { + i = matching_brace(&chars, i, ('(', ')'))? + 1; + } + i = skip_space(&chars, i); + } + word_at(&chars, i).map(|(w, _)| w) +} + +fn find_named_item(code: &str, keyword: &str, name: &str) -> Option { + let needle = format!("{keyword} {name}"); + let mut at = 0; + while let Some(rel) = code[at..].find(&needle) { + let pos = at + rel; + let after = pos + needle.len(); + let boundary = code[after..] + .chars() + .next() + .is_none_or(|c| !is_word_char(c)); + let before_ok = pos == 0 || !code[..pos].chars().next_back().is_some_and(is_word_char); + if boundary && before_ok { + return Some(pos); + } + at = pos + 1; + } + None +} + +fn enum_variants(code: &str, name: &str) -> Vec { + let mut out = Vec::new(); + let chars: Vec = code.chars().collect(); + let Some(at) = find_named_item(code, "enum", name) else { + return out; + }; + let mut i = code[..at].chars().count(); + while i < chars.len() && chars[i] != '{' { + i += 1; + } + let Some(close) = matching_brace(&chars, i, ('{', '}')) else { + return out; + }; + let body: String = chars[i + 1..close].iter().collect(); + for item in top_items(&body) { + if let Some(v) = leading_ident(&item) { + if v.chars().next().is_some_and(|c| c.is_ascii_uppercase()) { + out.push(v); + } + } + } + out +} + +fn struct_fields(code: &str, name: &str) -> Vec { + let mut out = Vec::new(); + let chars: Vec = code.chars().collect(); + let Some(at) = find_named_item(code, "struct", name) else { + return out; + }; + let mut i = code[..at].chars().count(); + while i < chars.len() && chars[i] != '{' { + i += 1; + } + let Some(close) = matching_brace(&chars, i, ('{', '}')) else { + return out; + }; + let body: String = chars[i + 1..close].iter().collect(); + for item in top_items(&body) { + let Some(v) = leading_ident(&item) else { + continue; + }; + let after = item.find(&v).map(|p| &item[p + v.len()..]).unwrap_or(""); + if after.trim_start().starts_with(':') { + out.push(v); + } + } + out +} + +/// Enum variants and struct fields in `code`, for definitions outside the +/// crate's `src` (an integration test's own model types). +fn collect_types(code: &str, items: &mut BTreeSet, bare: &mut BTreeSet) { + let chars: Vec = code.chars().collect(); + let mut i = 0; + while i < chars.len() { + if !(chars[i].is_ascii_alphabetic() || chars[i] == '_') { + i += 1; + continue; + } + let Some((word, end)) = word_at(&chars, i) else { + i += 1; + continue; + }; + if word == "enum" || word == "struct" { + let j = skip_space(&chars, end); + if let Some((name, _)) = word_at(&chars, j) { + let found = if word == "enum" { + enum_variants(code, &name) + } else { + struct_fields(code, &name) + }; + for item in found { + items.insert(item.clone()); + bare.insert(item); + } + } + } + i = end; + } +} + +/// The names a `use` statement imports. +fn collect_imports(code: &str, items: &mut BTreeSet) { + for line in code.lines() { + let line = line.trim_start(); + let Some(rest) = line.strip_prefix("use ") else { + continue; + }; + let decl = rest.split(';').next().unwrap_or(rest); + let mut word = String::new(); + for c in decl.chars().chain(std::iter::once(' ')) { + if c.is_ascii_alphanumeric() || c == '_' { + word.push(c); + } else { + if !word.is_empty() + && !matches!( + word.as_str(), + "use" | "crate" | "self" | "super" | "as" | "pub" + ) + { + items.insert(word.clone()); + } + word.clear(); + } + } + } +} + +#[derive(Default)] +struct Definitions { + /// Every Rust item name, bare or `Type::method`. + items: BTreeSet, + bare: BTreeSet, + /// Test and property names under `crates/*/tests`, `#[test]` in src, + /// and proptest functions. + tests: BTreeSet, + /// `#[kani::proof]` functions under `src/proofs/`. + harnesses: BTreeSet, + /// Fuzz targets under `fuzz/fuzz_targets/`. + fuzz: BTreeSet, + /// Proof source file stems. + proof_files: BTreeSet, + /// Every string literal in `crates/*` source. + literals: BTreeSet, + /// All crate source text, for product-surface names. + surface: String, + /// Rules by id and whether the record is retired. + rules: BTreeMap, + /// Product rule ids (`WB-...`) and their count. + product_rules: BTreeMap, + /// Bookspec option names. + options: BTreeSet, + /// Bookspec example file names. + examples: Vec, + /// Bookspec Lean files, path under `lean/`. + lean_files: BTreeSet, +} + +fn collect_function_bodies(code: &str, out: &mut Vec<(String, String)>) { + let chars: Vec = code.chars().collect(); + let mut i = 0; + while i < chars.len() { + if !(chars[i].is_ascii_alphabetic() || chars[i] == '_') { + i += 1; + continue; + } + let Some((word, end)) = word_at(&chars, i) else { + i += 1; + continue; + }; + if word != "fn" { + i = end; + continue; + } + let j = skip_space(&chars, end); + let Some((name, name_end)) = word_at(&chars, j) else { + i = end; + continue; + }; + let mut k = name_end; + // Skip the parameter list, then find the body. + if chars.get(k) == Some(&'<') { + if let Some(gt) = matching_brace(&chars, k, ('<', '>')) { + k = gt + 1; + } + } + k = skip_space(&chars, k); + if chars.get(k) == Some(&'(') { + if let Some(close) = matching_brace(&chars, k, ('(', ')')) { + k = close + 1; + } + } + while k < chars.len() && chars[k] != '{' && chars[k] != ';' { + k += 1; + } + if chars.get(k) == Some(&'{') { + if let Some(close) = matching_brace(&chars, k, ('{', '}')) { + let body: String = chars[k + 1..close].iter().collect(); + out.push((name, body)); + } + } + i = end; + } +} + +fn build_definitions(root: &Path) -> Definitions { + let mut defs = Definitions::default(); + + let mut src_files = Vec::new(); + for entry in std::fs::read_dir(root.join("crates")).expect("crates") { + let crate_dir = entry.expect("a crate").path(); + let src = crate_dir.join("src"); + if src.is_dir() { + walk(&src, "rs", &mut src_files); + } + } + src_files.sort(); + let mut enums = Vec::new(); + let mut structs = Vec::new(); + for path in &src_files { + let text = read(path); + let code = strip_code(&text); + defs.surface.push_str(&text); + defs.surface.push('\n'); + for literal in literals(&text) { + defs.literals.insert(literal); + } + collect_imports(&code, &mut defs.items); + // Keywords and names. + let chars: Vec = code.chars().collect(); + let mut i = 0; + while i < chars.len() { + if !(chars[i].is_ascii_alphabetic() || chars[i] == '_') { + i += 1; + continue; + } + let Some((word, end)) = word_at(&chars, i) else { + i += 1; + continue; + }; + match word.as_str() { + "fn" | "struct" | "enum" | "union" | "trait" | "type" | "mod" | "const" + | "static" => { + let j = skip_space(&chars, end); + if let Some((name, _)) = word_at(&chars, j) { + if word == "enum" { + enums.push((path.clone(), name.clone())); + } + if word == "struct" { + structs.push((path.clone(), name.clone())); + } + defs.items.insert(name.clone()); + defs.bare.insert(name); + } + } + "macro_rules" => { + let mut j = skip_space(&chars, end); + if chars.get(j) == Some(&'!') { + j = skip_space(&chars, j + 1); + if let Some((name, _)) = word_at(&chars, j) { + defs.items.insert(name.clone()); + defs.bare.insert(name); + } + } + } + _ => {} + } + i = end; + } + // Methods, qualified by their impl. + for (start, end, ty) in impl_ranges(&code) { + let block = &code[start..end]; + let mut fns = Vec::new(); + collect_pub_fns(block, &mut fns); + for (name, _) in fns { + let qualified = format!("{ty}::{name}"); + defs.items.insert(qualified); + defs.items.insert(name.clone()); + defs.bare.insert(name); + } + } + } + for (path, name) in enums { + let code = strip_code(&read(&path)); + for variant in enum_variants(&code, &name) { + defs.items.insert(variant.clone()); + defs.bare.insert(variant); + } + } + for (path, name) in structs { + let code = strip_code(&read(&path)); + for field in struct_fields(&code, &name) { + defs.items.insert(field.clone()); + defs.bare.insert(field); + } + } + + // Tests: every fn under `tests/`, and `#[test]`/proptest in src. + let mut test_files = Vec::new(); + for entry in std::fs::read_dir(root.join("crates")).expect("crates") { + let dir = entry.expect("a crate").path().join("tests"); + if dir.is_dir() { + walk(&dir, "rs", &mut test_files); + } + } + test_files.sort(); + for path in &test_files { + let code = strip_code(&read(path)); + collect_types(&code, &mut defs.items, &mut defs.bare); + collect_imports(&code, &mut defs.items); + let mut fns = Vec::new(); + collect_function_bodies(&code, &mut fns); + for (name, _) in fns { + defs.tests.insert(name); + } + } + for path in &src_files { + let text = read(path); + let code = strip_code(&text); + let chars: Vec = code.chars().collect(); + // `#[test]` functions. + for (name, _) in collect_bodies_with_attribute(&code, "#[test]") { + defs.tests.insert(name); + } + // Proptest blocks. + let mut i = 0; + while i < chars.len() { + if chars[i..].starts_with(&PROPTEST) { + if let Some(open) = code[i..].find('{') { + let at = i + open; + if let Some(close) = matching_brace(&chars, at, ('{', '}')) { + let block: String = chars[at + 1..close].iter().collect(); + let mut fns = Vec::new(); + collect_function_bodies(&block, &mut fns); + for (name, _) in fns { + defs.tests.insert(name); + } + i = close; + continue; + } + } + } + i += 1; + } + } + + // Kani harnesses and proof files. + let proofs = root.join("crates/ledger-core/src/proofs"); + let mut proof_files = Vec::new(); + walk(&proofs, "rs", &mut proof_files); + proof_files.sort(); + for path in &proof_files { + if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) { + defs.proof_files.insert(stem.to_string()); + } + let code = strip_code(&read(path)); + for (name, _) in collect_bodies_with_attribute(&code, "#[kani::proof]") { + defs.harnesses.insert(name); + } + } + + // Fuzz targets. + let fuzz = root.join("fuzz/fuzz_targets"); + let mut fuzz_files = Vec::new(); + walk(&fuzz, "rs", &mut fuzz_files); + for path in &fuzz_files { + let code = strip_code(&read(path)); + if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) { + defs.fuzz.insert(stem.to_string()); + } + let mut fns = Vec::new(); + collect_function_bodies(&code, &mut fns); + for (name, _) in fns { + defs.fuzz.insert(name); + } + } + + // Bookspec rules, options, examples and Lean files. + for record in bookspec_checker::records() { + defs.rules + .insert(record.id.to_string(), record.is_retired()); + for option in &record.options { + defs.options.insert(option.name.clone()); + } + } + for (name, _) in bookspec_checker::examples() { + defs.examples.push(name.replace(".toml", "")); + } + for (name, _) in bookspec_checker::lean_files() { + defs.lean_files.insert(name.to_string()); + } + + defs +} + +/// `pub fn` names in an impl block, with their offsets (unused offsets are +/// kept for a future stricter check). +fn collect_pub_fns(block: &str, out: &mut Vec<(String, usize)>) { + let chars: Vec = block.chars().collect(); + let mut i = 0; + while i < chars.len() { + if !(chars[i].is_ascii_alphabetic() || chars[i] == '_') { + i += 1; + continue; + } + let Some((word, end)) = word_at(&chars, i) else { + i += 1; + continue; + }; + if word != "pub" { + i = end; + continue; + } + let mut j = skip_space(&chars, end); + if chars.get(j) == Some(&'(') { + if let Some(close) = matching_brace(&chars, j, ('(', ')')) { + j = skip_space(&chars, close + 1); + } + } + if let Some((kw, kw_end)) = word_at(&chars, j) { + if kw == "fn" { + let k = skip_space(&chars, kw_end); + if let Some((name, _)) = word_at(&chars, k) { + out.push((name, i)); + } + } + } + i = end; + } +} + +/// Functions preceded (within the previous attribute block) by `attr`. +fn collect_bodies_with_attribute(code: &str, attr: &str) -> Vec<(String, String)> { + let mut out = Vec::new(); + let mut search = 0; + while let Some(at) = code[search..].find(attr) { + let start = search + at; + let after = start + attr.len(); + let tail = &code[after..]; + let Some(fn_at) = tail.find("fn ") else { + break; + }; + // Nothing but attributes/whitespace may sit between them. + let between = &tail[..fn_at]; + if between.contains('\n') { + let only_attrs = between.lines().all(|line| { + let line = line.trim(); + line.is_empty() + || line.starts_with("#[") + || line.starts_with("//") + || line.starts_with(']') + }); + if !only_attrs { + search = after; + continue; + } + } + let at = after + fn_at + 3; + let chars: Vec = code.chars().collect(); + let prefix_len = code[..at].chars().count(); + let j = skip_space(&chars, prefix_len); + let Some((name, _)) = word_at(&chars, j) else { + search = after; + continue; + }; + let mut k = j; + while k < chars.len() && chars[k] != '{' && chars[k] != ';' { + k += 1; + } + if chars.get(k) == Some(&'{') { + if let Some(close) = matching_brace(&chars, k, ('{', '}')) { + let body: String = chars[k + 1..close].iter().collect(); + out.push((name, body)); + } + } + search = after; + } + out +} + +/// Every `pub fn` in `crates/ledger-core/src/kernel/*.rs`, qualified by +/// its impl (`Type::method`). +fn kernel_functions(root: &Path) -> Vec<(String, String)> { + let mut files = Vec::new(); + walk( + &root.join("crates/ledger-core/src/kernel"), + "rs", + &mut files, + ); + files.sort(); + let mut out = Vec::new(); + for path in files { + let code = strip_code(&read(&path)); + let file = path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let impls = impl_ranges(&code); + let chars: Vec = code.chars().collect(); + let mut i = 0; + while i < chars.len() { + if !(chars[i].is_ascii_alphabetic() || chars[i] == '_') { + i += 1; + continue; + } + let Some((word, end)) = word_at(&chars, i) else { + i += 1; + continue; + }; + if word != "pub" { + i = end; + continue; + } + let j = skip_space(&chars, end); + if chars.get(j) == Some(&'(') { + // `pub(crate) fn` is not a `pub fn`. + i = end; + continue; + } + if let Some((kw, kw_end)) = word_at(&chars, j) { + if kw == "fn" { + let k = skip_space(&chars, kw_end); + if let Some((name, _)) = word_at(&chars, k) { + let offset = code[..i].chars().count(); + let ty = impls + .iter() + .find(|(start, end, _)| offset >= *start && offset < *end) + .map(|(_, _, ty)| ty.clone()); + let qualified = match ty { + Some(ty) => format!("{ty}::{name}"), + None => name, + }; + out.push((qualified, file.clone())); + } + } + } + i = end; + } + } + out +} + +/// True when `body` calls `name`, bare or qualified, including a method +/// call written `.name(`. +fn calls(body: &str, name: &str) -> bool { + if contains_call(body, &format!("{name}(")) { + return true; + } + let last = name.rsplit("::").next().unwrap_or(name); + contains_call(body, &format!("{last}(")) || contains_word(body, last) +} + +fn contains_word(body: &str, word: &str) -> bool { + let mut at = 0; + while let Some(rel) = body[at..].find(word) { + let pos = at + rel; + let before = body[..pos].chars().next_back(); + let after = body[pos + word.len()..].chars().next(); + if !before.is_some_and(is_word_char) && !after.is_some_and(is_word_char) { + return true; + } + at = pos + 1; + } + false +} + +fn contains_call(body: &str, needle: &str) -> bool { + let mut at = 0; + while let Some(rel) = body[at..].find(needle) { + let pos = at + rel; + let before = body[..pos].chars().next_back(); + if !before.is_some_and(is_word_char) { + return true; + } + at = pos + 1; + } + false +} + +/// A backticked token's resolution. +fn resolve( + token: &str, + defs: &Definitions, + bases: &[PathBuf], + all_paths: &[String], +) -> Result { + let token = token.trim(); + if token.is_empty() { + return Ok(Class::NonName); + } + if token.starts_with("BS-") || token.starts_with("WB-") { + if token.starts_with("BS-") && !defs.rules.contains_key(token) { + return Err(format!("unknown bookspec rule {token}")); + } + if token.starts_with("WB-") && !defs.product_rules.contains_key(token) { + return Err(format!("unknown product rule {token}")); + } + return Ok(Class::RuleId); + } + if token.starts_with("books.") || token.starts_with("books:") { + if defs.surface.contains(token) || defs.literals.iter().any(|l| l.contains(token)) { + return Ok(Class::ProductSurface); + } + return Err(format!("product surface {token} names nothing")); + } + if token.contains("://") { + if defs.surface.contains(token) { + return Ok(Class::ProductSurface); + } + return Ok(Class::NonName); + } + // `path::item`: the path exists and its item resolves. + if let Some((head, item)) = token.split_once("::") { + if is_path_like(head) { + let exists = path_exists(head, bases, all_paths) || bookspec_path_exists(head); + if !exists { + return Err(format!("path {head} does not exist")); + } + return resolve(item, defs, bases, all_paths); + } + } + if is_path_like(token) { + if token.contains("...") { + return Ok(Class::NonName); + } + if path_exists(token, bases, all_paths) { + return Ok(Class::Path); + } + if bookspec_path_exists(token) { + return Ok(Class::Path); + } + if token.contains('*') { + return resolve_wildcard(token, defs); + } + if defs.literals.contains(token) { + return Ok(Class::StringValue); + } + return Err(format!("path {token} does not exist")); + } + // `Type::{a, b}` expands to the items named. + if let Some(open) = token.find("::{") { + if let Some(close) = token[open + 3..].find('}') { + let prefix = &token[..open + 2]; + let inner = &token[open + 3..open + 3 + close]; + let mut classes = Vec::new(); + for item in inner.split(',') { + let item = item.trim(); + if item.is_empty() { + continue; + } + classes.push(resolve(&format!("{prefix}{item}"), defs, bases, all_paths)?); + } + if classes.is_empty() { + return Err(format!("empty brace group {token}")); + } + return Ok(classes[0]); + } + } + if token.contains('*') { + return resolve_wildcard(token, defs); + } + // `base[_suffix]`: both names must be real Lean theorems. + if let Some(open) = token.find('[') { + if token.ends_with(']') { + let base = &token[..open]; + let suffix = &token[open + 1..token.len() - 1]; + let full = format!("{base}{suffix}"); + if is_audited(base) && is_audited(&full) { + return Ok(Class::LeanTheorem); + } + return Err(format!("Lean notation {token} names no audited theorems")); + } + } + if is_audited(token) { + return Ok(Class::LeanTheorem); + } + let last = token.rsplit("::").next().unwrap_or(token); + if defs.items.contains(token) || defs.items.contains(last) || defs.bare.contains(last) { + return Ok(Class::RustItem); + } + if defs.tests.contains(last) { + return Ok(Class::Test); + } + if defs.harnesses.contains(last) { + return Ok(Class::KaniHarness); + } + if defs.fuzz.contains(last) { + return Ok(Class::FuzzTarget); + } + // A suffix fragment of a harness name, as in `_at_tenths`. + if token.starts_with('_') + && (defs.harnesses.iter().any(|h| h.ends_with(token)) + || defs.tests.iter().any(|t| t.ends_with(token))) + { + return Ok(Class::KaniHarness); + } + if is_crate_name(token, bases) { + return Ok(Class::Crate); + } + if is_fixture_dir(token, all_paths) { + return Ok(Class::Path); + } + if defs.options.contains(token) { + return Ok(Class::OptionValue); + } + if defs.examples.iter().any(|e| e == token) { + return Ok(Class::OptionValue); + } + if defs.literals.contains(token) { + return Ok(Class::StringValue); + } + if is_nonn_name(token) { + return Ok(Class::NonName); + } + // Lowercase dotted names that are settings, events or features, when + // they appear as a string literal or source text. + if token.contains('.') && defs.surface.contains(token) { + return Ok(Class::StringValue); + } + if is_kebab(token) { + return Err(format!( + "option-like name {token} names no option or example" + )); + } + Err(format!("{token} names no known item")) +} + +fn resolve_wildcard(token: &str, defs: &Definitions) -> Result { + let (before, after) = match token.split_once('*') { + Some((before, after)) => (before, after), + None => (token, ""), + }; + // An example path wildcard (`examples/1099-*.toml`) matches the + // bookspec example names. + let example_before = before + .strip_prefix("bookspec/") + .unwrap_or(before) + .strip_prefix("examples/") + .unwrap_or(before); + let example_after = after.trim_end_matches(".toml"); + if defs + .examples + .iter() + .any(|e| e.starts_with(example_before) && e.ends_with(example_after)) + { + return Ok(Class::OptionValue); + } + if token.starts_with("proofs::") { + let module = before.rsplit("::").next().unwrap_or(""); + if defs.proof_files.contains(module) || defs.harnesses.iter().any(|h| h.starts_with(module)) + { + return Ok(Class::KaniHarness); + } + } + if defs.tests.iter().any(|t| t.starts_with(before)) { + return Ok(Class::Test); + } + if defs.harnesses.iter().any(|h| h.starts_with(before)) { + return Ok(Class::KaniHarness); + } + if defs.items.iter().any(|i| i.starts_with(before)) { + return Ok(Class::RustItem); + } + if defs.fuzz.iter().any(|f| f.starts_with(before)) { + return Ok(Class::FuzzTarget); + } + if defs.examples.iter().any(|e| e.starts_with(before)) { + return Ok(Class::OptionValue); + } + if defs.literals.iter().any(|l| l.starts_with(before)) { + return Ok(Class::StringValue); + } + if defs.surface.contains(before) { + return Ok(Class::StringValue); + } + Err(format!("wildcard {token} matches nothing")) +} + +fn is_audited(name: &str) -> bool { + let bare = name.strip_prefix("Bookspec.").unwrap_or(name); + // Audit.lean is inside `namespace Bookspec`, so its names are relative; + // a name may be written with any suffix of its namespace. + let audited = bookspec_checker::audited_theorems(bookspec_checker::audit_lean()); + audited.contains(bare) + || audited.iter().any(|a| { + a == name || a.ends_with(&format!(".{name}")) || bare.ends_with(&format!(".{a}")) + }) +} + +fn is_path_like(token: &str) -> bool { + const EXTS: &[&str] = &[ + ".md", ".rs", ".toml", ".json", ".csv", ".lean", ".db", ".key", ".txt", ".pdf", ".yml", + ".yaml", ".sh", + ]; + EXTS.iter().any(|e| token.ends_with(e)) || token.contains('/') || token.contains('\\') +} + +fn path_exists(token: &str, bases: &[PathBuf], all_paths: &[String]) -> bool { + let token = token.trim_end_matches('/'); + if token.is_empty() { + return false; + } + if bases.iter().any(|base| base.join(token).exists()) { + return true; + } + all_paths + .iter() + .any(|p| p == token || p.ends_with(&format!("/{token}"))) +} + +fn bookspec_path_exists(token: &str) -> bool { + let rest = token.strip_prefix("bookspec/").unwrap_or(token); + if let Some(name) = rest.strip_prefix("examples/") { + return bookspec_checker::examples() + .iter() + .any(|(file, _)| *file == name); + } + if let Some(name) = rest.strip_prefix("spec/") { + return bookspec_checker::spec_files() + .iter() + .any(|(file, _)| *file == name); + } + if let Some(name) = rest.strip_prefix("lean/") { + return bookspec_checker::lean_files() + .iter() + .any(|(file, _)| *file == name); + } + false +} + +fn is_fixture_dir(token: &str, all_paths: &[String]) -> bool { + all_paths + .iter() + .any(|path| path.contains("/fixtures/") && path.split('/').any(|part| part == token)) +} + +fn is_crate_name(token: &str, bases: &[PathBuf]) -> bool { + let dashed = token.replace('_', "-"); + bases.iter().any(|base| { + base.file_name() + .is_some_and(|name| name == token || name == dashed.as_str()) + }) +} + +fn is_nonn_name(token: &str) -> bool { + // A value: quoted text, a brace/field list, an assignment, a date + // format, an invoice number, a percentage, an amount, punctuation. + if token.chars().any(|c| { + matches!( + c, + '"' | '\'' + | '{' + | '}' + | '[' + | ']' + | '(' + | ')' + | '<' + | '>' + | '=' + | '+' + | '%' + | '$' + | '#' + | '&' + | '?' + | '|' + | ',' + | ';' + ) || c.is_whitespace() + }) { + return true; + } + if token + .chars() + .all(|c| c.is_ascii_digit() || ".+-".contains(c)) + { + return true; + } + if token.starts_with('.') || token.contains("...") { + return true; + } + // INV- or INV-0001: an illustrative number. + if token.starts_with("INV-") + && token + .chars() + .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '-') + { + return true; + } + false +} + +fn is_kebab(token: &str) -> bool { + token.split('-').all(|part| { + !part.is_empty() + && part + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()) + }) && token.contains('-') +} + +/// The `| Harness | Law |` rows of `text`, as (harness, law number). +fn law_rows(text: &str) -> Vec<(String, u32)> { + let mut out = Vec::new(); + for line in text.lines() { + let line = line.trim(); + if !line.starts_with('|') { + continue; + } + let cells: Vec<&str> = line.split('|').map(str::trim).collect(); + if cells.len() < 4 { + continue; + } + let first = cells[1]; + let Some(name) = first.strip_prefix('`').and_then(|s| s.strip_suffix('`')) else { + continue; + }; + let second = cells[2]; + if let Ok(law) = second.parse::() { + out.push((name.to_string(), law)); + } + } + out +} + +fn claimed_ids(root: &Path) -> (BTreeSet, BTreeSet) { + let mut live = BTreeSet::new(); + let mut retired = BTreeSet::new(); + for path in claims_files(root) { + let text = read(&path); + for line in text.lines() { + if let Some(rest) = line.strip_prefix("**bookspec:**") { + if let Some(id) = first_backtick(rest) { + live.insert(id); + } + } + if let Some(rest) = line.strip_prefix("**retired bookspec:**") { + if let Some(id) = first_backtick(rest) { + retired.insert(id); + } + } + } + } + (live, retired) +} + +fn first_backtick(text: &str) -> Option { + let start = text.find('`')? + 1; + let end = text[start..].find('`')? + start; + Some(text[start..end].to_string()) +} + +fn claims_files(root: &Path) -> Vec { + let mut files = Vec::new(); + walk(&root.join("docs/spec/claims"), "md", &mut files); + files.sort(); + files +} + +#[derive(Default)] +struct Fields { + bookspec: String, + retired_bookspec: String, + claims: String, + enforced: String, + checked: String, +} + +fn fields(body: &str) -> Fields { + let names = [ + ("Enforced", 0usize), + ("Checked", 1), + ("Claims", 2), + ("bookspec", 3), + ("retired bookspec", 4), + ]; + let mut marks: Vec<(usize, usize, usize)> = Vec::new(); + for (name, id) in names { + let mut at = 0; + while let Some(rel) = body[at..].find(&format!("*{name}:*")) { + let pos = at + rel; + // The pattern matches inside `**name:**` too (at its second + // star), which is the same marker: keep one, and consume the + // second trailing star when it is the bold form. + let mut end = pos + format!("*{name}:*").len(); + if body.as_bytes().get(end) == Some(&b'*') { + end += 1; + } + if !marks.iter().any(|(p, _, _)| *p == pos) { + marks.push((pos, end, id)); + } + at = pos + 1; + } + } + // Pick markers are boundaries only. + let mut at = 0; + while let Some(rel) = body[at..].find("*Pick") { + let pos = at + rel; + if !marks.iter().any(|(p, _, _)| *p == pos) { + marks.push((pos, pos + 5, 9)); + } + at = pos + 1; + } + marks.sort(); + let mut out = Fields::default(); + for (i, (_, end, id)) in marks.iter().enumerate() { + let stop = marks.get(i + 1).map(|m| m.0).unwrap_or(body.len()); + let stop = stop.max(*end); + let value = body[*end..stop].trim().to_string(); + match id { + 0 => out.enforced.push_str(&value), + 1 => out.checked.push_str(&value), + 2 => out.claims.push_str(&value), + 3 => out.bookspec.push_str(&value), + 4 => out.retired_bookspec.push_str(&value), + _ => {} + } + } + out +} + +fn level(claims: &str) -> &str { + claims.split_whitespace().next().unwrap_or("yes") +} + +fn backticks(text: &str) -> Vec { + let mut out = Vec::new(); + let mut rest = text; + while let Some(start) = rest.find('`') { + let after = &rest[start + 1..]; + let Some(end) = after.find('`') else { + break; + }; + let token = &after[..end]; + if !token.contains('\n') && !token.is_empty() { + out.push(token.to_string()); + } + rest = &after[end + 1..]; + } + out +} + +fn b_sections(text: &str) -> Vec<(String, String)> { + let lines: Vec<&str> = text.lines().collect(); + let mut out = Vec::new(); + let mut i = 0; + while i < lines.len() { + if let Some(heading) = lines[i].strip_prefix("## ") { + if heading.starts_with("B-") { + let mut body = String::new(); + let mut j = i + 1; + while j < lines.len() && !lines[j].starts_with("## ") { + body.push_str(lines[j]); + body.push('\n'); + j += 1; + } + if let Some(at) = body.find("### Product rules") { + body.truncate(at); + } + out.push((heading.to_string(), body)); + i = j; + continue; + } + } + i += 1; + } + out +} + +/// Product-rule spans: (id, body). +fn wb_sections(text: &str) -> Vec<(String, String)> { + let lines: Vec<&str> = text.lines().collect(); + let mut out = Vec::new(); + let mut i = 0; + while i < lines.len() { + if let Some(rest) = lines[i].strip_prefix("**WB-") { + let id_tail: String = rest + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '-') + .collect(); + let id = format!("WB-{id_tail}"); + let mut body = String::new(); + let mut j = i; + while j < lines.len() { + if j > i && (lines[j].starts_with("**WB-") || lines[j].starts_with("## ")) { + break; + } + body.push_str(lines[j]); + body.push('\n'); + j += 1; + } + out.push((id, body)); + i = j; + continue; + } + i += 1; + } + out +} + +fn index_paths(root: &Path) -> (Vec, Vec) { + let mut bases = vec![root.to_path_buf()]; + for entry in std::fs::read_dir(root.join("crates")).expect("crates") { + let crate_dir = entry.expect("a crate").path(); + bases.push(crate_dir.clone()); + if crate_dir.join("tests").is_dir() { + bases.push(crate_dir.join("tests")); + } + } + bases.push(root.join("fuzz")); + let mut all = Vec::new(); + collect_paths(root, root, &mut all); + (bases, all) +} + +fn collect_paths(root: &Path, dir: &Path, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for entry in entries.flatten() { + let path = entry.path(); + let name = entry.file_name(); + let name = name.to_string_lossy(); + if name == "target" || name == ".git" || name == "node_modules" { + continue; + } + if let Ok(rel) = path.strip_prefix(root) { + out.push(rel.to_string_lossy().replace('\\', "/")); + } + if path.is_dir() { + collect_paths(root, &path, out); + } + } +} + +fn main_index(root: &Path) -> (Definitions, Vec, Vec) { + let mut defs = build_definitions(root); + // Product rule ids and their counts, so duplicates are caught. + for path in claims_files(root) { + let text = read(&path); + for (id, _) in wb_sections(&text) { + *defs.product_rules.entry(id).or_insert(0) += 1; + } + } + let (bases, paths) = index_paths(root); + (defs, bases, paths) +} + +#[test] +fn every_claim_is_backed() { + let root = repo_root(); + let (defs, bases, all_paths) = main_index(&root); + + assert!( + !defs.rules.is_empty(), + "the pinned bookspec has rule records" + ); + assert!(!defs.harnesses.is_empty(), "the proofs carry harnesses"); + + let mut failures: Vec = Vec::new(); + let mut counts: BTreeMap = BTreeMap::new(); + let mut claims_checked = 0usize; + let mut tokens_seen = 0usize; + + for path in claims_files(&root) { + let text = read(&path); + let file = path + .strip_prefix(&root) + .unwrap_or(&path) + .display() + .to_string(); + for (heading, body) in b_sections(&text) { + let f = fields(&body); + // Live ids only. + if !f.bookspec.is_empty() { + for id in backticks(&f.bookspec) { + match defs.rules.get(&id) { + Some(false) => {} + Some(true) => failures.push(format!( + "{file}: {heading}: {id} is retired; write `**retired bookspec:**`" + )), + None => failures.push(format!( + "{file}: {heading}: bookspec id {id} does not exist" + )), + } + } + } + if !f.retired_bookspec.is_empty() { + for id in backticks(&f.retired_bookspec) { + match defs.rules.get(&id) { + Some(true) => {} + Some(false) => failures.push(format!( + "{file}: {heading}: {id} is live; write `**bookspec:**`" + )), + None => failures.push(format!( + "{file}: {heading}: retired bookspec id {id} does not exist" + )), + } + } + } + let claim = level(&f.claims); + if claim != "yes" && claim != "partly" { + continue; + } + claims_checked += 1; + for (name, value) in [("Enforced", &f.enforced), ("Checked", &f.checked)] { + if value.trim().is_empty() { + failures.push(format!( + "{file}: {heading}: a `{claim}` claim has no **{name}:**" + )); + continue; + } + for token in backticks(value) { + tokens_seen += 1; + match resolve(&token, &defs, &bases, &all_paths) { + Ok(class) => *counts.entry(class).or_insert(0) += 1, + Err(error) => failures.push(format!( + "{file}: {heading}: {name}: backtick `{token}`: {error}" + )), + } + } + } + } + for (id, body) in wb_sections(&text) { + let f = fields(&body); + let claim = level(&f.claims); + if claim != "yes" && claim != "partly" { + continue; + } + claims_checked += 1; + for (name, value) in [("Enforced", &f.enforced), ("Checked", &f.checked)] { + if value.trim().is_empty() { + failures.push(format!( + "{file}: {id}: a `{claim}` product rule has no **{name}:**" + )); + continue; + } + for token in backticks(value) { + tokens_seen += 1; + match resolve(&token, &defs, &bases, &all_paths) { + Ok(class) => *counts.entry(class).or_insert(0) += 1, + Err(error) => failures + .push(format!("{file}: {id}: {name}: backtick `{token}`: {error}")), + } + } + } + } + } + + for (id, count) in &defs.product_rules { + if *count > 1 { + failures.push(format!("{id} is declared {count} times; WB ids are unique")); + } + } + + // The kernel: every pub fn has a harness, a bridge property and a law. + let kernel = kernel_functions(&root); + assert!(!kernel.is_empty(), "the kernel carries public functions"); + let mut harness_bodies: Vec<(String, String)> = Vec::new(); + let mut proof_files = Vec::new(); + walk( + &root.join("crates/ledger-core/src/proofs"), + "rs", + &mut proof_files, + ); + for path in &proof_files { + let code = strip_code(&read(path)); + harness_bodies.extend(collect_bodies_with_attribute(&code, "#[kani::proof]")); + } + let mut bridge_bodies: Vec<(String, String)> = Vec::new(); + let mut bridge_files = Vec::new(); + walk( + &root.join("crates/ledger-core/tests/kernel_bridge"), + "rs", + &mut bridge_files, + ); + for path in &bridge_files { + let text = read(path); + let code = strip_code(&text); + let chars: Vec = code.chars().collect(); + let mut i = 0; + while i < chars.len() { + if chars[i..].starts_with(&PROPTEST) { + if let Some(open) = code[i..].find('{') { + let at = i + open; + if let Some(close) = matching_brace(&chars, at, ('{', '}')) { + let block: String = chars[at + 1..close].iter().collect(); + let mut fns = Vec::new(); + collect_function_bodies(&block, &mut fns); + bridge_bodies.extend(fns); + i = close; + continue; + } + } + } + i += 1; + } + for (name, body) in collect_bodies_with_attribute(&code, "#[test]") { + bridge_bodies.push((name, body)); + } + } + + let mut laws: BTreeMap = BTreeMap::new(); + for (name, law) in law_rows(&read(&root.join("docs/verification.md"))) { + laws.insert(name, law); + } + let mut proof_notes = Vec::new(); + walk(&root.join("docs/proofs"), "md", &mut proof_notes); + for path in &proof_notes { + for (name, law) in law_rows(&read(path)) { + laws.entry(name).or_insert(law); + } + } + let laws_md = bookspec_checker::spec_files() + .into_iter() + .find(|(name, _)| *name == "laws.md") + .map(|(_, text)| text) + .expect("bookspec's spec/laws.md"); + let law_numbers: BTreeSet = laws_md + .lines() + .filter_map(|line| { + let cells: Vec<&str> = line.trim().split('|').map(str::trim).collect(); + if cells.len() < 5 { + return None; + } + cells[1].parse::().ok() + }) + .collect(); + assert!(!law_numbers.is_empty(), "bookspec numbers its laws"); + + let mut kernel_checked = 0usize; + let kernel_seen = kernel.len(); + let mut seen_exceptions = BTreeSet::new(); + for (name, file) in &kernel { + let harnesses: Vec<&str> = harness_bodies + .iter() + .filter(|(_, body)| calls(body, name)) + .map(|(h, _)| h.as_str()) + .collect(); + let bridges: Vec<&str> = bridge_bodies + .iter() + .filter(|(_, body)| calls(body, name)) + .map(|(b, _)| b.as_str()) + .collect(); + let law = harnesses + .iter() + .filter_map(|h| laws.get(*h)) + .find(|n| law_numbers.contains(n)); + let mut lacks = Vec::new(); + if harnesses.is_empty() { + lacks.push("a Kani harness"); + } + if bridges.is_empty() { + lacks.push("a bridge property"); + } + if law.is_none() { + lacks.push("a law"); + } + if lacks.is_empty() { + kernel_checked += 1; + continue; + } + match EXCEPTIONS.iter().find(|(fn_name, _, _)| fn_name == name) { + Some((_, what, why)) => { + seen_exceptions.insert(name.clone()); + let stated = *what; + for lack in &lacks { + let word = lack.trim_start_matches("a "); + assert!( + stated.contains(word) || stated.contains(lack), + "{name} is excepted for {stated:?}, but also lacks {lack} (in {file}); the list is stale" + ); + } + assert!(!why.trim().is_empty(), "{name}'s exception says why"); + } + None => failures.push(format!( + "kernel `{name}` ({file}) lacks {}; add a harness, a bridge property or a law, or name it in EXCEPTIONS with why", + lacks.join(", ") + )), + } + } + for (name, _, _) in EXCEPTIONS { + assert!( + kernel.iter().any(|(fn_name, _)| fn_name == name), + "excepted kernel function {name} does not exist; the list is stale" + ); + assert!( + seen_exceptions.contains(*name), + "excepted kernel function {name} is fully backed now; remove it from EXCEPTIONS" + ); + } + assert_eq!( + EXCEPTIONS.len(), + 16, + "the kernel exception list changes only on purpose" + ); + + // Every law row that cites a claimed rule names audited theorems. + let (live_ids, _) = claimed_ids(&root); + let audited = bookspec_checker::audited_theorems(bookspec_checker::audit_lean()); + assert!(!audited.is_empty(), "bookspec embeds its Audit.lean list"); + let mut law_rows_checked = 0usize; + for line in laws_md.lines() { + let cells: Vec<&str> = line.trim().split('|').map(str::trim).collect(); + if cells.len() < 5 { + continue; + } + let Ok(number) = cells[1].parse::() else { + continue; + }; + let citations: BTreeSet = cells[3] + .split(|c: char| !(c.is_ascii_alphanumeric() || c == '-')) + .filter(|w| w.starts_with("BS-")) + .map(str::to_string) + .collect(); + if !citations.iter().any(|id| live_ids.contains(id)) { + continue; + } + law_rows_checked += 1; + let theorems = cells[4]; + if theorems.contains("none —") { + let reason = theorems.split("none —").nth(1).unwrap_or("").trim(); + assert!( + !reason.is_empty(), + "law {number} says `none` without a reason" + ); + continue; + } + let tokens = backticks(theorems); + assert!( + !tokens.is_empty(), + "law {number} cites a claimed rule but names no Lean theorem" + ); + for token in tokens { + let allowed_definition = token == "Bookspec.Accepted" + && theorems.contains("`Bookspec.Accepted` (definition)"); + let bare = token.strip_prefix("Bookspec.").unwrap_or(&token); + if !allowed_definition && !audited.contains(bare) { + failures.push(format!( + "law {number}: Lean theorem `{token}` is not in Audit.lean" + )); + } + } + } + + println!("claims sections checked: {claims_checked}"); + println!("backticked tokens resolved: {tokens_seen}"); + for (class, count) in &counts { + println!(" {}: {count}", class.name()); + } + println!("kernel functions checked: {kernel_seen} ({kernel_checked} fully backed)"); + println!("kernel exceptions: {}", EXCEPTIONS.len()); + println!("law rows checked: {law_rows_checked}"); + + assert!( + failures.is_empty(), + "the traceability gate found {} problem(s):\n{}", + failures.len(), + failures.join("\n") + ); + assert!( + claims_checked >= CLAIMS_FLOOR, + "claims sections checked ({claims_checked}) fell below {CLAIMS_FLOOR}" + ); + assert!( + tokens_seen >= TOKENS_FLOOR, + "backticked tokens checked ({tokens_seen}) fell below {TOKENS_FLOOR}" + ); + assert!( + kernel_seen >= KERNEL_FLOOR, + "kernel functions checked ({kernel_seen}) fell below {KERNEL_FLOOR}" + ); +} + +/// Kernel public functions with no independent harness, bridge or law, +/// and why. The length is pinned above. +const EXCEPTIONS: &[(&str, &str, &str)] = &[ + ( + "movements", + "a Kani harness and a law", + "it allocates a Vec; every harness calls the fixed-array `movements_into` (proofs/mod.rs any_len says why), and its law 3 is movements_into's", + ), + ( + "reversal", + "a Kani harness and a law", + "it allocates a Vec; every reversal harness calls `reverse_line` directly, and its law 5 is reverse_line's", + ), + ( + "flip", + "a bridge property", + "it maps a two-variant enum with no amount to bridge; Kani `flip_negates` proves it", + ), + ( + "signed", + "a bridge property", + "it is called by the bridged `net` and `totals` properties, never as a bridge's own subject", + ), + ( + "movements_into", + "a bridge property", + "it is the fixed-array helper; bridge `sums_agree` bridges its public wrapper `movements`, and every harness calls it", + ), + ( + "reverse_line", + "a bridge property", + "bridge `reversal_agrees` covers it through `reversal`", + ), + ( + "payment_bucket", + "a bridge property", + "it maps two enums to a bucket with no amount to bridge; Kani `payment_bucket_is_the_table` proves the table", + ), + ( + "OnBehalf::mirror", + "a bridge property", + "it maps a two-variant enum to itself with no amount to bridge; Kani `constructive_mirrors` proves it", + ), + ( + "Direction::flip", + "a bridge property", + "it maps a three-variant enum with no amount to bridge; engine tests check it", + ), + ( + "Direction::of", + "a Kani harness, a bridge property and a law", + "it is a three-way sign classification, exercised through `party_target`; no harness or law states it directly", + ), + ( + "Direction::key", + "a Kani harness, a bridge property and a law", + "it is a wire-name lookup with no arithmetic; engine and store tests check the names", + ), + ( + "MonthPart::is_valid", + "a Kani harness, a bridge property and a law", + "it is a range predicate with no arithmetic; `part_weight` and the proration harnesses exercise it", + ), + ( + "part_weight", + "a Kani harness, a bridge property and a law", + "it is generic over `Units`, not `Amount`; laws 26-28 are stated through `prorate_by_days`, which calls it", + ), + ( + "fx_booked_minor", + "a Kani harness and a law", + "it is the Decimal/currency wrapper around `fx_booked`; the harnesses and law 41 are fx_booked's, and the bridge carries them to Decimal", + ), + ( + "round_places", + "a Kani harness and a law", + "it is the Decimal wrapper around `round_step`; the harnesses and law 40 are round_step's, and the bridge carries them to Decimal", + ), + ( + "round_minor", + "a Kani harness and a law", + "it is the Decimal/currency wrapper around `round_step`; the harnesses and law 40 are round_step's, and the bridge carries them to Decimal", + ), +]; + +#[test] +fn made_up_names_do_not_resolve() { + let root = repo_root(); + let (defs, bases, all_paths) = main_index(&root); + for token in ["no_such_fn_xyz", "NoSuch.theorem", "books.no_such_tool_xyz"] { + assert!( + resolve(token, &defs, &bases, &all_paths).is_err(), + "made-up name `{token}` must not resolve" + ); + } +} From 71a4e7e59d9dc85b0dbaf9226ff48414dbe0248b Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 21:25:16 -0700 Subject: [PATCH 08/26] fix(core): custom terms are due on the date they give BS-arap-3 statement 1: custom terms ("Due 2026-11-15") are due on the date they give. Terms::due_date returned the document's own date for them, so the MCP path (create_invoice / create_bill, from the terms given or a party's default) stored an invoice dated 2026-11-01 on "Due 2026-11-15" as due 2026-11-01: a document that read past due two weeks early in the aging. Terms now keeps the agreed date (a new `agreed` field, Some exactly for custom terms, with Terms::agreed_date), and due_date returns it, refusing an agreed date before the document's like any due date before its document. TermsKind keeps its shape, so stored kinds read as before. Terms read back from storage fill `agreed` from their canonical text when it is missing, and a custom terms with no readable date is refused rather than invented. Stored books: the journal records each document's due_date itself (invoice.created / bill.created payloads) and replay reads it, never recomputing it from the terms, so a document already written keeps the due date it recorded (posted is forever). New journal entries with custom terms carry the extra "agreed" key; older ones read as before. No golden under crates/*/tests/golden holds custom terms, so none changes; the live books have no invoices or bills. Through the tool, an invoice dated 2026-11-01 on "Due 2026-11-15": due 2026-11-01 before, 2026-11-15 after. Tests: ledger-core custom_terms_are_due_on_the_date_they_give (Terms, the stored document, the storage round trip incl. the older form, and the refusals) and the same through books.create_invoice / create_bill / a party's default terms and the refusal of a document dated after the agreed day (ledger-cli documents.rs). Co-Authored-By: Claude Sonnet 5.5 --- crates/ledger-cli/tests/documents.rs | 62 +++++++++++++++ crates/ledger-core/src/arap.rs | 90 ++++++++++++++++++---- crates/ledger-core/tests/spec_documents.rs | 54 +++++++++++++ 3 files changed, 192 insertions(+), 14 deletions(-) diff --git a/crates/ledger-cli/tests/documents.rs b/crates/ledger-cli/tests/documents.rs index f7368c28..83f450b3 100644 --- a/crates/ledger-cli/tests/documents.rs +++ b/crates/ledger-cli/tests/documents.rs @@ -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. diff --git a/crates/ledger-core/src/arap.rs b/crates/ledger-core/src/arap.rs index 2a89a679..5f92f1ae 100644 --- a/crates/ledger-core/src/arap.rs +++ b/crates/ledger-core/src/arap.rs @@ -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, +} + +/// 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, + text: String, + #[serde(default)] + agreed: Option, +} + +impl TryFrom for Terms { + type Error = String; + + fn try_from(w: TermsWire) -> Result { + 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 { 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 { + self.agreed + } + /// The early-payment discount, when there is one. pub fn discount(&self) -> Option { 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 { 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) diff --git a/crates/ledger-core/tests/spec_documents.rs b/crates/ledger-core/tests/spec_documents.rs index 2b638f36..1986e901 100644 --- a/crates/ledger-core/tests/spec_documents.rs +++ b/crates/ledger-core/tests/spec_documents.rs @@ -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::(json).unwrap(), terms); + let old = serde_json::json!({"kind": "custom", "text": "Due 2026-11-15"}); + assert_eq!(serde_json::from_value::(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::(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::(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] From e6c0d0d51b43b5d06ab724acae0827399cc211e2 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 21:25:16 -0700 Subject: [PATCH 09/26] test(core): the adapter reads due dates from the engine The bookspec adapter took a custom terms' due date by parsing the example's terms text, which sidestepped the engine bug that custom terms were due on the document's own date, so no example could catch it. It now takes every due date, custom included, from Terms::due_date; an example on "Due 2026-11-15" passes only if the engine computes 2026-11-15 (BS-arap-3). Co-Authored-By: Claude Sonnet 5.5 --- crates/ledger-core/tests/bookspec/events.rs | 26 +++++++-------------- crates/ledger-core/tests/bookspec/main.rs | 4 ++-- 2 files changed, 11 insertions(+), 19 deletions(-) diff --git a/crates/ledger-core/tests/bookspec/events.rs b/crates/ledger-core/tests/bookspec/events.rs index 4153c2e5..00eba781 100644 --- a/crates/ledger-core/tests/bookspec/events.rs +++ b/crates/ledger-core/tests/bookspec/events.rs @@ -203,12 +203,12 @@ impl Books<'_> { } /// 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`, except for a - /// date the parties agreed ("Due 2026-11-15"), which that call leaves to - /// its caller (the engine's contract: the caller passes the agreed date, - /// which the terms' canonical text carries). The example's spelling is - /// the canonical one, so the engine must print it back as written. - /// Without terms a document is due on its own date. + /// 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>, @@ -224,17 +224,9 @@ impl Books<'_> { text, "{what}: the engine prints terms {text:?} back as written" ); - let due = match parsed.kind() { - TermsKind::Custom => { - let agreed = text.strip_prefix("Due ").unwrap_or_else(|| { - panic!("{what}: custom terms {text:?} carry their date after \"Due \"") - }); - crate::date(agreed, what) - } - _ => parsed - .due_date(date) - .unwrap_or_else(|e| panic!("{what}: terms {text:?} on {date}: {e}")), - }; + let due = parsed + .due_date(date) + .unwrap_or_else(|e| panic!("{what}: terms {text:?} on {date}: {e}")); (due, Some(parsed)) } diff --git a/crates/ledger-core/tests/bookspec/main.rs b/crates/ledger-core/tests/bookspec/main.rs index e0f9c456..f835ecaf 100644 --- a/crates/ledger-core/tests/bookspec/main.rs +++ b/crates/ledger-core/tests/bookspec/main.rs @@ -55,8 +55,8 @@ pub(crate) use ledger_core::{ InstrumentId, InstrumentKind, InvoiceFields, Ledger, LedgerError, MemberCapital, MemberClose, Money, NewAsset, NewSchedule, PartyId, PartyMember, PartyShare, PaymentAccounts, ReconcilingKind, Role, ScheduleConvention, ScheduleId, ScheduleKind, Share, Side, Terms, - TermsKind, TinFacts, TinType, VendorId, W9Facts, cash_flow, members_equity, - profit_and_loss_for_period, trial_balance_as_of, vendor_1099_report, + 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; From 6b20946ae7fb0325cf9c0df7bc92b9c67986b2c4 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 21:53:53 -0700 Subject: [PATCH 10/26] docs(claims): name the real items the stricter gate caught The traceability gate now resolves a name exactly, so five citations that were only approximately right are corrected to the code they mean: - `form1099::Vendor1099Report::untagged_payments` is the free `form1099::untagged_payments`, not a method. - `JournalFormat::declared` is the free `format::declared`, not an associated function. - the Deductible and Apportion Lean theorems were cited bare; they live in those namespaces (`Deductible.tie_away_pos`, `Apportion.allocW_sum`, ...). - `control_agrees` is `Documents.control_agrees`. - `Step.discard` is a Step constructor, not an audited theorem; the claim keeps the two audited theorems that prove it. Co-Authored-By: DeepSeek V4.1 Flash --- docs/spec/claims/1099.md | 2 +- docs/spec/claims/arap.md | 2 +- docs/spec/claims/entry.md | 2 +- docs/spec/claims/format.md | 2 +- docs/spec/claims/ledger.md | 4 ++-- docs/spec/claims/partner.md | 4 ++-- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/spec/claims/1099.md b/docs/spec/claims/1099.md index c9bd6db5..9ca2e6da 100644 --- a/docs/spec/claims/1099.md +++ b/docs/spec/claims/1099.md @@ -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_payments`, `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). diff --git a/docs/spec/claims/arap.md b/docs/spec/claims/arap.md index 974e279c..611785e8 100644 --- a/docs/spec/claims/arap.md +++ b/docs/spec/claims/arap.md @@ -65,7 +65,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). diff --git a/docs/spec/claims/entry.md b/docs/spec/claims/entry.md index 080f976e..b311d1e2 100644 --- a/docs/spec/claims/entry.md +++ b/docs/spec/claims/entry.md @@ -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`, diff --git a/docs/spec/claims/format.md b/docs/spec/claims/format.md index 5d4f293e..fd2b2db6 100644 --- a/docs/spec/claims/format.md +++ b/docs/spec/claims/format.md @@ -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 diff --git a/docs/spec/claims/ledger.md b/docs/spec/claims/ledger.md index 9b4c3ea9..3d642908 100644 --- a/docs/spec/claims/ledger.md +++ b/docs/spec/claims/ledger.md @@ -310,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 diff --git a/docs/spec/claims/partner.md b/docs/spec/claims/partner.md index 3318e8b4..66fc3d27 100644 --- a/docs/spec/claims/partner.md +++ b/docs/spec/claims/partner.md @@ -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`, From 087ddaf094a20f802ba95ad80b02fa95ae731aa2 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 21:53:56 -0700 Subject: [PATCH 11/26] docs(claims): one Enforced/Checked pair for WB-prepaid-2 The rule carried two pairs, the first naming only `amortization_plan` and the replay entry point and the second naming `schedule_month_hold` too. One pair says both: the schedule's plan, replay, and the month hold, with the three tests that check them. Co-Authored-By: DeepSeek V4.1 Flash --- docs/spec/claims/prepaid.md | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/docs/spec/claims/prepaid.md b/docs/spec/claims/prepaid.md index 20ba1534..b49d108f 100644 --- a/docs/spec/claims/prepaid.md +++ b/docs/spec/claims/prepaid.md @@ -63,12 +63,7 @@ engine change is unit K-U5's; this note records the claim.) 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`. +replay), `Ledger::replay_register_schedule`, `Ledger::schedule_month_hold`. **Checked:** `defect9_legacy_schedules_stay_monthly_even`, -`prop_monthly_even_plan_is_unchanged`. - -**Enforced:** `schedules` replay (`amortization_plan`), -`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`. From 6f2e2cf1ebf12c27399fd2be604064fc11e62bbb Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 21:54:01 -0700 Subject: [PATCH 12/26] test(core): bridge the party direction, part weight and reverse_target Three properties the traceability gate can see as calls, not mentions: - `reverse_target_agrees`: the earlier party bridge only passed `reverse_target` to `and_then`, which proves nothing about the `i64` and `Decimal` instantiations agreeing; the property now calls both. - `direction_of_agrees`: `Direction::of` classifies the same sign at both types, each case keeping its meaning. - `part_weight_agrees`: `part_weight` is the same weight at `i32`, `i64` and `i128`, and `None` exactly for a part no month has. Co-Authored-By: DeepSeek V4.1 Flash --- .../tests/kernel_bridge/entries.rs | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/crates/ledger-core/tests/kernel_bridge/entries.rs b/crates/ledger-core/tests/kernel_bridge/entries.rs index 08d6c671..40bcf6a9 100644 --- a/crates/ledger-core/tests/kernel_bridge/entries.rs +++ b/crates/ledger-core/tests/kernel_bridge/entries.rs @@ -31,6 +31,14 @@ 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 { + prop_oneof![ + Just(kernel::Direction::Paid), + Just(kernel::Direction::Received), + Just(kernel::Direction::Neither), + ] +} + proptest! { #![proptest_config(ProptestConfig::with_cases(1000))] @@ -95,4 +103,73 @@ proptest! { 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 + /// each refuses the same out-of-range inputs (law 24). + #[test] + fn reverse_target_agrees( + amount in arb_cents(), + cash in arb_cents(), + in_kind in arb_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| kernel::PartyTarget { + amount: dec(r.amount), + direction: r.direction, + cash: dec(r.cash), + in_kind: dec(r.in_kind), + }; + prop_assert_eq!( + kernel::reverse_target(t).map(as_dec), + kernel::reverse_target(d) + ); + } + + /// `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 = kernel::part_weight(part); + let w64: Option = kernel::part_weight(part); + let w128: Option = 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); + } + } } From 080a3ffbf53b0e2fed5735f1e008045e1a7071d4 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 21:54:10 -0700 Subject: [PATCH 13/26] test(core): Kani for Direction::of and part_weight Both were exceptions for lacking all three backing kinds; neither is a wrapper or an enum map. `Direction::of` is the sign classification the party direction law is stated over (law 23), and `part_weight` is the weight the proration charges are computed from (laws 26-28). - `direction_of_is_the_sign` explores any `i64` and covers paid, received and neither (`kani::cover!`). - `part_weight_is_days_of_the_month` explores `days` and `month_days` up to 40 and covers a partial month, a whole month and an invalid part. - each spec block now carries its `SOURCE:` line, so the gate's right-law check applies to them. - `docs/proofs/entries.md` records each harness's law in the machine-readable table; the exception list drops from 16 to 14 (`Direction::key` and `MonthPart::is_valid` stay, with their reasons). Co-Authored-By: DeepSeek V4.1 Flash --- crates/ledger-core/src/kernel/entries.rs | 5 +- crates/ledger-core/src/proofs/mod.rs | 44 ++++++++++++++++- .../tests/bookspec/traceability.rs | 12 +---- docs/proofs/entries.md | 48 +++++++++++++++++++ 4 files changed, 94 insertions(+), 15 deletions(-) create mode 100644 docs/proofs/entries.md diff --git a/crates/ledger-core/src/kernel/entries.rs b/crates/ledger-core/src/kernel/entries.rs index 07144ab2..cb40e4a8 100644 --- a/crates/ledger-core/src/kernel/entries.rs +++ b/crates/ledger-core/src/kernel/entries.rs @@ -1150,7 +1150,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(amount: T) -> Self { if amount > T::ZERO { Direction::Paid @@ -1461,7 +1461,8 @@ 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. +/// month_days)`, exactly. `None` for a part no month has. SOURCE: +/// BS-asset-1, BS-prepaid-1 (proration by days; laws 26-28). pub fn part_weight(p: MonthPart) -> Option { if !p.is_valid() { return None; diff --git a/crates/ledger-core/src/proofs/mod.rs b/crates/ledger-core/src/proofs/mod.rs index e127cedd..52e4caae 100644 --- a/crates/ledger-core/src/proofs/mod.rs +++ b/crates/ledger-core/src/proofs/mod.rs @@ -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 = 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 diff --git a/crates/ledger-core/tests/bookspec/traceability.rs b/crates/ledger-core/tests/bookspec/traceability.rs index b2b716cf..30a9ef66 100644 --- a/crates/ledger-core/tests/bookspec/traceability.rs +++ b/crates/ledger-core/tests/bookspec/traceability.rs @@ -1747,7 +1747,7 @@ fn every_claim_is_backed() { } assert_eq!( EXCEPTIONS.len(), - 16, + 14, "the kernel exception list changes only on purpose" ); @@ -1876,11 +1876,6 @@ const EXCEPTIONS: &[(&str, &str, &str)] = &[ "a bridge property", "it maps a three-variant enum with no amount to bridge; engine tests check it", ), - ( - "Direction::of", - "a Kani harness, a bridge property and a law", - "it is a three-way sign classification, exercised through `party_target`; no harness or law states it directly", - ), ( "Direction::key", "a Kani harness, a bridge property and a law", @@ -1891,11 +1886,6 @@ const EXCEPTIONS: &[(&str, &str, &str)] = &[ "a Kani harness, a bridge property and a law", "it is a range predicate with no arithmetic; `part_weight` and the proration harnesses exercise it", ), - ( - "part_weight", - "a Kani harness, a bridge property and a law", - "it is generic over `Units`, not `Amount`; laws 26-28 are stated through `prorate_by_days`, which calls it", - ), ( "fx_booked_minor", "a Kani harness and a law", diff --git a/docs/proofs/entries.md b/docs/proofs/entries.md new file mode 100644 index 00000000..cb5c5285 --- /dev/null +++ b/docs/proofs/entries.md @@ -0,0 +1,48 @@ +# 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` | 26 | `days` and `month_days` 0..=40; valid, partial, whole and invalid parts covered | + +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` | 26 | + +Times: measured alone with +`cargo kani -p ledger-core --exact --harness proofs::` 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 and refuses the same out-of-range inputs (law 24). 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. From 10fdab668d1063a3d096a942dc285677d642c0f8 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 21:54:19 -0700 Subject: [PATCH 14/26] fix(core): the gate resolves names strictly Three resolver weaknesses let a wrong name pass as backed, which is exactly what the gate exists to catch: - Kani harnesses resolved as Rust items: every `fn` under `src/proofs/` was in the item set, so 79 of ~82 harness citations never reached the harness class. Proof functions are excluded from items and harnesses are checked before items, so deleting a `#[kani::proof]` attribute now leaves the claim unbacked. - A kernel function was "called" by a word mention or any `.name(`. A call is now a bare `name(` that is not a method call, or `Type::name(` for a kernel type's method. The two proof and bridge call sites that only used method syntax are written as the qualified call they mean. - A `Type::item` token matched if its last segment existed anywhere, and every `fn` under `tests/` counted as a test. `Type::item` must now be an impl function, a variant, a field or an associated const of that type; `module::item` must be defined in that module's file; and only `#[test]`/`#[tokio::test]`/`proptest!` functions are tests. - Product surfaces are the exact tool registrations (or exact declared names); the dotted-string fallback is gone; crate names come from `[package] name`, not directory names. - `Audit.lean` is parsed once and matched exactly, with or without the `Bookspec.` prefix. The law-table check is stricter too: duplicate rows with different law numbers fail, and where a kernel function's `SOURCE:` line and its harness's law row both cite rule ids, they must intersect. Of the 55 kernel functions, 29 have both and are checked; 26 are skipped (no `SOURCE:` ids or a law with no rules). Self-tests cover a harness name, a proof helper that is not a harness, a made-up method, a real item under the wrong type, a test helper, an unregistered `books.` name, a directory as a crate, and an unaudited Lean name. Co-Authored-By: DeepSeek V4.1 Flash --- .../tests/bookspec/traceability.rs | 789 +++++++++++++----- 1 file changed, 588 insertions(+), 201 deletions(-) diff --git a/crates/ledger-core/tests/bookspec/traceability.rs b/crates/ledger-core/tests/bookspec/traceability.rs index 30a9ef66..a51682eb 100644 --- a/crates/ledger-core/tests/bookspec/traceability.rs +++ b/crates/ledger-core/tests/bookspec/traceability.rs @@ -255,8 +255,9 @@ fn impl_ranges(code: &str) -> Vec<(usize, usize, String)> { i = end; continue; } - // The type is the last identifier before the opening brace, and - // after `for` when it is a trait impl. + // The type is the path's last segment after `for` when it is a + // trait impl, with a leading generic parameter list skipped (an + // `impl Foo` names `Foo`, not `T`). let mut j = end; while j < chars.len() && chars[j] != '{' { j += 1; @@ -269,22 +270,7 @@ fn impl_ranges(code: &str) -> Vec<(usize, usize, String)> { Some((_, after)) => after, None => &header, }; - let mut last = String::new(); - let mut k = 0; - while k < segment.len() { - let rest: Vec = segment[k..].chars().collect(); - match word_at(&rest, 0) { - Some((w, used)) => { - last = w; - k += segment[k..] - .chars() - .take(used) - .map(char::len_utf8) - .sum::(); - } - None => k += segment[k..].chars().next().map(char::len_utf8).unwrap_or(1), - } - } + let last = impl_type_name(segment); if let Some(close) = matching_brace(&chars, j, ('{', '}')) { let start = chars[..i].iter().map(|c| c.len_utf8()).sum::(); let end = chars[..=close].iter().map(|c| c.len_utf8()).sum::(); @@ -295,6 +281,23 @@ fn impl_ranges(code: &str) -> Vec<(usize, usize, String)> { out } +/// The type an impl header after `impl` (and after `for`) names. +fn impl_type_name(segment: &str) -> String { + let mut rest = segment.trim_start(); + if rest.starts_with('<') { + let chars: Vec = rest.chars().collect(); + if let Some(close) = matching_brace(&chars, 0, ('<', '>')) { + let consumed: usize = chars[..=close].iter().map(|c| c.len_utf8()).sum(); + rest = rest[consumed..].trim_start(); + } + } + let head: String = rest + .chars() + .take_while(|c| !matches!(c, '<' | '{') && !c.is_whitespace()) + .collect(); + head.rsplit("::").next().unwrap_or(&head).to_string() +} + /// Every top-level item of a brace block, split on commas. fn top_items(body: &str) -> Vec { let chars: Vec = body.chars().collect(); @@ -424,7 +427,7 @@ fn struct_fields(code: &str, name: &str) -> Vec { /// Enum variants and struct fields in `code`, for definitions outside the /// crate's `src` (an integration test's own model types). -fn collect_types(code: &str, items: &mut BTreeSet, bare: &mut BTreeSet) { +fn collect_types(code: &str, items: &mut BTreeSet, qualified: &mut BTreeSet) { let chars: Vec = code.chars().collect(); let mut i = 0; while i < chars.len() { @@ -439,14 +442,16 @@ fn collect_types(code: &str, items: &mut BTreeSet, bare: &mut BTreeSet, bare: &mut BTreeSet) { +/// The names a `use` statement imports. They are not definitions: only an +/// external type's associated item (`NaiveDate::MAX`) is excused by them. +fn collect_imports(code: &str, imports: &mut BTreeSet) { for line in code.lines() { let line = line.trim_start(); let Some(rest) = line.strip_prefix("use ") else { @@ -473,7 +479,7 @@ fn collect_imports(code: &str, items: &mut BTreeSet) { "use" | "crate" | "self" | "super" | "as" | "pub" ) { - items.insert(word.clone()); + imports.insert(word.clone()); } word.clear(); } @@ -483,11 +489,24 @@ fn collect_imports(code: &str, items: &mut BTreeSet) { #[derive(Default)] struct Definitions { - /// Every Rust item name, bare or `Type::method`. + /// Every bare Rust item name (a `fn`, type, variant, field, `const`, + /// module or macro) defined under `crates/*/src` or in a test file. items: BTreeSet, - bare: BTreeSet, - /// Test and property names under `crates/*/tests`, `#[test]` in src, - /// and proptest functions. + /// The exact `Type::item` names: an impl's functions, an enum's + /// variants, an impl's associated `const`s and types. + qualified: BTreeSet, + /// The items defined in each module's own file (a directory module + /// keeps its submodules' items too, which is what it re-exports). + module_items: BTreeMap>, + /// Type names defined under `crates/*/src`. + types: BTreeSet, + /// Names a `use` line imports (external types included). + imports: BTreeSet, + /// `[package] name` of every crate. + crates: BTreeSet, + /// The exact tool names `ledger-mcp` registers. + product_surfaces: BTreeSet, + /// Test names: a `#[test]` fn or a `proptest!` body, in src or tests. tests: BTreeSet, /// `#[kani::proof]` functions under `src/proofs/`. harnesses: BTreeSet, @@ -497,7 +516,7 @@ struct Definitions { proof_files: BTreeSet, /// Every string literal in `crates/*` source. literals: BTreeSet, - /// All crate source text, for product-surface names. + /// All crate source text, for wildcard prefixes. surface: String, /// Rules by id and whether the record is retired. rules: BTreeMap, @@ -558,9 +577,160 @@ fn collect_function_bodies(code: &str, out: &mut Vec<(String, String)>) { } } +/// The `[package] name` of a Cargo manifest. +fn package_name(text: &str) -> Option { + let mut in_package = false; + for line in text.lines() { + let line = line.trim(); + if line.starts_with('[') { + in_package = line == "[package]"; + continue; + } + if in_package { + if let Some(rest) = line.strip_prefix("name") { + let rest = rest.trim_start(); + if let Some(rest) = rest.strip_prefix('=') { + let rest = rest.trim(); + if let Some(rest) = rest.strip_prefix('"') { + return rest.split('"').next().map(str::to_string); + } + } + } + } + } + None +} + +/// The module(s) a source file defines items for: its own file stem (or +/// `mod.rs`'s directory), and every enclosing directory that is a module +/// root, because a directory module re-exports its submodules' items. +fn module_keys(path: &Path) -> Vec { + let mut keys = Vec::new(); + let file = path.file_name().and_then(|n| n.to_str()).unwrap_or(""); + if file == "mod.rs" { + if let Some(dir) = path + .parent() + .and_then(|p| p.file_name()) + .and_then(|n| n.to_str()) + { + keys.push(dir.to_string()); + } + } else if file != "lib.rs" { + if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) { + keys.push(stem.to_string()); + } + } + let mut dir = path.parent(); + while let Some(d) = dir { + if d.file_name().is_some_and(|n| n == "src") { + break; + } + if d.join("mod.rs").is_file() { + if let Some(name) = d.file_name().and_then(|n| n.to_str()) { + keys.push(name.to_string()); + } + } + dir = d.parent(); + } + keys +} + +/// Test names: a `#[test]` fn or a function inside a `proptest!` block. +fn collect_test_names(code: &str, tests: &mut BTreeSet) { + for attr in ["#[test]", "#[tokio::test"] { + for (name, _) in collect_bodies_with_attribute(code, attr) { + tests.insert(name); + } + } + let chars: Vec = code.chars().collect(); + let mut i = 0; + while i < chars.len() { + if chars[i..].starts_with(&PROPTEST) { + if let Some(open) = code[i..].find('{') { + let at = i + open; + if let Some(close) = matching_brace(&chars, at, ('{', '}')) { + let block: String = chars[at + 1..close].iter().collect(); + let mut fns = Vec::new(); + collect_function_bodies(&block, &mut fns); + for (name, _) in fns { + tests.insert(name); + } + i = close; + continue; + } + } + } + i += 1; + } +} + +/// Every function and associated `const`/type in an impl block, qualified +/// by the implementing type. +fn collect_impl_qualified(block: &str, ty: &str, qualified: &mut BTreeSet) { + let chars: Vec = block.chars().collect(); + let mut i = 0; + while i < chars.len() { + if !(chars[i].is_ascii_alphabetic() || chars[i] == '_') { + i += 1; + continue; + } + let Some((word, end)) = word_at(&chars, i) else { + i += 1; + continue; + }; + if word == "fn" || word == "const" || word == "type" { + let j = skip_space(&chars, end); + if let Some((next, _)) = word_at(&chars, j) { + // `const fn` is a function; the `fn` arm records it. + if word != "const" || next != "fn" { + qualified.insert(format!("{ty}::{next}")); + } + } + } + i = end; + } +} + +/// The exact tool names `ledger-mcp` registers: every `name = "books.…"` +/// in its source. +fn collect_tool_names(root: &Path, out: &mut BTreeSet) { + let mut files = Vec::new(); + walk(&root.join("crates/ledger-mcp/src"), "rs", &mut files); + for path in files { + let text = read(&path); + let needle = "name = \""; + let mut at = 0; + while let Some(rel) = text[at..].find(needle) { + let start = at + rel + needle.len(); + let Some(end) = text[start..].find('"') else { + break; + }; + let name = &text[start..start + end]; + if name.starts_with("books.") { + out.insert(name.to_string()); + } + at = start + end + 1; + } + } +} + fn build_definitions(root: &Path) -> Definitions { let mut defs = Definitions::default(); + // Crate names: the workspace root, `fuzz`, and each crate's package. + let mut manifests = vec![root.join("Cargo.toml"), root.join("fuzz/Cargo.toml")]; + for entry in std::fs::read_dir(root.join("crates")).expect("crates") { + manifests.push(entry.expect("a crate").path().join("Cargo.toml")); + } + for manifest in manifests { + if let Ok(text) = std::fs::read_to_string(&manifest) { + if let Some(name) = package_name(&text) { + defs.crates.insert(name); + } + } + } + collect_tool_names(root, &mut defs.product_surfaces); + let mut src_files = Vec::new(); for entry in std::fs::read_dir(root.join("crates")).expect("crates") { let crate_dir = entry.expect("a crate").path(); @@ -570,6 +740,7 @@ fn build_definitions(root: &Path) -> Definitions { } } src_files.sort(); + let proofs = root.join("crates/ledger-core/src/proofs"); let mut enums = Vec::new(); let mut structs = Vec::new(); for path in &src_files { @@ -580,7 +751,13 @@ fn build_definitions(root: &Path) -> Definitions { for literal in literals(&text) { defs.literals.insert(literal); } - collect_imports(&code, &mut defs.items); + // A proof harness is never a plain Rust item: it resolves only as a + // `#[kani::proof]` fn, or deleting the attribute would go unseen. + if path.starts_with(&proofs) { + continue; + } + collect_imports(&code, &mut defs.imports); + let keys = module_keys(path); // Keywords and names. let chars: Vec = code.chars().collect(); let mut i = 0; @@ -604,8 +781,19 @@ fn build_definitions(root: &Path) -> Definitions { if word == "struct" { structs.push((path.clone(), name.clone())); } + if matches!( + word.as_str(), + "struct" | "enum" | "union" | "trait" | "type" + ) { + defs.types.insert(name.clone()); + } defs.items.insert(name.clone()); - defs.bare.insert(name); + for key in &keys { + defs.module_items + .entry(key.clone()) + .or_default() + .insert(name.clone()); + } } } "macro_rules" => { @@ -614,7 +802,12 @@ fn build_definitions(root: &Path) -> Definitions { j = skip_space(&chars, j + 1); if let Some((name, _)) = word_at(&chars, j) { defs.items.insert(name.clone()); - defs.bare.insert(name); + for key in &keys { + defs.module_items + .entry(key.clone()) + .or_default() + .insert(name.clone()); + } } } } @@ -622,35 +815,29 @@ fn build_definitions(root: &Path) -> Definitions { } i = end; } - // Methods, qualified by their impl. + // Methods, associated items and variants, qualified by their type. for (start, end, ty) in impl_ranges(&code) { - let block = &code[start..end]; - let mut fns = Vec::new(); - collect_pub_fns(block, &mut fns); - for (name, _) in fns { - let qualified = format!("{ty}::{name}"); - defs.items.insert(qualified); - defs.items.insert(name.clone()); - defs.bare.insert(name); - } + collect_impl_qualified(&code[start..end], &ty, &mut defs.qualified); } } for (path, name) in enums { let code = strip_code(&read(&path)); for variant in enum_variants(&code, &name) { defs.items.insert(variant.clone()); - defs.bare.insert(variant); + defs.qualified.insert(format!("{name}::{variant}")); } } for (path, name) in structs { let code = strip_code(&read(&path)); for field in struct_fields(&code, &name) { defs.items.insert(field.clone()); - defs.bare.insert(field); + // A public field is the type's item too (`Iif::changes`). + defs.qualified.insert(format!("{name}::{field}")); } } - // Tests: every fn under `tests/`, and `#[test]`/proptest in src. + // Tests: a `#[test]` fn or a `proptest!` body, in src or tests. A + // plain helper under `tests/` is not a test. let mut test_files = Vec::new(); for entry in std::fs::read_dir(root.join("crates")).expect("crates") { let dir = entry.expect("a crate").path().join("tests"); @@ -661,42 +848,13 @@ fn build_definitions(root: &Path) -> Definitions { test_files.sort(); for path in &test_files { let code = strip_code(&read(path)); - collect_types(&code, &mut defs.items, &mut defs.bare); - collect_imports(&code, &mut defs.items); - let mut fns = Vec::new(); - collect_function_bodies(&code, &mut fns); - for (name, _) in fns { - defs.tests.insert(name); - } + collect_types(&code, &mut defs.items, &mut defs.qualified); + collect_imports(&code, &mut defs.imports); + collect_test_names(&code, &mut defs.tests); } for path in &src_files { - let text = read(path); - let code = strip_code(&text); - let chars: Vec = code.chars().collect(); - // `#[test]` functions. - for (name, _) in collect_bodies_with_attribute(&code, "#[test]") { - defs.tests.insert(name); - } - // Proptest blocks. - let mut i = 0; - while i < chars.len() { - if chars[i..].starts_with(&PROPTEST) { - if let Some(open) = code[i..].find('{') { - let at = i + open; - if let Some(close) = matching_brace(&chars, at, ('{', '}')) { - let block: String = chars[at + 1..close].iter().collect(); - let mut fns = Vec::new(); - collect_function_bodies(&block, &mut fns); - for (name, _) in fns { - defs.tests.insert(name); - } - i = close; - continue; - } - } - } - i += 1; - } + let code = strip_code(&read(path)); + collect_test_names(&code, &mut defs.tests); } // Kani harnesses and proof files. @@ -748,87 +906,74 @@ fn build_definitions(root: &Path) -> Definitions { defs } -/// `pub fn` names in an impl block, with their offsets (unused offsets are -/// kept for a future stricter check). -fn collect_pub_fns(block: &str, out: &mut Vec<(String, usize)>) { - let chars: Vec = block.chars().collect(); - let mut i = 0; - while i < chars.len() { - if !(chars[i].is_ascii_alphabetic() || chars[i] == '_') { - i += 1; - continue; - } - let Some((word, end)) = word_at(&chars, i) else { - i += 1; - continue; - }; - if word != "pub" { - i = end; - continue; - } - let mut j = skip_space(&chars, end); - if chars.get(j) == Some(&'(') { - if let Some(close) = matching_brace(&chars, j, ('(', ')')) { - j = skip_space(&chars, close + 1); - } - } - if let Some((kw, kw_end)) = word_at(&chars, j) { - if kw == "fn" { - let k = skip_space(&chars, kw_end); - if let Some((name, _)) = word_at(&chars, k) { - out.push((name, i)); - } - } - } - i = end; - } -} - /// Functions preceded (within the previous attribute block) by `attr`. fn collect_bodies_with_attribute(code: &str, attr: &str) -> Vec<(String, String)> { + let chars: Vec = code.chars().collect(); let mut out = Vec::new(); let mut search = 0; while let Some(at) = code[search..].find(attr) { let start = search + at; - let after = start + attr.len(); - let tail = &code[after..]; - let Some(fn_at) = tail.find("fn ") else { + // The attribute runs from its `[` to the matching `]`; an + // attribute may carry arguments (`#[tokio::test(flavor = …)]`). + let Some(open) = code[start..].find('[').map(|p| start + p) else { break; }; - // Nothing but attributes/whitespace may sit between them. - let between = &tail[..fn_at]; - if between.contains('\n') { - let only_attrs = between.lines().all(|line| { - let line = line.trim(); - line.is_empty() - || line.starts_with("#[") - || line.starts_with("//") - || line.starts_with(']') - }); - if !only_attrs { - search = after; - continue; + let open = code[..open].chars().count(); + let Some(close) = matching_brace(&chars, open, ('[', ']')) else { + break; + }; + let mut i = skip_space(&chars, close + 1); + // Further attributes may sit between this one and the item. + while chars.get(i) == Some(&'#') { + let j = if chars.get(i + 1) == Some(&'!') { + i + 2 + } else { + i + 1 + }; + if chars.get(j) != Some(&'[') { + break; + } + let Some(c) = matching_brace(&chars, j, ('[', ']')) else { + break; + }; + i = skip_space(&chars, c + 1); + } + // Visibility and modifiers, then `fn`. + while let Some((word, end)) = word_at(&chars, i) { + match word.as_str() { + "pub" => { + i = skip_space(&chars, end); + if chars.get(i) == Some(&'(') { + if let Some(c) = matching_brace(&chars, i, ('(', ')')) { + i = skip_space(&chars, c + 1); + } + } + } + "async" | "const" | "unsafe" | "extern" => { + i = skip_space(&chars, end); + } + "fn" => { + i = skip_space(&chars, end); + break; + } + _ => break, } } - let at = after + fn_at + 3; - let chars: Vec = code.chars().collect(); - let prefix_len = code[..at].chars().count(); - let j = skip_space(&chars, prefix_len); - let Some((name, _)) = word_at(&chars, j) else { - search = after; + let Some((name, _)) = word_at(&chars, i) else { + search = start + attr.len(); continue; }; - let mut k = j; + let mut k = i; while k < chars.len() && chars[k] != '{' && chars[k] != ';' { k += 1; } if chars.get(k) == Some(&'{') { - if let Some(close) = matching_brace(&chars, k, ('{', '}')) { - let body: String = chars[k + 1..close].iter().collect(); + if let Some(end) = matching_brace(&chars, k, ('{', '}')) { + let body: String = chars[k + 1..end].iter().collect(); out.push((name, body)); } } - search = after; + search = start + attr.len(); } out } @@ -895,23 +1040,23 @@ fn kernel_functions(root: &Path) -> Vec<(String, String)> { out } -/// True when `body` calls `name`, bare or qualified, including a method -/// call written `.name(`. +/// True when `body` calls `name`: a qualified call (`Type::name(`), or a +/// bare `name(` that is not a method call (`.name(`). A word mention is +/// not a call. fn calls(body: &str, name: &str) -> bool { - if contains_call(body, &format!("{name}(")) { - return true; + if name.contains("::") { + return contains_qualified_call(body, name); } - let last = name.rsplit("::").next().unwrap_or(name); - contains_call(body, &format!("{last}(")) || contains_word(body, last) + contains_bare_call(body, name) } -fn contains_word(body: &str, word: &str) -> bool { +fn contains_qualified_call(body: &str, name: &str) -> bool { + let needle = format!("{name}("); let mut at = 0; - while let Some(rel) = body[at..].find(word) { + while let Some(rel) = body[at..].find(&needle) { let pos = at + rel; let before = body[..pos].chars().next_back(); - let after = body[pos + word.len()..].chars().next(); - if !before.is_some_and(is_word_char) && !after.is_some_and(is_word_char) { + if !before.is_some_and(is_word_char) { return true; } at = pos + 1; @@ -919,12 +1064,15 @@ fn contains_word(body: &str, word: &str) -> bool { false } -fn contains_call(body: &str, needle: &str) -> bool { +/// A bare `name(` that is neither a method call (`.name(`) nor the tail of +/// a longer identifier; a qualified call (`::name(`) counts. +fn contains_bare_call(body: &str, name: &str) -> bool { + let needle = format!("{name}("); let mut at = 0; - while let Some(rel) = body[at..].find(needle) { + while let Some(rel) = body[at..].find(&needle) { let pos = at + rel; let before = body[..pos].chars().next_back(); - if !before.is_some_and(is_word_char) { + if !before.is_some_and(is_word_char) && before != Some('.') { return true; } at = pos + 1; @@ -952,11 +1100,23 @@ fn resolve( } return Ok(Class::RuleId); } - if token.starts_with("books.") || token.starts_with("books:") { - if defs.surface.contains(token) || defs.literals.iter().any(|l| l.contains(token)) { + if token.starts_with("books.") { + // The exact tool registrations, or an exact name the books declare + // (a setting key such as `books.cash_accounts`). + if defs.product_surfaces.contains(token) || defs.literals.contains(token) { return Ok(Class::ProductSurface); } - return Err(format!("product surface {token} names nothing")); + return Err(format!("product surface {token} names no tool or setting")); + } + if token.starts_with("books:") { + // A scope (`books:post`) or a resource URI (`books://digest`), each + // an exact name in the source. + if defs.literals.contains(token) { + return Ok(Class::ProductSurface); + } + return Err(format!( + "product surface {token} names no scope or resource" + )); } if token.contains("://") { if defs.surface.contains(token) { @@ -1029,17 +1189,26 @@ fn resolve( if is_audited(token) { return Ok(Class::LeanTheorem); } - let last = token.rsplit("::").next().unwrap_or(token); - if defs.items.contains(token) || defs.items.contains(last) || defs.bare.contains(last) { - return Ok(Class::RustItem); + if token.contains("::") { + return resolve_qualified(token, defs, bases, all_paths); } - if defs.tests.contains(last) { - return Ok(Class::Test); - } - if defs.harnesses.contains(last) { + // A harness before an item: a proof function is never an ordinary item, + // so deleting its `#[kani::proof]` attribute leaves the claim unbacked. + if defs.harnesses.contains(token) { return Ok(Class::KaniHarness); } - if defs.fuzz.contains(last) { + if defs.items.contains(token) { + return Ok(Class::RustItem); + } + // An imported type (`Decimal`): a real item, though defined elsewhere. + if defs.imports.contains(token) && token.chars().next().is_some_and(|c| c.is_ascii_uppercase()) + { + return Ok(Class::RustItem); + } + if defs.tests.contains(token) { + return Ok(Class::Test); + } + if defs.fuzz.contains(token) { return Ok(Class::FuzzTarget); } // A suffix fragment of a harness name, as in `_at_tenths`. @@ -1049,7 +1218,7 @@ fn resolve( { return Ok(Class::KaniHarness); } - if is_crate_name(token, bases) { + if is_crate_name(token, defs) { return Ok(Class::Crate); } if is_fixture_dir(token, all_paths) { @@ -1067,11 +1236,6 @@ fn resolve( if is_nonn_name(token) { return Ok(Class::NonName); } - // Lowercase dotted names that are settings, events or features, when - // they appear as a string literal or source text. - if token.contains('.') && defs.surface.contains(token) { - return Ok(Class::StringValue); - } if is_kebab(token) { return Err(format!( "option-like name {token} names no option or example" @@ -1080,6 +1244,58 @@ fn resolve( Err(format!("{token} names no known item")) } +/// A `::` path: the last two segments name an item its container defines. +/// +/// A capitalized head is a type, so `Type::item` must be an impl function, +/// an enum variant, or an associated `const`/type. A lowercase head is a +/// module, so `module::item` must be defined in that module's own file. A +/// leading `crate` or crate name is dropped first. +fn resolve_qualified( + token: &str, + defs: &Definitions, + bases: &[PathBuf], + all_paths: &[String], +) -> Result { + let mut segments: Vec<&str> = token.split("::").collect(); + if matches!(segments.first(), Some(&"crate") | Some(&"self")) { + segments.remove(0); + } + while segments.first().is_some_and(|s| is_crate_name(s, defs)) { + segments.remove(0); + } + let Some(item) = segments.last().copied() else { + return Err(format!("{token} names no item")); + }; + if segments.len() == 1 { + return resolve(item, defs, bases, all_paths); + } + let container = segments[segments.len() - 2]; + let head_uppercase = container + .chars() + .next() + .is_some_and(|c| c.is_ascii_uppercase()); + if head_uppercase { + let qualified = format!("{container}::{item}"); + if defs.qualified.contains(&qualified) { + return Ok(Class::RustItem); + } + // An external type's associated item (`NaiveDate::MAX`): the type + // is imported, not defined in the tree, so its items are not here. + if !defs.types.contains(container) && defs.imports.contains(container) { + return Ok(Class::RustItem); + } + return Err(format!("{token} names no `{qualified}`")); + } + if defs + .module_items + .get(container) + .is_some_and(|items| items.contains(item)) + { + return Ok(Class::RustItem); + } + Err(format!("{token} names no item in module `{container}`")) +} + fn resolve_wildcard(token: &str, defs: &Definitions) -> Result { let (before, after) = match token.split_once('*') { Some((before, after)) => (before, after), @@ -1131,15 +1347,17 @@ fn resolve_wildcard(token: &str, defs: &Definitions) -> Result { Err(format!("wildcard {token} matches nothing")) } +/// The audited theorem list, parsed once. +fn audited_theorems() -> &'static BTreeSet { + static AUDITED: std::sync::OnceLock> = std::sync::OnceLock::new(); + AUDITED.get_or_init(|| bookspec_checker::audited_theorems(bookspec_checker::audit_lean())) +} + fn is_audited(name: &str) -> bool { let bare = name.strip_prefix("Bookspec.").unwrap_or(name); - // Audit.lean is inside `namespace Bookspec`, so its names are relative; - // a name may be written with any suffix of its namespace. - let audited = bookspec_checker::audited_theorems(bookspec_checker::audit_lean()); - audited.contains(bare) - || audited.iter().any(|a| { - a == name || a.ends_with(&format!(".{name}")) || bare.ends_with(&format!(".{a}")) - }) + // Audit.lean lists bare names (inside `namespace Bookspec`); a citation + // may write either form, but never a namespace suffix. + audited_theorems().contains(bare) || audited_theorems().contains(name) } fn is_path_like(token: &str) -> bool { @@ -1189,12 +1407,10 @@ fn is_fixture_dir(token: &str, all_paths: &[String]) -> bool { .any(|path| path.contains("/fixtures/") && path.split('/').any(|part| part == token)) } -fn is_crate_name(token: &str, bases: &[PathBuf]) -> bool { +/// A `[package] name` of one of the crates (dashed or underscored). +fn is_crate_name(token: &str, defs: &Definitions) -> bool { let dashed = token.replace('_', "-"); - bases.iter().any(|base| { - base.file_name() - .is_some_and(|name| name == token || name == dashed.as_str()) - }) + defs.crates.contains(token) || defs.crates.contains(&dashed) } fn is_nonn_name(token: &str) -> bool { @@ -1279,6 +1495,57 @@ fn law_rows(text: &str) -> Vec<(String, u32)> { out } +/// Record a harness's law row; a harness listed twice with different laws +/// is a conflict, not a precedence. +fn record_law( + laws: &mut BTreeMap, + failures: &mut Vec, + name: String, + law: u32, + source: &str, +) { + match laws.get(&name) { + Some(&existing) if existing != law => failures.push(format!( + "harness `{name}` is listed with law {existing} and law {law} ({source}); one row says the law" + )), + Some(_) => {} + None => { + laws.insert(name, law); + } + } +} + +/// The `BS-` ids a kernel function's own doc comment cites: the spec block +/// directly above the definition (attributes may sit between). +fn source_ids(text: &str, qualified: &str) -> BTreeSet { + let method = qualified.rsplit("::").next().unwrap_or(qualified); + let needle = format!("fn {method}"); + let mut ids = BTreeSet::new(); + let mut at = 0; + while let Some(rel) = text[at..].find(&needle) { + let pos = at + rel; + let before = text[..pos].chars().next_back(); + let after = text[pos + needle.len()..].chars().next(); + if !before.is_some_and(is_word_char) && !after.is_some_and(is_word_char) { + let line_start = text[..pos].rfind('\n').map(|p| p + 1).unwrap_or(0); + for line in text[..line_start].lines().rev() { + let trimmed = line.trim(); + if let Some(rest) = trimmed.strip_prefix("///") { + for word in rest.split(|c: char| !(c.is_ascii_alphanumeric() || c == '-')) { + if word.starts_with("BS-") { + ids.insert(word.to_string()); + } + } + } else if !trimmed.starts_with("#[") { + break; + } + } + } + at = pos + 1; + } + ids +} + fn claimed_ids(root: &Path) -> (BTreeSet, BTreeSet) { let mut live = BTreeSet::new(); let mut retired = BTreeSet::new(); @@ -1658,13 +1925,18 @@ fn every_claim_is_backed() { let mut laws: BTreeMap = BTreeMap::new(); for (name, law) in law_rows(&read(&root.join("docs/verification.md"))) { - laws.insert(name, law); + record_law(&mut laws, &mut failures, name, law, "docs/verification.md"); } let mut proof_notes = Vec::new(); walk(&root.join("docs/proofs"), "md", &mut proof_notes); for path in &proof_notes { + let source = path + .strip_prefix(&root) + .unwrap_or(path) + .display() + .to_string(); for (name, law) in law_rows(&read(path)) { - laws.entry(name).or_insert(law); + record_law(&mut laws, &mut failures, name, law, &source); } } let laws_md = bookspec_checker::spec_files() @@ -1672,21 +1944,44 @@ fn every_claim_is_backed() { .find(|(name, _)| *name == "laws.md") .map(|(_, text)| text) .expect("bookspec's spec/laws.md"); - let law_numbers: BTreeSet = laws_md - .lines() - .filter_map(|line| { - let cells: Vec<&str> = line.trim().split('|').map(str::trim).collect(); - if cells.len() < 5 { - return None; - } - cells[1].parse::().ok() - }) - .collect(); + let mut law_rules: BTreeMap> = BTreeMap::new(); + for line in laws_md.lines() { + let cells: Vec<&str> = line.trim().split('|').map(str::trim).collect(); + if cells.len() < 5 { + continue; + } + let Ok(number) = cells[1].parse::() else { + continue; + }; + let rules: BTreeSet = cells[3] + .split(|c: char| !(c.is_ascii_alphanumeric() || c == '-')) + .filter(|w| w.starts_with("BS-")) + .map(str::to_string) + .collect(); + law_rules.insert(number, rules); + } + let law_numbers: BTreeSet = law_rules.keys().copied().collect(); assert!(!law_numbers.is_empty(), "bookspec numbers its laws"); + // The kernel sources, by file name, for the spec block above each one. + let mut kernel_texts: BTreeMap = BTreeMap::new(); + let mut kernel_paths = Vec::new(); + walk( + &root.join("crates/ledger-core/src/kernel"), + "rs", + &mut kernel_paths, + ); + for path in &kernel_paths { + if let Some(file) = path.file_name().and_then(|n| n.to_str()) { + kernel_texts.insert(file.to_string(), read(path)); + } + } + let mut kernel_checked = 0usize; let kernel_seen = kernel.len(); let mut seen_exceptions = BTreeSet::new(); + let mut right_law_applied = 0usize; + let mut right_law_skipped = 0usize; for (name, file) in &kernel { let harnesses: Vec<&str> = harness_bodies .iter() @@ -1702,6 +1997,38 @@ fn every_claim_is_backed() { .iter() .filter_map(|h| laws.get(*h)) .find(|n| law_numbers.contains(n)); + // The harness's law row must serve the rule the function's own spec + // block cites: a `fx_booked` harness mapped to law 4 would fail. + let ids = kernel_texts + .get(file) + .map(|text| source_ids(text, name)) + .unwrap_or_default(); + let fn_laws: BTreeSet = harnesses + .iter() + .filter_map(|h| laws.get(*h).copied()) + .filter(|n| law_numbers.contains(n)) + .collect(); + let applicable: Vec = fn_laws + .iter() + .copied() + .filter(|n| law_rules.get(n).is_some_and(|rules| !rules.is_empty())) + .collect(); + if !ids.is_empty() && !applicable.is_empty() { + right_law_applied += 1; + let shared = applicable.iter().any(|n| { + law_rules + .get(n) + .is_some_and(|rules| rules.iter().any(|id| ids.contains(id))) + }); + if !shared { + failures.push(format!( + "kernel `{name}` ({file}) cites {}; its harness law(s) {applicable:?} cite no shared rule", + ids.iter().cloned().collect::>().join(", ") + )); + } + } else { + right_law_skipped += 1; + } let mut lacks = Vec::new(); if harnesses.is_empty() { lacks.push("a Kani harness"); @@ -1805,6 +2132,9 @@ fn every_claim_is_backed() { println!(" {}: {count}", class.name()); } println!("kernel functions checked: {kernel_seen} ({kernel_checked} fully backed)"); + println!( + "harness law matches the function's rule: {right_law_applied} applied, {right_law_skipped} skipped" + ); println!("kernel exceptions: {}", EXCEPTIONS.len()); println!("law rows checked: {law_rows_checked}"); @@ -1907,10 +2237,67 @@ const EXCEPTIONS: &[(&str, &str, &str)] = &[ fn made_up_names_do_not_resolve() { let root = repo_root(); let (defs, bases, all_paths) = main_index(&root); - for token in ["no_such_fn_xyz", "NoSuch.theorem", "books.no_such_tool_xyz"] { + for token in [ + "no_such_fn_xyz", + "NoSuch.theorem", + "books.no_such_tool_xyz", + // An associated item the type does not have. + "Ledger::no_such_method", + // A real item under the wrong type (`target` is the free fn in + // `shares`, not a `Ledger` method). + "Ledger::target", + // A test helper, not a `#[test]` or `proptest!` function. + "arb_cents", + // A product name that is not a registered tool. + "books.add", + // A Lean name that is not audited, with or without the prefix. + "Bookspec.NoSuch.theorem", + ] { assert!( resolve(token, &defs, &bases, &all_paths).is_err(), "made-up name `{token}` must not resolve" ); } + // A directory is not a crate (`tests` resolves only as `mod tests`). + assert!( + !is_crate_name("tests", &defs), + "a directory name must not pass as a crate" + ); +} + +#[test] +fn a_harness_listed_twice_must_agree() { + let mut laws = BTreeMap::new(); + let mut failures = Vec::new(); + record_law(&mut laws, &mut failures, "harness".into(), 4, "a.md"); + record_law(&mut laws, &mut failures, "harness".into(), 4, "b.md"); + assert!(failures.is_empty(), "the same law twice is not a conflict"); + record_law(&mut laws, &mut failures, "harness".into(), 5, "c.md"); + assert_eq!(failures.len(), 1, "two laws for one harness is a conflict"); +} + +#[test] +fn harnesses_resolve_only_as_proofs() { + let root = repo_root(); + let (defs, bases, all_paths) = main_index(&root); + let harness = defs + .harnesses + .iter() + .next() + .expect("the proofs carry harnesses"); + assert_eq!( + resolve(harness, &defs, &bases, &all_paths), + Ok(Class::KaniHarness), + "a harness classifies as a Kani harness" + ); + // `any_proration` is a plain helper in `src/proofs/`, not a proof. + assert!( + !defs.harnesses.contains("any_proration"), + "the helper is not a harness" + ); + assert_ne!( + resolve("any_proration", &defs, &bases, &all_paths).ok(), + Some(Class::KaniHarness), + "a proof helper without `#[kani::proof]` is not a harness" + ); } From 36d1954e5936c15a33001fd41bf18495860ececd Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 21:54:24 -0700 Subject: [PATCH 15/26] docs(proofs): the harness-to-law table format The gate reads every proof note for a machine-readable table pairing a harness with its bookspec law, but the format was undocumented. State it: the first cell is the harness name in backticks, the second a bare integer, extra columns allowed; name the three failures it drives (a kernel function with no row, one harness with two different laws, a law sharing no `BS-` id with the function's `SOURCE:` line). Co-Authored-By: DeepSeek V4.1 Flash --- docs/proofs/README.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/docs/proofs/README.md b/docs/proofs/README.md index 031f5bda..c3c83c0a 100644 --- a/docs/proofs/README.md +++ b/docs/proofs/README.md @@ -29,6 +29,25 @@ instead: - 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 `.rs`), not one file; `just prove-list` prints each harness, its module path, and whether it runs in `prove` or From 08733c6fa2043c5ea2b33aa55c67029d1942f73b Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 21:56:37 -0700 Subject: [PATCH 16/26] test(core): five examples are for options wanderbooks did not pick The bookspec adapter's test pinned the examples for an unpicked option at three (the other option of BS-arap-7, -8 and -9). The bookspec fixes give BS-prepaid-2's equal-months and BS-ledger-20's refuse each an example of their own, so no option-example allow-list grows; wanderbooks picks daily and warn-by-default, so it skips both, and the count is five. The runner and the loader tests still agree on exactly which. Co-Authored-By: Claude Sonnet 5.5 --- crates/ledger-core/tests/bookspec/examples.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/ledger-core/tests/bookspec/examples.rs b/crates/ledger-core/tests/bookspec/examples.rs index 727aae7d..a8e5b0be 100644 --- a/crates/ledger-core/tests/bookspec/examples.rs +++ b/crates/ledger-core/tests/bookspec/examples.rs @@ -156,9 +156,12 @@ pub(crate) fn every_bookspec_example_holds() { 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(), - 3, - "the three unpicked-option examples: {skipped:?}" + 5, + "the five unpicked-option examples: {skipped:?}" ); } From e98b9a63de2ec3ab38d008c1ecb7f5585943e3ca Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 22:33:19 -0700 Subject: [PATCH 17/26] docs(core): every kernel function cites its rule Twenty-six kernel entry points had a harness, a bridge or a law, but no SOURCE line of their own: their doc comments stopped at a sentence, so the traceability gate could not check that the harness's law serves the rule the function claims. Each now carries the house spec block, its source clause naming the rule of the law its harness proves (take is law 10, so BS-statement-3; flip is law 5, so BS-ledger-5). Where a wrapper's law is its inner function's (round_places, round_minor, fx_booked_minor), the source clause says so; part_weight and catch_up had their rule id on a continuation line, so the SOURCE line now names it. Co-Authored-By: DeepSeek V4.1 Flash --- crates/ledger-core/src/kernel/entries.rs | 249 ++++++++++++++++++++++- crates/ledger-core/src/kernel/fx.rs | 10 + crates/ledger-core/src/kernel/round.rs | 20 ++ 3 files changed, 274 insertions(+), 5 deletions(-) diff --git a/crates/ledger-core/src/kernel/entries.rs b/crates/ledger-core/src/kernel/entries.rs index cb40e4a8..c4c1c6a6 100644 --- a/crates/ledger-core/src/kernel/entries.rs +++ b/crates/ledger-core/src/kernel/entries.rs @@ -284,6 +284,15 @@ pub enum LineError { } /// 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, @@ -292,6 +301,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(side: Side, amount: T) -> Option { match side { Side::Debit => Some(amount), @@ -300,6 +320,16 @@ pub fn signed(side: Side, amount: T) -> Option { } /// 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(lines: impl IntoIterator) -> Option<(T, T)> { let mut debits = T::ZERO; let mut credits = T::ZERO; @@ -313,6 +343,16 @@ pub fn totals(lines: impl IntoIterator) -> 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(lines: impl IntoIterator) -> Option { let mut total = T::ZERO; for (side, amount) in lines { @@ -467,6 +507,18 @@ pub fn deductible_amount(shares: &[(T, T)]) -> Option { /// 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(lines: &[(Side, T)]) -> Result<(), LineError> { if lines.len() < 2 { return Err(LineError::TooFewLines); @@ -491,6 +543,13 @@ pub fn check_lines(lines: &[(Side, T)]) -> Result<(), LineError> { /// 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( lines: impl IntoIterator, ) -> Option> { @@ -507,6 +566,16 @@ pub fn movements( /// [`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( lines: &[(K, Side, T)], out: &mut [(K, T)], @@ -527,18 +596,43 @@ pub fn movements_into( /// 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(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((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(account_type: AccountType, movement: T) -> Option { match account_type.normal_side() { Side::Debit => Some(movement), @@ -548,6 +642,17 @@ pub fn normal_balance(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(movement: T) -> Option<(T, T)> { if movement > T::ZERO { Some((movement, T::ZERO)) @@ -561,6 +666,17 @@ pub fn columns(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(movement: T) -> Option<(Side, T)> { if movement > T::ZERO { Some((Side::Credit, movement)) @@ -574,6 +690,15 @@ pub fn closing_line(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(credit: T) -> Option<(Side, T)> { closing_line(credit) } @@ -673,6 +798,17 @@ pub fn payment_bucket(role: PayRole, tag: Tag) -> Option { /// 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(lines: &[(Option, Side, T)]) -> Option<[T; 3]> { let mut out = [T::ZERO; 3]; for &(bucket, side, amount) in lines { @@ -737,6 +873,16 @@ pub fn net_buckets(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(whole: T, parts: &mut [T]) -> Option<()> { let Some((last, rest)) = parts.split_last_mut() else { return Some(()); @@ -919,6 +1065,17 @@ pub struct EntryFlows { /// 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(remaining: T, movement: T) -> Option { let against = movement.checked_neg()?; Some(if remaining > T::ZERO && movement < T::ZERO { @@ -972,6 +1129,18 @@ pub fn apply_cash(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(lines: &[(Flow, Side, T)]) -> Option> { let (cash, moved) = entry_movements(lines)?; flows_of(cash, moved) @@ -980,6 +1149,14 @@ pub fn entry_flows(lines: &[(Flow, Side, T)]) -> Option /// 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(lines: &[(Flow, Side, T)]) -> Option<(T, [T; 3])> { let mut cash = T::ZERO; let mut moved = [T::ZERO; 3]; @@ -999,6 +1176,16 @@ pub fn entry_movements(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(cash: T, moved: [T; 3]) -> Option> { // Balanced lines only: every part below rests on it. let mut total = cash; @@ -1049,6 +1236,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, @@ -1117,6 +1310,17 @@ pub fn constructive( /// 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(debits: T, credits: T, inflow: T, outflow: T) -> Option { let d = debits.checked_sub(outflow)?; let c = credits.checked_sub(inflow)?; @@ -1141,6 +1345,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, @@ -1325,6 +1536,16 @@ pub fn party_target( /// 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: PartyTarget) -> Option> { let neg = |a: T| { if a == T::ZERO { @@ -1461,8 +1682,17 @@ 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. SOURCE: -/// BS-asset-1, BS-prepaid-1 (proration by days; laws 26-28). +/// 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(p: MonthPart) -> Option { if !p.is_valid() { return None; @@ -1649,10 +1879,10 @@ pub fn prorate_by_days( /// ```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 <= @@ -1683,6 +1913,15 @@ pub fn catch_up(scheduled: &[T], posted: &[T]) -> Option { /// 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(scheduled: &[T], posted: &[T], out: &mut [T]) -> Option<()> { if scheduled.len() != posted.len() || out.len() != scheduled.len() { return None; diff --git a/crates/ledger-core/src/kernel/fx.rs b/crates/ledger-core/src/kernel/fx.rs index 0707b630..38e8e9eb 100644 --- a/crates/ledger-core/src/kernel/fx.rs +++ b/crates/ledger-core/src/kernel/fx.rs @@ -106,6 +106,16 @@ pub fn fx_booked(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, diff --git a/crates/ledger-core/src/kernel/round.rs b/crates/ledger-core/src/kernel/round.rs index 03fd69df..d108e20d 100644 --- a/crates/ledger-core/src/kernel/round.rs +++ b/crates/ledger-core/src/kernel/round.rs @@ -69,6 +69,19 @@ pub fn round_step(amount: T, step: T, mode: Rounding) -> Option { /// 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 { 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 Option { match currency.minor_units() { Some(places) => round_places(amount, places, mode), From 4d3444c0af56e50e41aa764b823fbc5f4174cf7f Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 22:34:28 -0700 Subject: [PATCH 18/26] fix(core): the gate walks a whole path and pins its skips Three holes in the traceability gate let a name pass that should not: - an imported uppercase type excused any associated item, so NaiveDate::NoSuchThing resolved. External types' items are now an explicit list of what the claims cite (NaiveDate::MAX only); - only the last two segments of a qualified path were checked, so bogus::Ledger::post_entry and bogus::form1099::untagged_payments resolved. The whole path is walked: an optional crate name, then every module segment against the real module tree (file modules, inline mods, glob re-exports), then the item the module or type defines; - a bare-name call counted in any module, so other::take( looked like take. Only kernel::name( or an imported name( counts now. The right-law check was skippable by omission: a function with no rule or no harness law was silently counted as skipped. Every ordinary function must now be applied, and the skipped set is pinned to the excepted wrappers that lack a law or a rule (SKIPPED), compared exactly. source_ids reads only the spec block's source clause and is keyed by the function's signature, so the free flip and Direction::flip no longer share one id set and fx_booked stops picking BS-ledger-14 from prose. The index also read root.rs badly: strip_code treated the backslash in a raw Windows path (r"\\?\UNC\") as an escape and blanked the rest of the file, so Root (and its adopt) were invisible. Raw strings are parsed as raw strings now; Root::adopt resolves through its own impl, not through the imported-type excuse that used to hide the bug. Co-Authored-By: DeepSeek V4.1 Flash --- .../tests/bookspec/traceability.rs | 684 +++++++++++++----- 1 file changed, 491 insertions(+), 193 deletions(-) diff --git a/crates/ledger-core/tests/bookspec/traceability.rs b/crates/ledger-core/tests/bookspec/traceability.rs index a51682eb..b2b71b48 100644 --- a/crates/ledger-core/tests/bookspec/traceability.rs +++ b/crates/ledger-core/tests/bookspec/traceability.rs @@ -21,17 +21,23 @@ //! Tokens that are plainly values (a quoted option word, a setting value, //! a journal event, a tool name, an illustrative amount) are classified by //! narrow, explicit rules below and counted, so the gate says how much it -//! actually resolved. Every `**bookspec:**` id must be a live record (a -//! retired one is written `**retired bookspec:**`); every `WB-` id is -//! unique. +//! actually resolved. A product surface is a registered tool name, or an +//! exact string literal the source declares. Every `**bookspec:**` id must +//! be a live record (a retired one is written `**retired bookspec:**`); +//! every `WB-` id is unique. //! //! It also checks every `pub fn` in `crates/ledger-core/src/kernel/*.rs`: //! a Kani harness calls it, a bridge property in `tests/kernel_bridge/` -//! calls it, and one of its harnesses carries a numbered law that is a -//! row of bookspec's `spec/laws.md`. The functions that are wrappers or -//! enum maps with no independent harness, bridge or law are named in +//! calls it, one of its harnesses carries a numbered law that is a row of +//! bookspec's `spec/laws.md`, and the source clause of its own spec block +//! cites a rule that law serves. The functions that are wrappers or enum +//! maps with no independent harness, bridge or law are named in //! [`EXCEPTIONS`], with what each lacks and why; its length is pinned so -//! the list changes only on purpose. +//! the list changes only on purpose. A function the gate cannot apply the +//! right-law check to (because it has no harness law, or cites no rule) is +//! recorded, and the set of those is pinned too: it must be exactly the +//! excepted wrappers [`SKIPPED`] names, never a hole ordinary functions +//! fall through. //! //! Finally, every law row of `spec/laws.md` that cites a rule wanderbooks //! claims names Lean theorems that are all audited, or says `none —` with @@ -107,6 +113,48 @@ fn walk(dir: &Path, ext: &str, out: &mut Vec) { } } +/// Where a raw string starting at `i` ends (`r"…"`, `r#"…"#`, `br"…"`), +/// or `None` when `i` is not a raw string. Without this, a backslash in a +/// Windows path inside `r"…"` reads as an escape and blanks the rest of +/// the file. +fn raw_string_end(chars: &[char], i: usize) -> Option { + if i > 0 && is_word_char(chars[i - 1]) { + return None; + } + let mut j = i; + if chars.get(j) == Some(&'b') { + j += 1; + } + if chars.get(j) != Some(&'r') { + return None; + } + j += 1; + let mut hashes = 0usize; + while chars.get(j) == Some(&'#') { + hashes += 1; + j += 1; + } + if chars.get(j) != Some(&'"') { + return None; + } + j += 1; + while j < chars.len() { + if chars[j] == '"' { + let mut k = j + 1; + let mut seen = 0usize; + while seen < hashes && chars.get(k) == Some(&'#') { + seen += 1; + k += 1; + } + if seen == hashes { + return Some(k); + } + } + j += 1; + } + Some(chars.len()) +} + /// The source with comments and string/char literals blanked, so a word in /// a comment or a string is never mistaken for a definition. fn strip_code(text: &str) -> String { @@ -114,7 +162,9 @@ fn strip_code(text: &str) -> String { let mut out = String::with_capacity(text.len()); let mut i = 0; while i < chars.len() { - if chars[i] == '/' && chars.get(i + 1) == Some(&'/') { + if let Some(end) = raw_string_end(&chars, i) { + i = end; + } else if chars[i] == '/' && chars.get(i + 1) == Some(&'/') { while i < chars.len() && chars[i] != '\n' { i += 1; } @@ -427,7 +477,12 @@ fn struct_fields(code: &str, name: &str) -> Vec { /// Enum variants and struct fields in `code`, for definitions outside the /// crate's `src` (an integration test's own model types). -fn collect_types(code: &str, items: &mut BTreeSet, qualified: &mut BTreeSet) { +fn collect_types( + code: &str, + items: &mut BTreeSet, + qualified: &mut BTreeSet, + types: &mut BTreeSet, +) { let chars: Vec = code.chars().collect(); let mut i = 0; while i < chars.len() { @@ -442,6 +497,7 @@ fn collect_types(code: &str, items: &mut BTreeSet, qualified: &mut BTree if word == "enum" || word == "struct" { let j = skip_space(&chars, end); if let Some((name, _)) = word_at(&chars, j) { + types.insert(name.clone()); if word == "enum" { for variant in enum_variants(code, &name) { qualified.insert(format!("{name}::{variant}")); @@ -495,8 +551,13 @@ struct Definitions { /// The exact `Type::item` names: an impl's functions, an enum's /// variants, an impl's associated `const`s and types. qualified: BTreeSet, - /// The items defined in each module's own file (a directory module - /// keeps its submodules' items too, which is what it re-exports). + /// Every real module's full path (`crate::a::b`): a file module + /// (`src/a/b.rs`, `src/a/b/mod.rs`, the crate root) and every inline + /// `mod b { … }`. + modules: BTreeSet, + /// The items defined directly in each module, keyed by that full path. + /// A glob re-export (`pub use entries::*;`) brings a module's items + /// into the re-exporting one, as Rust does. module_items: BTreeMap>, /// Type names defined under `crates/*/src`. types: BTreeSet, @@ -601,38 +662,145 @@ fn package_name(text: &str) -> Option { None } -/// The module(s) a source file defines items for: its own file stem (or -/// `mod.rs`'s directory), and every enclosing directory that is a module -/// root, because a directory module re-exports its submodules' items. -fn module_keys(path: &Path) -> Vec { - let mut keys = Vec::new(); - let file = path.file_name().and_then(|n| n.to_str()).unwrap_or(""); - if file == "mod.rs" { - if let Some(dir) = path - .parent() - .and_then(|p| p.file_name()) - .and_then(|n| n.to_str()) - { - keys.push(dir.to_string()); - } - } else if file != "lib.rs" { - if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) { - keys.push(stem.to_string()); - } +/// The module a source file is, as segments below its crate root: `lib.rs` +/// and `main.rs` are the root, `a.rs` and `a/mod.rs` are `a`, `a/b.rs` is +/// `a::b`. +fn module_path_of(path: &Path, src: &Path) -> Vec { + let Ok(rel) = path.strip_prefix(src) else { + return Vec::new(); + }; + let mut parts: Vec = rel + .components() + .map(|c| c.as_os_str().to_string_lossy().into_owned()) + .collect(); + let Some(last) = parts.pop() else { + return Vec::new(); + }; + if last == "lib.rs" || last == "main.rs" { + return Vec::new(); } - let mut dir = path.parent(); - while let Some(d) = dir { - if d.file_name().is_some_and(|n| n == "src") { - break; + let Some(stem) = last.strip_suffix(".rs") else { + return Vec::new(); + }; + if stem != "mod" { + parts.push(stem.to_string()); + } + parts +} + +/// Record every item of `code`, the body of module `path` in `file`: +/// functions, types, variants' containers, `const`s, macros and submodule +/// names, each in its module. An inline `mod b { … }` is a module of its +/// own, recursed into with `path::b`; a `use …::*` is remembered so a glob +/// re-export can be applied once every module is known. +fn scan_module( + code: &str, + path: &str, + file: &Path, + defs: &mut Definitions, + enums: &mut Vec<(PathBuf, String)>, + structs: &mut Vec<(PathBuf, String)>, + globs: &mut Vec<(String, String)>, +) { + let chars: Vec = code.chars().collect(); + let mut i = 0; + while i < chars.len() { + if !(chars[i].is_ascii_alphabetic() || chars[i] == '_') { + i += 1; + continue; } - if d.join("mod.rs").is_file() { - if let Some(name) = d.file_name().and_then(|n| n.to_str()) { - keys.push(name.to_string()); + let Some((word, end)) = word_at(&chars, i) else { + i += 1; + continue; + }; + let mut after = end; + match word.as_str() { + "mod" => { + let j = skip_space(&chars, end); + if let Some((name, name_end)) = word_at(&chars, j) { + defs.items.insert(name.clone()); + defs.module_items + .entry(path.to_string()) + .or_default() + .insert(name.clone()); + let mut k = skip_space(&chars, name_end); + while k < chars.len() && chars[k] != '{' && chars[k] != ';' { + k += 1; + } + if chars.get(k) == Some(&'{') { + if let Some(close) = matching_brace(&chars, k, ('{', '}')) { + let full = format!("{path}::{name}"); + defs.modules.insert(full.clone()); + let body: String = chars[k + 1..close].iter().collect(); + scan_module(&body, &full, file, defs, enums, structs, globs); + after = close + 1; + } + } + } } + "use" => { + let mut k = i; + while k < chars.len() && chars[k] != ';' { + k += 1; + } + let decl: String = chars[i..k].iter().collect(); + if let Some(target) = glob_use_target(&decl) { + globs.push((path.to_string(), target)); + } + after = k.min(chars.len()); + } + "fn" | "struct" | "enum" | "union" | "trait" | "type" | "const" | "static" => { + let j = skip_space(&chars, end); + if let Some((name, _)) = word_at(&chars, j) { + if word == "enum" { + enums.push((file.to_path_buf(), name.clone())); + } + if word == "struct" { + structs.push((file.to_path_buf(), name.clone())); + } + if matches!( + word.as_str(), + "struct" | "enum" | "union" | "trait" | "type" + ) { + defs.types.insert(name.clone()); + } + defs.items.insert(name.clone()); + defs.module_items + .entry(path.to_string()) + .or_default() + .insert(name); + } + } + "macro_rules" => { + let mut j = skip_space(&chars, end); + if chars.get(j) == Some(&'!') { + j = skip_space(&chars, j + 1); + if let Some((name, _)) = word_at(&chars, j) { + defs.items.insert(name.clone()); + defs.module_items + .entry(path.to_string()) + .or_default() + .insert(name); + } + } + } + _ => {} } - dir = d.parent(); + i = after.max(end); } - keys +} + +/// The target of a glob `use` (`use a::b::*;` names `a::b`), or `None` for +/// any other import. +fn glob_use_target(decl: &str) -> Option { + let decl = decl.trim_start().strip_prefix("use ")?.trim(); + let target = decl.strip_suffix("::*")?.trim(); + // `super` and `self` are relative to the inline test modules, whose + // items no claim names; resolving them would need the parent chain. + if target.is_empty() || target == "super" || target == "self" { + return None; + } + Some(target.to_string()) } /// Test names: a `#[test]` fn or a function inside a `proptest!` block. @@ -717,12 +885,19 @@ fn collect_tool_names(root: &Path, out: &mut BTreeSet) { fn build_definitions(root: &Path) -> Definitions { let mut defs = Definitions::default(); - // Crate names: the workspace root, `fuzz`, and each crate's package. - let mut manifests = vec![root.join("Cargo.toml"), root.join("fuzz/Cargo.toml")]; + // Crate names and directories: each crate under `crates/`, the + // workspace root, and `fuzz`. + let mut crate_dirs: Vec<(PathBuf, String)> = Vec::new(); for entry in std::fs::read_dir(root.join("crates")).expect("crates") { - manifests.push(entry.expect("a crate").path().join("Cargo.toml")); + let dir = entry.expect("a crate").path(); + if let Ok(text) = std::fs::read_to_string(dir.join("Cargo.toml")) { + if let Some(name) = package_name(&text) { + defs.crates.insert(name.clone()); + crate_dirs.push((dir, name)); + } + } } - for manifest in manifests { + for manifest in [root.join("Cargo.toml"), root.join("fuzz/Cargo.toml")] { if let Ok(text) = std::fs::read_to_string(&manifest) { if let Some(name) = package_name(&text) { defs.crates.insert(name); @@ -731,108 +906,99 @@ fn build_definitions(root: &Path) -> Definitions { } collect_tool_names(root, &mut defs.product_surfaces); - let mut src_files = Vec::new(); - for entry in std::fs::read_dir(root.join("crates")).expect("crates") { - let crate_dir = entry.expect("a crate").path(); - let src = crate_dir.join("src"); - if src.is_dir() { - walk(&src, "rs", &mut src_files); - } - } - src_files.sort(); let proofs = root.join("crates/ledger-core/src/proofs"); + let mut src_files = Vec::new(); + let mut src_texts: BTreeMap = BTreeMap::new(); let mut enums = Vec::new(); let mut structs = Vec::new(); - for path in &src_files { - let text = read(path); - let code = strip_code(&text); - defs.surface.push_str(&text); - defs.surface.push('\n'); - for literal in literals(&text) { - defs.literals.insert(literal); - } - // A proof harness is never a plain Rust item: it resolves only as a - // `#[kani::proof]` fn, or deleting the attribute would go unseen. - if path.starts_with(&proofs) { + let mut globs = Vec::new(); + for (crate_dir, crate_name) in &crate_dirs { + let src = crate_dir.join("src"); + if !src.is_dir() { continue; } - collect_imports(&code, &mut defs.imports); - let keys = module_keys(path); - // Keywords and names. - let chars: Vec = code.chars().collect(); - let mut i = 0; - while i < chars.len() { - if !(chars[i].is_ascii_alphabetic() || chars[i] == '_') { - i += 1; - continue; + // The crate root is a module even when nothing but `mod` lines + // live there. + defs.modules.insert(crate_name.clone()); + let mut files = Vec::new(); + walk(&src, "rs", &mut files); + files.sort(); + for path in files { + // Read each file once; later passes reuse this text. + let text = read(&path); + let code = strip_code(&text); + defs.surface.push_str(&text); + defs.surface.push('\n'); + for literal in literals(&text) { + defs.literals.insert(literal); } - let Some((word, end)) = word_at(&chars, i) else { - i += 1; - continue; + // A proof harness is never a plain Rust item: it resolves only + // as a `#[kani::proof]` fn, or deleting the attribute would go + // unseen. + if !path.starts_with(&proofs) { + collect_imports(&code, &mut defs.imports); + let segments = module_path_of(&path, &src); + let module = if segments.is_empty() { + crate_name.clone() + } else { + format!("{crate_name}::{}", segments.join("::")) + }; + defs.modules.insert(module.clone()); + scan_module( + &code, + &module, + &path, + &mut defs, + &mut enums, + &mut structs, + &mut globs, + ); + // Methods, associated items and variants, qualified by + // their type. + for (start, end, ty) in impl_ranges(&code) { + collect_impl_qualified(&code[start..end], &ty, &mut defs.qualified); + } + } + src_texts.insert(path.clone(), text); + src_files.push(path); + } + } + // A glob re-export brings a module's items into the re-exporting one, + // as Rust does: `pub use entries::*;` names a sibling, and + // `crate::a::b` is absolute. Three passes reach a re-export chain. + for _ in 0..3 { + for (module, target) in &globs { + let krate = module.split("::").next().unwrap_or(""); + let resolved = match target.strip_prefix("crate::") { + Some(rest) => format!("{krate}::{rest}"), + None if target.contains("::") => target.clone(), + None => format!("{module}::{target}"), }; - match word.as_str() { - "fn" | "struct" | "enum" | "union" | "trait" | "type" | "mod" | "const" - | "static" => { - let j = skip_space(&chars, end); - if let Some((name, _)) = word_at(&chars, j) { - if word == "enum" { - enums.push((path.clone(), name.clone())); - } - if word == "struct" { - structs.push((path.clone(), name.clone())); - } - if matches!( - word.as_str(), - "struct" | "enum" | "union" | "trait" | "type" - ) { - defs.types.insert(name.clone()); - } - defs.items.insert(name.clone()); - for key in &keys { - defs.module_items - .entry(key.clone()) - .or_default() - .insert(name.clone()); - } - } - } - "macro_rules" => { - let mut j = skip_space(&chars, end); - if chars.get(j) == Some(&'!') { - j = skip_space(&chars, j + 1); - if let Some((name, _)) = word_at(&chars, j) { - defs.items.insert(name.clone()); - for key in &keys { - defs.module_items - .entry(key.clone()) - .or_default() - .insert(name.clone()); - } - } - } - } - _ => {} + if let Some(items) = defs.module_items.get(&resolved).cloned() { + defs.module_items + .entry(module.clone()) + .or_default() + .extend(items); } - i = end; - } - // Methods, associated items and variants, qualified by their type. - for (start, end, ty) in impl_ranges(&code) { - collect_impl_qualified(&code[start..end], &ty, &mut defs.qualified); } } - for (path, name) in enums { - let code = strip_code(&read(&path)); - for variant in enum_variants(&code, &name) { - defs.items.insert(variant.clone()); - defs.qualified.insert(format!("{name}::{variant}")); + for (path, name) in &enums { + if let Some(text) = src_texts.get(path) { + let code = strip_code(text); + for variant in enum_variants(&code, name) { + defs.items.insert(variant.clone()); + defs.qualified.insert(format!("{name}::{variant}")); + } } } - for (path, name) in structs { - let code = strip_code(&read(&path)); - for field in struct_fields(&code, &name) { - defs.items.insert(field.clone()); - // A public field is the type's item too (`Iif::changes`). - defs.qualified.insert(format!("{name}::{field}")); + for (path, name) in &structs { + if let Some(text) = src_texts.get(path) { + let code = strip_code(text); + for field in struct_fields(&code, name) { + defs.items.insert(field.clone()); + // A public field is the type's item too (`Iif::changes`). + defs.qualified.insert(format!("{name}::{field}")); + } } } @@ -847,13 +1013,14 @@ fn build_definitions(root: &Path) -> Definitions { } test_files.sort(); for path in &test_files { - let code = strip_code(&read(path)); - collect_types(&code, &mut defs.items, &mut defs.qualified); + let text = read(path); + let code = strip_code(&text); + collect_types(&code, &mut defs.items, &mut defs.qualified, &mut defs.types); collect_imports(&code, &mut defs.imports); collect_test_names(&code, &mut defs.tests); } for path in &src_files { - let code = strip_code(&read(path)); + let code = strip_code(src_texts.get(path).expect("read above")); collect_test_names(&code, &mut defs.tests); } @@ -980,7 +1147,7 @@ fn collect_bodies_with_attribute(code: &str, attr: &str) -> Vec<(String, String) /// Every `pub fn` in `crates/ledger-core/src/kernel/*.rs`, qualified by /// its impl (`Type::method`). -fn kernel_functions(root: &Path) -> Vec<(String, String)> { +fn kernel_functions(root: &Path) -> Vec<(String, String, String)> { let mut files = Vec::new(); walk( &root.join("crates/ledger-core/src/kernel"), @@ -1020,7 +1187,7 @@ fn kernel_functions(root: &Path) -> Vec<(String, String)> { if let Some((kw, kw_end)) = word_at(&chars, j) { if kw == "fn" { let k = skip_space(&chars, kw_end); - if let Some((name, _)) = word_at(&chars, k) { + if let Some((name, name_end)) = word_at(&chars, k) { let offset = code[..i].chars().count(); let ty = impls .iter() @@ -1030,7 +1197,28 @@ fn kernel_functions(root: &Path) -> Vec<(String, String)> { Some(ty) => format!("{ty}::{name}"), None => name, }; - out.push((qualified, file.clone())); + // The exact signature, `pub` through the body's `{`: + // two items may share a name (`flip`), and the + // signature is what tells their doc blocks apart. + let mut body = name_end; + let mut after = skip_space(&chars, body); + if chars.get(after) == Some(&'<') { + if let Some(gt) = matching_brace(&chars, after, ('<', '>')) { + after = gt + 1; + } + } + after = skip_space(&chars, after); + if chars.get(after) == Some(&'(') { + if let Some(close) = matching_brace(&chars, after, ('(', ')')) { + body = close + 1; + } + } + let mut brace = body; + while brace < chars.len() && chars[brace] != '{' && chars[brace] != ';' { + brace += 1; + } + let signature: String = chars[i..brace].iter().collect(); + out.push((qualified, file.clone(), signature)); } } } @@ -1065,14 +1253,29 @@ fn contains_qualified_call(body: &str, name: &str) -> bool { } /// A bare `name(` that is neither a method call (`.name(`) nor the tail of -/// a longer identifier; a qualified call (`::name(`) counts. +/// a longer identifier. A qualified call counts only as `kernel::name(`: +/// another module's `take(` is not the kernel's. fn contains_bare_call(body: &str, name: &str) -> bool { let needle = format!("{name}("); let mut at = 0; while let Some(rel) = body[at..].find(&needle) { let pos = at + rel; - let before = body[..pos].chars().next_back(); - if !before.is_some_and(is_word_char) && before != Some('.') { + let before = &body[..pos]; + let counts = match before.chars().next_back() { + None => true, + Some('.') => false, + Some(c) if is_word_char(c) => false, + Some(':') => { + let qualifier = before + .trim_end_matches(':') + .rsplit(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .next() + .unwrap_or(""); + qualifier == "kernel" + } + Some(_) => true, + }; + if counts { return true; } at = pos + 1; @@ -1131,7 +1334,7 @@ fn resolve( if !exists { return Err(format!("path {head} does not exist")); } - return resolve(item, defs, bases, all_paths); + return resolve(item, &defs, &bases, &all_paths); } } if is_path_like(token) { @@ -1163,7 +1366,7 @@ fn resolve( if item.is_empty() { continue; } - classes.push(resolve(&format!("{prefix}{item}"), defs, bases, all_paths)?); + classes.push(resolve(&format!("{prefix}{item}"), &defs, &bases, &all_paths)?); } if classes.is_empty() { return Err(format!("empty brace group {token}")); @@ -1190,7 +1393,7 @@ fn resolve( return Ok(Class::LeanTheorem); } if token.contains("::") { - return resolve_qualified(token, defs, bases, all_paths); + return resolve_qualified(token, &defs, &bases, &all_paths); } // A harness before an item: a proof function is never an ordinary item, // so deleting its `#[kani::proof]` attribute leaves the claim unbacked. @@ -1244,12 +1447,42 @@ fn resolve( Err(format!("{token} names no known item")) } -/// A `::` path: the last two segments name an item its container defines. -/// -/// A capitalized head is a type, so `Type::item` must be an impl function, -/// an enum variant, or an associated `const`/type. A lowercase head is a -/// module, so `module::item` must be defined in that module's own file. A -/// leading `crate` or crate name is dropped first. +/// The associated items of types the tree does not define, which the +/// claims cite today. Everything else is checked against a type's own +/// items; a new name here is a deliberate addition, not a way past the +/// check. +const EXTERNAL_ITEMS: &[&str] = &["NaiveDate::MAX"]; + +/// The package name a token names (a citation writes `ledger_core` for the +/// `ledger-core` package). +fn canonical_crate<'a>(token: &str, defs: &'a Definitions) -> Option<&'a str> { + let dashed = token.replace('_', "-"); + defs.crates + .iter() + .find(|name| **name == token || **name == dashed) + .map(String::as_str) +} + +/// True when `token` names a type the source defines, or an uppercase +/// imported type (whose items are then the explicit [`EXTERNAL_ITEMS`]). +fn is_typeish(token: &str, defs: &Definitions) -> bool { + defs.types.contains(token) + || (defs.imports.contains(token) + && token.chars().next().is_some_and(|c| c.is_ascii_uppercase())) +} + +/// True when `parts` names a real module path of `krate`. +fn module_exists(krate: &str, parts: &[&str], defs: &Definitions) -> bool { + let full = std::iter::once(krate) + .chain(parts.iter().copied()) + .collect::>() + .join("::"); + defs.modules.contains(&full) +} + +/// A `::` path, walked whole: an optional crate name, then a module path +/// whose every segment is a real module, then the type or item defined +/// there. fn resolve_qualified( token: &str, defs: &Definitions, @@ -1260,40 +1493,65 @@ fn resolve_qualified( if matches!(segments.first(), Some(&"crate") | Some(&"self")) { segments.remove(0); } - while segments.first().is_some_and(|s| is_crate_name(s, defs)) { - segments.remove(0); + let mut krate: Option<&str> = None; + if let Some(first) = segments.first().copied() { + if let Some(found) = canonical_crate(first, defs) { + krate = Some(found); + segments.remove(0); + } } let Some(item) = segments.last().copied() else { return Err(format!("{token} names no item")); }; if segments.len() == 1 { - return resolve(item, defs, bases, all_paths); + return resolve(item, &defs, &bases, &all_paths); } let container = segments[segments.len() - 2]; - let head_uppercase = container - .chars() - .next() - .is_some_and(|c| c.is_ascii_uppercase()); - if head_uppercase { + let candidates: Vec<&str> = match krate { + Some(name) => vec![name], + None => defs.crates.iter().map(String::as_str).collect(), + }; + if is_typeish(container, defs) { + // The segments before the type must still be a real module path: + // `bogus::Ledger::post_entry` is no path to `Ledger`. + let modules = &segments[..segments.len() - 2]; + if !modules.is_empty() && !candidates.iter().any(|k| module_exists(k, modules, defs)) { + return Err(format!( + "{token}: `{}` is no module path", + modules.join("::") + )); + } let qualified = format!("{container}::{item}"); if defs.qualified.contains(&qualified) { return Ok(Class::RustItem); } - // An external type's associated item (`NaiveDate::MAX`): the type - // is imported, not defined in the tree, so its items are not here. - if !defs.types.contains(container) && defs.imports.contains(container) { + if !defs.types.contains(container) && EXTERNAL_ITEMS.contains(&qualified.as_str()) { return Ok(Class::RustItem); } return Err(format!("{token} names no `{qualified}`")); } - if defs - .module_items - .get(container) - .is_some_and(|items| items.contains(item)) - { - return Ok(Class::RustItem); + // Every segment but the item is a module of the crate, in order. + let modules = &segments[..segments.len() - 1]; + for krate in &candidates { + if !module_exists(krate, modules, defs) { + continue; + } + let full = std::iter::once(*krate) + .chain(modules.iter().copied()) + .collect::>() + .join("::"); + if defs + .module_items + .get(&full) + .is_some_and(|items| items.contains(item)) + { + return Ok(Class::RustItem); + } } - Err(format!("{token} names no item in module `{container}`")) + Err(format!( + "{token}: `{}` is no module path or the item is not there", + modules.join("::") + )) } fn resolve_wildcard(token: &str, defs: &Definitions) -> Result { @@ -1515,33 +1773,31 @@ fn record_law( } } -/// The `BS-` ids a kernel function's own doc comment cites: the spec block -/// directly above the definition (attributes may sit between). -fn source_ids(text: &str, qualified: &str) -> BTreeSet { - let method = qualified.rsplit("::").next().unwrap_or(qualified); - let needle = format!("fn {method}"); +/// The `BS-` ids on the source-citation line of the spec block directly +/// above a kernel function's signature (attributes may sit between). Only +/// that line is read, never every `BS-` mention in the block: prose may +/// cite a rule the function does not serve (`fx_booked` mentions +/// `BS-ledger-14` as the CHOICE it follows). The signature identifies the +/// item, so the free `flip` and `Direction::flip` read their own blocks. +fn source_ids(text: &str, signature: &str) -> BTreeSet { let mut ids = BTreeSet::new(); - let mut at = 0; - while let Some(rel) = text[at..].find(&needle) { - let pos = at + rel; - let before = text[..pos].chars().next_back(); - let after = text[pos + needle.len()..].chars().next(); - if !before.is_some_and(is_word_char) && !after.is_some_and(is_word_char) { - let line_start = text[..pos].rfind('\n').map(|p| p + 1).unwrap_or(0); - for line in text[..line_start].lines().rev() { - let trimmed = line.trim(); - if let Some(rest) = trimmed.strip_prefix("///") { - for word in rest.split(|c: char| !(c.is_ascii_alphanumeric() || c == '-')) { - if word.starts_with("BS-") { - ids.insert(word.to_string()); - } + let Some(pos) = text.find(signature) else { + return ids; + }; + let line_start = text[..pos].rfind('\n').map(|p| p + 1).unwrap_or(0); + for line in text[..line_start].lines().rev() { + let trimmed = line.trim(); + if let Some(rest) = trimmed.strip_prefix("///") { + if let Some(at) = rest.find("SOURCE:") { + for word in rest[at..].split(|c: char| !(c.is_ascii_alphanumeric() || c == '-')) { + if word.starts_with("BS-") { + ids.insert(word.to_string()); } - } else if !trimmed.starts_with("#[") { - break; } } + } else if !trimmed.starts_with("#[") { + break; } - at = pos + 1; } ids } @@ -1982,7 +2238,8 @@ fn every_claim_is_backed() { let mut seen_exceptions = BTreeSet::new(); let mut right_law_applied = 0usize; let mut right_law_skipped = 0usize; - for (name, file) in &kernel { + let mut right_law_skipped_names = BTreeSet::new(); + for (name, file, signature) in &kernel { let harnesses: Vec<&str> = harness_bodies .iter() .filter(|(_, body)| calls(body, name)) @@ -2001,7 +2258,7 @@ fn every_claim_is_backed() { // block cites: a `fx_booked` harness mapped to law 4 would fail. let ids = kernel_texts .get(file) - .map(|text| source_ids(text, name)) + .map(|text| source_ids(text, signature)) .unwrap_or_default(); let fn_laws: BTreeSet = harnesses .iter() @@ -2028,6 +2285,7 @@ fn every_claim_is_backed() { } } else { right_law_skipped += 1; + right_law_skipped_names.insert(name.clone()); } let mut lacks = Vec::new(); if harnesses.is_empty() { @@ -2064,7 +2322,7 @@ fn every_claim_is_backed() { } for (name, _, _) in EXCEPTIONS { assert!( - kernel.iter().any(|(fn_name, _)| fn_name == name), + kernel.iter().any(|(fn_name, _, _)| fn_name == name), "excepted kernel function {name} does not exist; the list is stale" ); assert!( @@ -2077,6 +2335,20 @@ fn every_claim_is_backed() { 14, "the kernel exception list changes only on purpose" ); + // No ordinary function may fall through the right-law check: the + // skipped set is exactly these wrappers, each excepted because its + // law is its inner function's (or it has no law at all). + let expected_skips: BTreeSet = SKIPPED.iter().map(|s| (*s).to_string()).collect(); + assert_eq!( + right_law_skipped_names, expected_skips, + "the set of kernel functions the right-law check cannot apply to changed" + ); + for name in SKIPPED { + assert!( + EXCEPTIONS.iter().any(|(excepted, _, _)| excepted == name), + "skipped kernel function {name} is not excepted; it must cite its rule" + ); + } // Every law row that cites a claimed rule names audited theorems. let (live_ids, _) = claimed_ids(&root); @@ -2135,6 +2407,14 @@ fn every_claim_is_backed() { println!( "harness law matches the function's rule: {right_law_applied} applied, {right_law_skipped} skipped" ); + println!( + " skipped (excepted, no law or no rule): {}", + right_law_skipped_names + .iter() + .cloned() + .collect::>() + .join(", ") + ); println!("kernel exceptions: {}", EXCEPTIONS.len()); println!("law rows checked: {law_rows_checked}"); @@ -2233,6 +2513,24 @@ const EXCEPTIONS: &[(&str, &str, &str)] = &[ ), ]; +/// The kernel functions the right-law check cannot apply to, pinned +/// exactly: each is excepted above, and lacks either a harness law or a +/// cited rule for one. `movements` and `reversal` allocate, so every +/// harness proves their fixed-array helper; `round_places`, `round_minor` +/// and `fx_booked_minor` are Decimal wrappers whose law is the inner +/// function's; `Direction::key` is a wire name and `MonthPart::is_valid` a +/// range predicate, with no law at all. A new name here is a deliberate +/// widening, never a silent hole. +const SKIPPED: &[&str] = &[ + "movements", + "reversal", + "Direction::key", + "MonthPart::is_valid", + "round_places", + "round_minor", + "fx_booked_minor", +]; + #[test] fn made_up_names_do_not_resolve() { let root = repo_root(); From c784bfe1d4c98ab3f8aa533cc6ecd8e160addb79 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 22:34:51 -0700 Subject: [PATCH 19/26] test(core): the gate's call and field probes The stricter call matcher and the field check were fixed in code but had no self-test, so a regression could hide behind the gate's own pass. These probe them directly: x.take(5), a bare mention and other::take( are not calls, kernel::take( is; Iif::form_4797 and TaxSummary::changes are the other type's items and must not resolve, while each type's own fields and methods do. The made-up-name probe also gains NaiveDate::NoSuchThing and the two bogus prefixes, and the `tests` probe now says plainly that bare `tests` resolves as a Rust item (`mod tests`), not as a crate. Co-Authored-By: DeepSeek V4.1 Flash --- .../tests/bookspec/traceability.rs | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/crates/ledger-core/tests/bookspec/traceability.rs b/crates/ledger-core/tests/bookspec/traceability.rs index b2b71b48..a3ba16fc 100644 --- a/crates/ledger-core/tests/bookspec/traceability.rs +++ b/crates/ledger-core/tests/bookspec/traceability.rs @@ -2563,6 +2563,54 @@ fn made_up_names_do_not_resolve() { ); } +/// `calls` finds a call, never a mention: a method call, a bare mention, or +/// another module's function of the same name is not the kernel's call. +#[test] +fn calls_finds_a_call_not_a_mention() { + assert!( + !calls("x.take(5)", "take"), + "a method call is not the kernel's" + ); + assert!(!calls("take", "take"), "a bare mention is not a call"); + assert!( + !calls("other::take(5)", "take"), + "another module's take is not the kernel's" + ); + assert!(calls("kernel::take(5)", "take"), "a kernel call counts"); + assert!(calls("take(5)", "take"), "an imported bare call counts"); + assert!(calls("kernel::Direction::flip(d)", "Direction::flip")); + assert!( + !calls("kernel::Direction::flip(d)", "flip"), + "a type's flip is not the free flip" + ); +} + +/// A field belongs to its own type, and a method to its own type: a field +/// of `Iif` never backs `TaxSummary::…`, nor the reverse. +#[test] +fn a_field_belongs_to_its_own_type() { + let root = repo_root(); + let (defs, bases, all_paths) = main_index(&root); + for token in [ + "Iif::changes", + "Iif::receivable_payable", + "Iif::warnings", + "TaxSummary::form_4797", + ] { + assert_eq!( + resolve(token, &defs, &bases, &all_paths), + Ok(Class::RustItem), + "`{token}` is a real item of its type" + ); + } + for token in ["Iif::form_4797", "TaxSummary::changes"] { + assert!( + resolve(token, &defs, &bases, &all_paths).is_err(), + "`{token}` is a field of the other type and must not resolve" + ); + } +} + #[test] fn a_harness_listed_twice_must_agree() { let mut laws = BTreeMap::new(); From 176b59cc4f309bb8ed11deee194e6a8b3ef37c4f Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 22:35:10 -0700 Subject: [PATCH 20/26] fix(proofs): part_weight is a lemma for laws 26-28 Law 26 is that the parts of a proration sum to its total, which prorate_parts_sum_to_total proves. part_weight_is_days_of_the_month proves the weight formula (days x monthly rate), which is law 27's statement. Its row is numbered 27 now, in both tables, with a note that it is a lemma for laws 26-28 rather than a restatement of law 26. Co-Authored-By: DeepSeek V4.1 Flash --- docs/proofs/entries.md | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/docs/proofs/entries.md b/docs/proofs/entries.md index cb5c5285..86efac50 100644 --- a/docs/proofs/entries.md +++ b/docs/proofs/entries.md @@ -16,7 +16,13 @@ the exception list before. | Harness | Law | Bounds | |---|---|---| | `direction_of_is_the_sign` | 23 | any `i64` amount; all three signs covered | -| `part_weight_is_days_of_the_month` | 26 | `days` and `month_days` 0..=40; valid, partial, whole and invalid parts 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`): @@ -24,7 +30,7 @@ traceability gate, `crates/ledger-core/tests/bookspec/traceability.rs`): | Harness | Law | |---|---| | `direction_of_is_the_sign` | 23 | -| `part_weight_is_days_of_the_month` | 26 | +| `part_weight_is_days_of_the_month` | 27 | Times: measured alone with `cargo kani -p ledger-core --exact --harness proofs::` on 2026-11-08: @@ -45,4 +51,5 @@ verification, 3 covers, build included). 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. +proration charges of laws 26-28 are computed from, its harness numbered +for the law it restates most closely (27). From 5a029f3cab89c70420280a916d535557d095869f Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 22:35:23 -0700 Subject: [PATCH 21/26] test(core): the reversal bridge reaches the refusal reverse_target_agrees claimed to compare refusal agreement, but arb_cents is bounded to +/-2^40, so the i64::MIN arm of reverse_target's match never ran: the bridge compared two answers, never a refusal. The edge strategy now includes i64::MIN and i64::MAX, and the None arm is checked: at least one amount is i64::MIN, and Decimal (which can hold the negation) answers the exact opposite. The docs say that plainly instead of claiming the two types refuse the same values. Co-Authored-By: DeepSeek V4.1 Flash --- .../tests/kernel_bridge/entries.rs | 40 +++++++++++++++---- docs/proofs/entries.md | 9 +++-- 2 files changed, 38 insertions(+), 11 deletions(-) diff --git a/crates/ledger-core/tests/kernel_bridge/entries.rs b/crates/ledger-core/tests/kernel_bridge/entries.rs index 40bcf6a9..466f16e8 100644 --- a/crates/ledger-core/tests/kernel_bridge/entries.rs +++ b/crates/ledger-core/tests/kernel_bridge/entries.rs @@ -39,6 +39,13 @@ fn arb_direction() -> impl Strategy { ] } +/// 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 { + prop_oneof![arb_cents(), Just(i64::MIN), Just(i64::MAX)] +} + proptest! { #![proptest_config(ProptestConfig::with_cases(1000))] @@ -121,12 +128,15 @@ proptest! { } /// `kernel::reverse_target` is the exact opposite at both types, and - /// each refuses the same out-of-range inputs (law 24). + /// `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_cents(), - cash in arb_cents(), - in_kind in arb_cents(), + amount in arb_edge_cents(), + cash in arb_edge_cents(), + in_kind in arb_edge_cents(), direction in arb_direction(), ) { let t = kernel::PartyTarget { @@ -147,10 +157,24 @@ proptest! { cash: dec(r.cash), in_kind: dec(r.in_kind), }; - prop_assert_eq!( - kernel::reverse_target(t).map(as_dec), - kernel::reverse_target(d) - ); + 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 diff --git a/docs/proofs/entries.md b/docs/proofs/entries.md index 86efac50..930aeb56 100644 --- a/docs/proofs/entries.md +++ b/docs/proofs/entries.md @@ -45,9 +45,12 @@ verification, 3 covers, build included). - `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 and refuses the same out-of-range inputs (law 24). The earlier - bridge only passed it to `and_then`, which is a mention, not a call; this - property calls it. + 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 From cc8526ae074cf6465e050e8839b92051a1a4e9eb Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 22:35:42 -0700 Subject: [PATCH 22/26] perf(core): the gate builds its index once The four tests each rebuilt the full index (every source file, every claim, the rule records): a fresh scan apiece spent seconds re-reading the same tree. One OnceLock now holds it for the file. build_definitions also re-reads each file once per type it defines and makes a second full pass; it now reads each file once into a map and reuses that text for the module scan, the variants and fields, and the test names. Co-Authored-By: DeepSeek V4.1 Flash --- .../tests/bookspec/traceability.rs | 76 +++++++++++-------- 1 file changed, 46 insertions(+), 30 deletions(-) diff --git a/crates/ledger-core/tests/bookspec/traceability.rs b/crates/ledger-core/tests/bookspec/traceability.rs index a3ba16fc..cf905009 100644 --- a/crates/ledger-core/tests/bookspec/traceability.rs +++ b/crates/ledger-core/tests/bookspec/traceability.rs @@ -1334,7 +1334,7 @@ fn resolve( if !exists { return Err(format!("path {head} does not exist")); } - return resolve(item, &defs, &bases, &all_paths); + return resolve(item, defs, bases, all_paths); } } if is_path_like(token) { @@ -1366,7 +1366,7 @@ fn resolve( if item.is_empty() { continue; } - classes.push(resolve(&format!("{prefix}{item}"), &defs, &bases, &all_paths)?); + classes.push(resolve(&format!("{prefix}{item}"), defs, bases, all_paths)?); } if classes.is_empty() { return Err(format!("empty brace group {token}")); @@ -1393,7 +1393,7 @@ fn resolve( return Ok(Class::LeanTheorem); } if token.contains("::") { - return resolve_qualified(token, &defs, &bases, &all_paths); + return resolve_qualified(token, defs, bases, all_paths); } // A harness before an item: a proof function is never an ordinary item, // so deleting its `#[kani::proof]` attribute leaves the claim unbacked. @@ -1504,7 +1504,7 @@ fn resolve_qualified( return Err(format!("{token} names no item")); }; if segments.len() == 1 { - return resolve(item, &defs, &bases, &all_paths); + return resolve(item, defs, bases, all_paths); } let container = segments[segments.len() - 2]; let candidates: Vec<&str> = match krate { @@ -2012,23 +2012,31 @@ fn collect_paths(root: &Path, dir: &Path, out: &mut Vec) { } } -fn main_index(root: &Path) -> (Definitions, Vec, Vec) { - let mut defs = build_definitions(root); - // Product rule ids and their counts, so duplicates are caught. - for path in claims_files(root) { - let text = read(&path); - for (id, _) in wb_sections(&text) { - *defs.product_rules.entry(id).or_insert(0) += 1; +/// The whole index, built once for every test in this file: the four +/// tests read the same tree, and a fresh scan apiece spent seconds +/// re-reading it. +fn main_index() -> &'static (Definitions, Vec, Vec) { + static INDEX: std::sync::OnceLock<(Definitions, Vec, Vec)> = + std::sync::OnceLock::new(); + INDEX.get_or_init(|| { + let root = repo_root(); + let mut defs = build_definitions(&root); + // Product rule ids and their counts, so duplicates are caught. + for path in claims_files(&root) { + let text = read(&path); + for (id, _) in wb_sections(&text) { + *defs.product_rules.entry(id).or_insert(0) += 1; + } } - } - let (bases, paths) = index_paths(root); - (defs, bases, paths) + let (bases, paths) = index_paths(&root); + (defs, bases, paths) + }) } #[test] fn every_claim_is_backed() { let root = repo_root(); - let (defs, bases, all_paths) = main_index(&root); + let (defs, bases, all_paths) = main_index(); assert!( !defs.rules.is_empty(), @@ -2091,7 +2099,7 @@ fn every_claim_is_backed() { } for token in backticks(value) { tokens_seen += 1; - match resolve(&token, &defs, &bases, &all_paths) { + match resolve(&token, defs, bases, all_paths) { Ok(class) => *counts.entry(class).or_insert(0) += 1, Err(error) => failures.push(format!( "{file}: {heading}: {name}: backtick `{token}`: {error}" @@ -2116,7 +2124,7 @@ fn every_claim_is_backed() { } for token in backticks(value) { tokens_seen += 1; - match resolve(&token, &defs, &bases, &all_paths) { + match resolve(&token, defs, bases, all_paths) { Ok(class) => *counts.entry(class).or_insert(0) += 1, Err(error) => failures .push(format!("{file}: {id}: {name}: backtick `{token}`: {error}")), @@ -2533,8 +2541,7 @@ const SKIPPED: &[&str] = &[ #[test] fn made_up_names_do_not_resolve() { - let root = repo_root(); - let (defs, bases, all_paths) = main_index(&root); + let (defs, bases, all_paths) = main_index(); for token in [ "no_such_fn_xyz", "NoSuch.theorem", @@ -2550,15 +2557,26 @@ fn made_up_names_do_not_resolve() { "books.add", // A Lean name that is not audited, with or without the prefix. "Bookspec.NoSuch.theorem", + // An imported type's item outside the explicit external list. + "NaiveDate::NoSuchThing", + // A real type and item behind a middle segment that is no module. + "bogus::Ledger::post_entry", + "bogus::form1099::untagged_payments", ] { assert!( - resolve(token, &defs, &bases, &all_paths).is_err(), + resolve(token, defs, bases, all_paths).is_err(), "made-up name `{token}` must not resolve" ); } - // A directory is not a crate (`tests` resolves only as `mod tests`). + // A directory is not a crate: bare `tests` resolves as a Rust item + // (`mod tests` in several src files), never as a crate. + assert_eq!( + resolve("tests", defs, bases, all_paths), + Ok(Class::RustItem), + "bare `tests` is a module, not a crate" + ); assert!( - !is_crate_name("tests", &defs), + !is_crate_name("tests", defs), "a directory name must not pass as a crate" ); } @@ -2589,8 +2607,7 @@ fn calls_finds_a_call_not_a_mention() { /// of `Iif` never backs `TaxSummary::…`, nor the reverse. #[test] fn a_field_belongs_to_its_own_type() { - let root = repo_root(); - let (defs, bases, all_paths) = main_index(&root); + let (defs, bases, all_paths) = main_index(); for token in [ "Iif::changes", "Iif::receivable_payable", @@ -2598,14 +2615,14 @@ fn a_field_belongs_to_its_own_type() { "TaxSummary::form_4797", ] { assert_eq!( - resolve(token, &defs, &bases, &all_paths), + resolve(token, defs, bases, all_paths), Ok(Class::RustItem), "`{token}` is a real item of its type" ); } for token in ["Iif::form_4797", "TaxSummary::changes"] { assert!( - resolve(token, &defs, &bases, &all_paths).is_err(), + resolve(token, defs, bases, all_paths).is_err(), "`{token}` is a field of the other type and must not resolve" ); } @@ -2624,15 +2641,14 @@ fn a_harness_listed_twice_must_agree() { #[test] fn harnesses_resolve_only_as_proofs() { - let root = repo_root(); - let (defs, bases, all_paths) = main_index(&root); + let (defs, bases, all_paths) = main_index(); let harness = defs .harnesses .iter() .next() .expect("the proofs carry harnesses"); assert_eq!( - resolve(harness, &defs, &bases, &all_paths), + resolve(harness, defs, bases, all_paths), Ok(Class::KaniHarness), "a harness classifies as a Kani harness" ); @@ -2642,7 +2658,7 @@ fn harnesses_resolve_only_as_proofs() { "the helper is not a harness" ); assert_ne!( - resolve("any_proration", &defs, &bases, &all_paths).ok(), + resolve("any_proration", defs, bases, all_paths).ok(), Some(Class::KaniHarness), "a proof helper without `#[kani::proof]` is not a harness" ); From 47502999d033880c0de6081efc78c6d77e50a2fd Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 23:14:01 -0700 Subject: [PATCH 23/26] build: pin bookspec at 00b7c54, payments and the aging, and audit_lean bookspec main now carries X-H1a (a payment event, terms, the aging and due-date queries, their examples; an example names the option it rests on, and a claimed CHOICE declares its pick) and X-J's half (audit_lean, the audited theorem list an engine checks its claims against). The checker and the Lean move together (tests/bookspec/pin.rs): Lean 177 theorems, standard axioms only; 71 of 76 examples run and pass, the five others are for options wanderbooks did not pick. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 4 ++-- crates/ledger-core/Cargo.toml | 4 ++-- crates/ledger-package/Cargo.toml | 2 +- verify/lean/lake-manifest.json | 4 ++-- verify/lean/lakefile.toml | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5d0aa248..d3ea2ca8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", diff --git a/crates/ledger-core/Cargo.toml b/crates/ledger-core/Cargo.toml index c3ecffd2..db8ab7d5 100644 --- a/crates/ledger-core/Cargo.toml +++ b/crates/ledger-core/Cargo.toml @@ -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" } diff --git a/crates/ledger-package/Cargo.toml b/crates/ledger-package/Cargo.toml index 8e3979bd..ee770c16 100644 --- a/crates/ledger-package/Cargo.toml +++ b/crates/ledger-package/Cargo.toml @@ -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" diff --git a/verify/lean/lake-manifest.json b/verify/lean/lake-manifest.json index f4e385bf..8afdfa6d 100644 --- a/verify/lean/lake-manifest.json +++ b/verify/lean/lake-manifest.json @@ -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", diff --git a/verify/lean/lakefile.toml b/verify/lean/lakefile.toml index 859694b1..6ad0fa56 100644 --- a/verify/lean/lakefile.toml +++ b/verify/lean/lakefile.toml @@ -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]] From 946777628f1f74be2598773ff411cc9cd24f2ce1 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 23:22:49 -0700 Subject: [PATCH 24/26] docs(claims): name what the aging examples rest on in words The traceability gate refused `under` in B-18's checked line: it is the key bookspec's examples use to name the option they rest on, not a name in wanderbooks, so it resolves to nothing here. The sentence now says it in words. Found when X-J's gate first read X-H1a's claims. Co-Authored-By: Claude Opus 5.5 --- docs/spec/claims/arap.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/spec/claims/arap.md b/docs/spec/claims/arap.md index 7bf8e902..0e7e0b1a 100644 --- a/docs/spec/claims/arap.md +++ b/docs/spec/claims/arap.md @@ -35,8 +35,8 @@ 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 them (`under`) and the -runner skips them for the pick above. +`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 From b304fc9a9a12c3c214c22cf7ae0c3c29090e4520 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 23:24:40 -0700 Subject: [PATCH 25/26] docs(plan): X-H1e makes BS-prepaid-2's examples depend on its pick Found in X-H1a's re-check: every schedule event names its convention, so no schedule example depends on the engine's BS-prepaid-2 pick, and for whole months from the 1st the daily and equal-months methods agree. The fix is a schedule that takes the engine's method, with a mid-month start, where the two differ. Co-Authored-By: Claude Opus 5.5 --- plan/p14-bookspec.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plan/p14-bookspec.md b/plan/p14-bookspec.md index bf2e8169..abd7c59d 100644 --- a/plan/p14-bookspec.md +++ b/plan/p14-bookspec.md @@ -74,7 +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). 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-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 | From f5ad691b80fdb2a75a147af9666fc6d62a58c2c6 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 9 Nov 2026 01:03:52 -0700 Subject: [PATCH 26/26] docs(plan): K-U10 carries the exact tie-break, an owner decision K-U3's review found the split ranks remainders by a rounded quotient, so a tie goes where the 28th digit sends it. Making it exact moves a cent between parties in recomputed past reports, so it is put to the owner with the cents it moves; K-U3 keeps today's behaviour and pins it. Co-Authored-By: Claude Opus 5.5 --- plan/p14-bookspec.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plan/p14-bookspec.md b/plan/p14-bookspec.md index abd7c59d..ca9b1518 100644 --- a/plan/p14-bookspec.md +++ b/plan/p14-bookspec.md @@ -83,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/.rs`, `proofs/.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 |