diff --git a/AGENTS.md b/AGENTS.md index 1882a789..77b678be 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -224,6 +224,7 @@ clone, with status. Rules: | `docs/spec/claims/` | Wanderbooks' claims on each bookspec rule: the CHOICE picked, where the engine enforces it, which tests check it, and product rules `WB--` | | https://git.swaits.com/swaits/bookspec | Where the rules live (D-68): `rules/` records, `spec/rules/` reading pages, `spec/rules-index.md`; every rule is `BS--` | | `docs/verification.md` | The formal proofs: every accounting law, its Kani harness and Lean theorem, what they found | +| `docs/command-steps.md` | Which step of bookspec's Lean model each `Ledger` command is, and which commands the proofs do not cover | | `docs/parity.md` | Feature catalog and the non-regression floor | | `docs/capability-parity.md` | Parity vs the GSheet+GDrive system + the cutover rule | | `docs/mcp-interface.md` | The MCP tool surface: the primary interface spec | diff --git a/crates/ledger-core/tests/command_steps.rs b/crates/ledger-core/tests/command_steps.rs new file mode 100644 index 00000000..a22ddff3 --- /dev/null +++ b/crates/ledger-core/tests/command_steps.rs @@ -0,0 +1,151 @@ +//! `docs/command-steps.md` lists every command on `Ledger`, with the step +//! of bookspec's Lean model it is. +//! +//! bookspec proves its laws for every state a `Step` reaches. A command +//! that changes the books and is no step is outside those proofs, so the +//! page has to name every command, and a new one has to be placed (or +//! written down as not covered) before it ships. This test reads the +//! source and the page and fails when they differ. + +use std::collections::{BTreeMap, BTreeSet}; + +const SOURCE: &str = include_str!("../src/ledger.rs"); +const PAGE: &str = include_str!("../../../docs/command-steps.md"); + +/// The steps of the two models (`Bookspec.Step`, `Bookspec.Documents.Step`), +/// and `none` for a command that is no step. +const STEPS: &[&str] = &[ + "addAccount", + "draft", + "post", + "reverse", + "openPeriod", + "close", + "closeToRetained", + "discard", + "record", + "document", + "doc.reverse", + "writeOff", + "assign", + "release", + "markSent", + "none", +]; + +/// The commands that are no step of the model. Adding one here is +/// admitting a hole in what the proofs cover: the page says what closes it. +const NO_STEP: &[&str] = &["renumber_account"]; + +/// Every `pub fn` of `impl Ledger` that takes `&mut self`, by name. +fn commands() -> BTreeSet { + let start = SOURCE + .find("\nimpl Ledger {") + .expect("ledger.rs has one `impl Ledger {`"); + // The block ends at the first line that is a lone closing brace. + let body = &SOURCE[start + 1..]; + let end = body.find("\n}\n").expect("the impl block closes"); + let lines: Vec<&str> = body[..end].lines().collect(); + let mut found = BTreeSet::new(); + for (i, line) in lines.iter().enumerate() { + let Some(rest) = line.strip_prefix(" pub fn ") else { + continue; + }; + let name: String = rest + .chars() + .take_while(|c| c.is_alphanumeric() || *c == '_') + .collect(); + // The signature runs to the line that opens the body. + let signature: String = lines[i..] + .iter() + .take_while(|l| !l.trim_end().ends_with('{')) + .chain(lines[i..].iter().find(|l| l.trim_end().ends_with('{'))) + .copied() + .collect::>() + .join(" "); + if signature.contains("&mut self") { + found.insert(name); + } + } + found +} + +/// The page's table: command to its steps. +fn rows() -> BTreeMap> { + let table = PAGE + .split("## Every command") + .nth(1) + .expect("the page has the section `## Every command`"); + let mut rows = BTreeMap::new(); + for line in table.lines() { + let cells: Vec<&str> = line.split('|').map(str::trim).collect(); + // `| `name` | steps | note |` splits into ["", name, steps, note, ""]. + if cells.len() < 4 || !cells[1].starts_with('`') { + continue; + } + let name = cells[1].trim_matches('`').to_string(); + let steps = cells[2].split(',').map(|s| s.trim().to_string()).collect(); + assert!( + rows.insert(name.clone(), steps).is_none(), + "docs/command-steps.md lists `{name}` twice" + ); + } + rows +} + +/// Every command has a row, and every row a command. +#[test] +fn every_command_is_on_the_page() { + let commands = commands(); + assert!( + commands.len() > 100, + "found only {} commands: the reader of ledger.rs is broken", + commands.len() + ); + let listed: BTreeSet = rows().into_keys().collect(); + let missing: Vec<_> = commands.difference(&listed).collect(); + let stale: Vec<_> = listed.difference(&commands).collect(); + assert!( + missing.is_empty() && stale.is_empty(), + "docs/command-steps.md and `impl Ledger` differ.\n\ + Commands with no row (add one, with the model's step it is, or a \ + new `Step` in bookspec): {missing:?}\n\ + Rows with no command (remove them): {stale:?}" + ); +} + +/// Every row names steps the model has. +#[test] +fn every_row_names_a_step_of_the_model() { + for (command, steps) in rows() { + assert!(!steps.is_empty(), "`{command}` names no step"); + for step in &steps { + assert!( + STEPS.contains(&step.as_str()), + "`{command}` names `{step}`, which is no step of the model" + ); + } + } +} + +/// The commands that are no step are the ones written down, and no others. +#[test] +fn the_commands_outside_the_model_are_the_ones_named() { + let outside: BTreeSet = rows() + .into_iter() + .filter(|(_, steps)| steps.iter().any(|s| s == "none")) + .map(|(command, _)| command) + .collect(); + let named: BTreeSet = NO_STEP.iter().map(|s| s.to_string()).collect(); + assert_eq!( + outside, named, + "a command marked `none` on the page must be in NO_STEP, and the \ + page's \"No step\" section must say what closes it" + ); + for (command, steps) in rows() { + assert!( + steps.len() == 1 || !steps.iter().any(|s| s == "none"), + "`{command}` is `none` and a step at once" + ); + } +} diff --git a/docs/command-steps.md b/docs/command-steps.md new file mode 100644 index 00000000..23bfedbc --- /dev/null +++ b/docs/command-steps.md @@ -0,0 +1,244 @@ +# Commands and steps: what the Lean model covers + +bookspec's Lean proves its laws about the books over time for every state +`Reachable` from empty books by a `Step`. The engine changes the books +through 119 public commands on `Ledger`. This page maps each command to +the step or steps it is, so "every reachable state" can be read for what +it covers, and names what it does not. + +The map is kept whole by a test +(`crates/ledger-core/tests/command_steps.rs`): a public command on +`Ledger` that takes `&mut self` and has no row here fails the build, and +so does a row for a command that is gone. A new command gets a row, and +if it is not one of the model's steps, a new `Step` in bookspec with its +preservation proof (AGENTS.md, formal methods, item 3). + +## The model's steps + +Two models run side by side (bookspec `lean/Bookspec/Exec/Doc.lean`, +"Composition"): the ledger (the chart, the posted log, drafts, periods) +and the documents (tagged lines, control accounts, sends). + +| Step | Model | What it is | +|---|---|---| +| `addAccount` | ledger | a new account, its code not taken | +| `draft` | ledger | a draft entry (and a line added to one), not in a closed period | +| `post` | ledger | a draft posted: balanced, on known accounts, not in a closed period | +| `reverse` | ledger | a posted entry's mirror, at most once, never a close, not dated before the original | +| `openPeriod` | ledger | a period that nests with or lies apart from every other | +| `close`, `closeToRetained` | ledger | an open period closed, in order, with no draft in it | +| `discard` | ledger | a draft removed | +| `record` | ledger | a record of how the books are kept: no account, entry or period changes | +| `document` | documents | lines posted with their documents (an invoice, a bill, a settlement) | +| `doc.reverse` | documents | the mirror of lines that carry documents | +| `writeOff` | documents | a write-off, above zero and at most what is owed | +| `assign`, `release` | documents | an account takes or gives up a control role | +| `markSent` | documents | a send recorded on an invoice | + +## What the map is, and is not + +- **A reading, checked two ways, proved in neither.** No proof ties a + Rust command to a Lean step. Two machine checks do: bookspec's examples + (the engine answers each recorded command as the record says), and the + differential test `crates/ledger-core/tests/bookspec/lean_model.rs`, + which runs random command sequences through the engine and the Lean + model and compares every figure and refusal. That test reaches an entry + drafted and posted, a reversal, a close to retained earnings, an + invoice and a bill. It does not reach a standalone `openPeriod`, a close + with explicit targets, a draft left unposted (so `discard`), or an + account added after the first event; those are by review. +- **`record` covers 71 commands.** They change nothing the ledger model + keeps, so every law about balances, statements and periods holds across + them with nothing to prove. Some keep a register with rules of its own + (the note says which); see "Registers" below. +- **Several steps in one command** run inside `Ledger::atomically`: all + of them happen or none does. + +## Not covered + +### No step: `renumber_account` + +The model's chart is a list of codes, and its lines name accounts by +code. The engine's lines name accounts by id, and a renumber changes one +code and no entry. In the model that is a renaming of one code across the +chart and the log, which no step does. The engine refuses a taken code +(`check_renumber_account`), so codes stay distinct, and its tests check +that no balance moves; neither is a theorem. Closes with a `renumber` +step in bookspec: codes stay distinct, and every balance is the old one +under the new code. + +### Doors: 17 commands that take what an older version wrote + +A journal line an older version accepted must replay (BS-entry-4), so +each rule added later has a door beside the command: the same change +without the newer check. A store calls a door only for a line its journal +already holds. Most drop checks the model does not carry (a size bound, a +minor unit, a text rule). Four drop one the model's step requires: + +| Door | The step's condition it does not check | +|---|---| +| `create_entry` | `draft`: the date is in no closed period | +| `replay_generate_recurring` | `draft`: the same | +| `replay_create_period` | `openPeriod`: no partial overlap | +| `replay_reverse_entry` | `reverse`: the reversal is not dated before the original | + +So books replayed from a journal written before those rules can stand in +a state the model does not reach, and a caller of the engine that uses a +door for new work can put them there. What still holds, read from the +proofs: the preservation of `Inv.distinct`, `Inv.accepted` and +`Inv.known` (distinct codes, every posted entry balanced and on known +accounts) uses none of the four conditions, so the trial balance and the +accounting equation hold in those books too. `Inv.draftsOpen` (no draft +in a closed period) does not. That reading is not yet a theorem. Closes +with: a `ReplayStep` relation in bookspec (the steps without the four +conditions) and the proof that the three invariants hold in every state +it reaches. + +`create_entry` is a door by its doc comment only: its name does not say +so, and it is public. The store calls `try_create_entry` first. + +### Registers: state with rules of its own + +These are `record` to the ledger model. Their arithmetic is proved as +functions (bookspec `Schedule`, `Prorate`, `Deductible`, `Payroll`, +`Apportion`); how they change over time is tested, not modelled: + +- **Fixed assets**: registered, corrected, linked to an acquisition, + depreciated by runs, disposed once. +- **Schedules**: a month posts at most once while its posting stands, and + is due again when that posting is reversed. +- **Recurring entries**: an occurrence is generated at most once. +- **Payroll runs**: a run is recorded with the entry that posted it. + +### The pair is one set of books by construction + +bookspec says so itself (`Exec/Doc.lean`): that the documents' lines are +exactly the ledger's posted lines is kept by how the runner is built, not +proved. The engine's side of the same fact is `Ledger::atomically` and +the control check (`Ledger::control_check`), which are tested. + +## Every command + +In source order. "door" in a note marks a command that exists for replay. + +| Command | Step | Note | +|---|---|---| +| `register_schedule` | record | register: schedules | +| `register_schedule_under` | record | register: schedules | +| `replay_register_schedule` | record | register: schedules | +| `replay_register_schedule_under` | record | register: schedules | +| `post_schedule_month` | draft, post, record | register: schedules (the month is marked posted) | +| `register_recurring` | record | register: recurring entries | +| `replay_register_recurring` | record | register: recurring entries | +| `generate_recurring` | draft, record | register: recurring entries (the occurrence is marked generated) | +| `replay_generate_recurring` | draft, record | door: no closed-period check; register: recurring entries | +| `add_account` | addAccount | | +| `add_control_account` | addAccount | | +| `replay_add_account` | addAccount | door: without the child-type and blank-text rules; a taken code is still refused | +| `renumber_account` | none | changes a code the chart holds; see "No step" | +| `rename_account` | record | | +| `replay_rename_account` | record | | +| `assign_role` | assign, release | `None` is the release | +| `set_account_tax` | record | | +| `create_entry` | draft | door: no closed-period check (replay, and the engine's own entries, which post at once) | +| `try_create_entry` | draft | | +| `add_line` | draft | | +| `replay_add_line` | draft | door: without the account check and the size bound; the post still refuses | +| `add_line_fx` | draft | | +| `replay_add_line_fx` | draft | door: without the account check and the size bound; the post still refuses | +| `post_entry` | post | | +| `replay_post_entry` | post | door: without the minor-unit check | +| `set_draft_state` | record | a note on a draft: no line moves | +| `replay_set_draft_state` | record | a note on a draft: no line moves | +| `discard_draft` | discard | | +| `replay_discard_draft` | discard | | +| `note_entry_origin` | record | what posted an entry, and its journal line | +| `expect_posted_seq` | record | what posted an entry, and its journal line | +| `stamp_unstamped` | record | what posted an entry, and its journal line | +| `reverse_entry` | reverse, doc.reverse | the document step when a line carries a document | +| `replay_reverse_entry` | reverse, doc.reverse | door: without the date order and the document checks | +| `register_asset` | record | register: fixed assets | +| `replay_register_asset` | record | register: fixed assets | +| `set_asset_tag` | record | register: fixed assets | +| `set_asset_serial` | record | register: fixed assets | +| `set_asset_acquisition` | record | register: fixed assets | +| `replay_set_asset_acquisition` | record | register: fixed assets | +| `restore_asset_acquisition` | record | register: fixed assets | +| `set_asset_description` | record | register: fixed assets | +| `set_asset_basis` | record | register: fixed assets | +| `replay_set_asset_basis` | record | register: fixed assets | +| `replay_set_asset_tax_basis` | record | register: fixed assets | +| `correct_asset` | record | register: fixed assets | +| `replay_correct_asset` | record | register: fixed assets | +| `record_depreciation_run` | record | register: fixed assets | +| `dispose_asset` | record | register: fixed assets | +| `replay_dispose_asset` | record | register: fixed assets | +| `create_period` | openPeriod | | +| `replay_create_period` | openPeriod | door: without the nesting rule and the calendar bound | +| `close_period` | addAccount, closeToRetained | the account only when retained earnings has none yet | +| `close_period_to` | addAccount, close | the account only when a target role has none yet | +| `add_customer` | record | | +| `add_vendor` | record | | +| `set_vendor_1099` | record | | +| `replay_vendor_1099` | record | | +| `set_vendor_w9_flag` | record | | +| `add_instrument` | record | | +| `set_entry_instrument` | record | | +| `set_entry_vendor` | record | | +| `add_party` | record | | +| `update_party` | record | | +| `set_party_role` | record | | +| `set_party_w9` | record | | +| `set_party_tin` | record | | +| `set_party_creditor` | record | | +| `set_party_w4` | record | | +| `set_entry_party` | record | | +| `set_entry_parties` | record | | +| `replay_set_entry_parties` | record | | +| `set_entry_no_party` | record | | +| `create_invoice` | addAccount, draft, post, document | the account only when the control role has none yet | +| `create_invoice_with` | addAccount, draft, post, document | the account only when the control role has none yet | +| `create_bill` | addAccount, draft, post, document | the account only when the control role has none yet | +| `create_bill_with` | addAccount, draft, post, document | the account only when the control role has none yet | +| `mark_sent` | markSent | | +| `replay_invoice_sent` | markSent | | +| `settle` | addAccount, draft, post, document | a settlement is a document step (bookspec `settle_posts_a_document_step`) | +| `receive_payment` | addAccount, draft, post, document | a settlement is a document step (bookspec `settle_posts_a_document_step`) | +| `receive_payment_with` | addAccount, draft, post, document | a settlement is a document step (bookspec `settle_posts_a_document_step`) | +| `pay_bill` | addAccount, draft, post, document | a settlement is a document step (bookspec `settle_posts_a_document_step`) | +| `pay_bill_with` | addAccount, draft, post, document | a settlement is a document step (bookspec `settle_posts_a_document_step`) | +| `write_off` | addAccount, draft, post, writeOff | | +| `void_document` | reverse, doc.reverse | | +| `replay_invoice` | document | door: tags the lines of an entry its own events already replayed; nothing is bounded | +| `replay_invoice_with` | document | door: tags the lines of an entry its own events already replayed; nothing is bounded | +| `replay_bill` | document | door: tags the lines of an entry its own events already replayed; nothing is bounded | +| `replay_bill_with` | document | door: tags the lines of an entry its own events already replayed; nothing is bounded | +| `replay_invoice_payment` | document | door: tags the lines of an entry its own events already replayed; nothing is bounded | +| `replay_invoice_payment_at` | document | door: tags the lines of an entry its own events already replayed; nothing is bounded | +| `replay_invoice_write_off` | writeOff | door: as above | +| `replay_bill_payment` | document | door: tags the lines of an entry its own events already replayed; nothing is bounded | +| `replay_bill_payment_at` | document | door: tags the lines of an entry its own events already replayed; nothing is bounded | +| `mark_cleared` | record | | +| `set_fx_rate` | record | | +| `run_payroll` | addAccount, draft, post, record | register: payroll runs | +| `remit_payroll_taxes` | draft, post | | +| `replay_payroll_run` | record | register: payroll runs | +| `apply_settings` | record | | +| `annotate_attachment` | record | | +| `replay_annotate_attachment` | record | | +| `set_entry_settles` | record | | +| `replay_set_entry_settles` | record | | +| `apply_convention` | record | | +| `apply_convention_source` | record | | +| `apply_decision_source` | record | | +| `apply_open_item_source` | record | | +| `apply_retire_convention` | record | | +| `apply_decision` | record | | +| `apply_open_item` | record | | +| `apply_resolve_item` | record | | +| `apply_approval` | record | | +| `add_class` | record | | +| `set_line_class` | record | a note on a draft: no line moves | +| `replay_class` | record | | +| `set_project` | record | | +| `replay_set_project` | record | | diff --git a/docs/testing.md b/docs/testing.md index 4aa7526a..61fdde63 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -21,6 +21,7 @@ promise. | Fault injection (store) | a full disk or a cut-off append leaves whole, openable books (1) | `ledger-store/tests/faults.rs`, `store.rs` (`power_loss_at_any_byte_of_the_last_append_is_recovered`) | `just check` | ~5s | every change | | Concurrency (store) | a viewer reading while the books are written sees only whole books, never a false "differs" (2) | `ledger-store/tests/concurrency.rs` | `just check` | <1s | every change | | Model-based stateful | the Lean state machine, transcribed (3) | `tests/model.rs` | `just check` | ~3s | every change | +| Model coverage | every public command on `Ledger` is named on `docs/command-steps.md` with the step of the Lean model it is, and the commands that are no step are a pinned list (3) | `tests/command_steps.rs` | `just check` | <1s | every change | | Differential: Decimal vs i64 | the kernel at two types (3) | `kernel_bridge/` | `just check` | <1s | every change | | Differential: GnuCash | another implementation, adjudicated (3) | `tests/oracle_gnucash.rs`, bookspec `gnucash/oracle/` | `just oracle` | ~2 min | weekly | | Formal proofs | Kani (bounded) and Lean (unbounded) | `src/proofs/`, `verify/lean/` | `just prove` (51 harnesses and Lean), `just prove-slow` (the 9 in the justfile's `kani_slow`, each under its own 30-minute cap); 60 harnesses in all with the checker canary (2026-10-28) | prove ~5 min and prove-slow ~8 min at four jobs on a quiet laptop (each ~25 min under heavy load; docs/verification.md, "Running it") | weekly (CI runs both) | diff --git a/docs/verification.md b/docs/verification.md index 8d3f629a..a77cc8e7 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -188,6 +188,13 @@ Each step carries the checks the engine makes before it mutates. These theorems hold in **every state reachable from empty books, by any sequence of commands, of any length**: +"Commands" there are the model's steps. Which command of the engine is +which step is `docs/command-steps.md`: 119 commands, of which one +(`renumber_account`) is no step, and 17 are the doors a journal is +replayed through, four of which do not make a check the model's step +requires. That page says what the theorems below do and do not cover for +each, and `tests/command_steps.rs` fails when a command has no row. + 11. **The invariant holds**: chart codes are unique, every posted entry is acceptable and on known accounts, and no draft is dated in a closed period. (That last one is why the store can journal a post before diff --git a/plan/2026-11-09_TRIAGE.md b/plan/2026-11-09_TRIAGE.md index baab39d4..f7def72c 100644 --- a/plan/2026-11-09_TRIAGE.md +++ b/plan/2026-11-09_TRIAGE.md @@ -110,9 +110,26 @@ books. The gaps are in what the gates do not see. (`wanderbooks licenses`; the viewer has no About page yet), with a check in the lint part that it is current. Worker, well specified. 5. **The Lean model of the books covers 14 steps; the Rust `Ledger` has - about 100 commands**, and no list maps one to the other, so "every - reachable state" covers less than it reads. First the inventory - (worker, scout), then the steps that matter (hard implementation). + 119 commands**, and no list mapped one to the other, so "every + reachable state" covered less than it read. The inventory is done + (`docs/command-steps.md`, kept whole by `tests/command_steps.rs`): 71 + commands are the `record` step, 11 are one step, 19 are several steps + run as one, 17 are replay doors and one is no step. What it found, each + closing with Lean in bookspec (hard implementation, then the pin moves): + - `renumber_account` is no step of the model. A `renumber` step: codes + stay distinct, and every balance is the old one under the new code. + - Four doors apply a change without a check the model's step requires + (`create_entry`, `replay_generate_recurring`, `replay_create_period`, + `replay_reverse_entry`), so books replayed from an old journal can be + outside `Reachable`. The laws that rest on distinct codes, acceptable + entries and known accounts still hold, by reading the proofs; a + `ReplayStep` relation and its theorem would make that proved. + - The registers (fixed assets, schedules, recurring entries, payroll + runs) have proved arithmetic and no step model of how they change. + - Nothing proves a Rust command is its Lean step. Two tests check it: + bookspec's examples and the differential test (`lean_model.rs`), + which does not reach a standalone period, a close with explicit + targets, a draft left unposted or an account added late. Extend it. 6. **Coverage is measured only for ledger-core and ledger-store.** 7. **Three allocation preludes are still outside the kernel** (`try_allocate`, `allocate_cumulative`, `tax_capital::split`): they @@ -142,5 +159,5 @@ signing (D-64); the re-audit (P10); Q-6 before P9b. (all four done). 4. One gate at the end (`just check`, `just prove`), one push, four gates read. -5. The command-to-step inventory, the allocation preludes, then bookspec's - examples and second implementation. +5. The steps the inventory found missing (bookspec), the allocation + preludes, then bookspec's examples and second implementation.